code
stringlengths
13
6.09M
order_type
stringclasses
2 values
original_example
dict
step_ids
listlengths
1
5
<|reserved_special_token_0|> class FocalLoss(nn.Module): """https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109""" def __init__(self, gamma=2): super().__init__() self.gamma = gamma def forward(self, logit, target): target = target.float() max_val = (-logit).clamp(min=0) loss = logit - logit * target + max_val + ((-max_val).exp() + (- logit - max_val).exp()).log() invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0)) loss = (invprobs * self.gamma).exp() * loss loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss return loss.mean() <|reserved_special_token_1|> <|reserved_special_token_0|> class FocalLoss1(nn.Module): <|reserved_special_token_0|> def forward(self, logits, label): """[summary] Args: logits ([type]): tensor of shape (N, C, H, W) label ([type]): tensor of shape(N, H, W) Returns: [type]: [description] """ ignore = label.data.cpu() == self.ignore_lb n_valid = (ignore == 0).sum() label[ignore] = 0 ignore = ignore.nonzero() _, M = ignore.size() a, *b = ignore.chunk(M, dim=1) mask = torch.ones_like(logits) mask[[a, torch.arange(mask.size(1)), *b]] = 0 probs = torch.sigmoid(logits) lb_one_hot = logits.data.clone().zero_().scatter_(1, label. unsqueeze(1), 1) pt = torch.where(lb_one_hot == 1, probs, 1 - probs) alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot) loss = -alpha * (1 - pt) ** self.gamma * torch.log(pt + 1e-12) loss[mask == 0] = 0 if self.reduction == 'mean': loss = loss.sum(dim=1).sum() / n_valid return loss class FocalLoss(nn.Module): """https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109""" def __init__(self, gamma=2): super().__init__() self.gamma = gamma def forward(self, logit, target): target = target.float() max_val = (-logit).clamp(min=0) loss = logit - logit * target + max_val + ((-max_val).exp() + (- logit - max_val).exp()).log() invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0)) loss = (invprobs * self.gamma).exp() * loss loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss return loss.mean() <|reserved_special_token_1|> <|reserved_special_token_0|> class FocalLoss1(nn.Module): def __init__(self, alpha=0.25, gamma=2, reduction='mean', ignore_lb=255): super().__init__() self.alpha = alpha self.gamma = gamma self.reduction = reduction self.ignore_lb = ignore_lb def forward(self, logits, label): """[summary] Args: logits ([type]): tensor of shape (N, C, H, W) label ([type]): tensor of shape(N, H, W) Returns: [type]: [description] """ ignore = label.data.cpu() == self.ignore_lb n_valid = (ignore == 0).sum() label[ignore] = 0 ignore = ignore.nonzero() _, M = ignore.size() a, *b = ignore.chunk(M, dim=1) mask = torch.ones_like(logits) mask[[a, torch.arange(mask.size(1)), *b]] = 0 probs = torch.sigmoid(logits) lb_one_hot = logits.data.clone().zero_().scatter_(1, label. unsqueeze(1), 1) pt = torch.where(lb_one_hot == 1, probs, 1 - probs) alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot) loss = -alpha * (1 - pt) ** self.gamma * torch.log(pt + 1e-12) loss[mask == 0] = 0 if self.reduction == 'mean': loss = loss.sum(dim=1).sum() / n_valid return loss class FocalLoss(nn.Module): """https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109""" def __init__(self, gamma=2): super().__init__() self.gamma = gamma def forward(self, logit, target): target = target.float() max_val = (-logit).clamp(min=0) loss = logit - logit * target + max_val + ((-max_val).exp() + (- logit - max_val).exp()).log() invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0)) loss = (invprobs * self.gamma).exp() * loss loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss return loss.mean() <|reserved_special_token_1|> import torch import torch.nn as nn from torch.nn import functional as F class FocalLoss1(nn.Module): def __init__(self, alpha=0.25, gamma=2, reduction='mean', ignore_lb=255): super().__init__() self.alpha = alpha self.gamma = gamma self.reduction = reduction self.ignore_lb = ignore_lb def forward(self, logits, label): """[summary] Args: logits ([type]): tensor of shape (N, C, H, W) label ([type]): tensor of shape(N, H, W) Returns: [type]: [description] """ ignore = label.data.cpu() == self.ignore_lb n_valid = (ignore == 0).sum() label[ignore] = 0 ignore = ignore.nonzero() _, M = ignore.size() a, *b = ignore.chunk(M, dim=1) mask = torch.ones_like(logits) mask[[a, torch.arange(mask.size(1)), *b]] = 0 probs = torch.sigmoid(logits) lb_one_hot = logits.data.clone().zero_().scatter_(1, label. unsqueeze(1), 1) pt = torch.where(lb_one_hot == 1, probs, 1 - probs) alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot) loss = -alpha * (1 - pt) ** self.gamma * torch.log(pt + 1e-12) loss[mask == 0] = 0 if self.reduction == 'mean': loss = loss.sum(dim=1).sum() / n_valid return loss class FocalLoss(nn.Module): """https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109""" def __init__(self, gamma=2): super().__init__() self.gamma = gamma def forward(self, logit, target): target = target.float() max_val = (-logit).clamp(min=0) loss = logit - logit * target + max_val + ((-max_val).exp() + (- logit - max_val).exp()).log() invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0)) loss = (invprobs * self.gamma).exp() * loss loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss return loss.mean() <|reserved_special_token_1|> import torch import torch.nn as nn from torch.nn import functional as F class FocalLoss1(nn.Module): def __init__(self, alpha=0.25, gamma=2, reduction='mean', ignore_lb=255): super().__init__() self.alpha = alpha self.gamma = gamma self.reduction = reduction self.ignore_lb = ignore_lb def forward(self, logits, label): """[summary] Args: logits ([type]): tensor of shape (N, C, H, W) label ([type]): tensor of shape(N, H, W) Returns: [type]: [description] """ # overcome ignored label ignore = label.data.cpu() == self.ignore_lb n_valid = (ignore == 0).sum() label[ignore] = 0 ignore = ignore.nonzero() _, M = ignore.size() a, *b = ignore.chunk(M, dim=1) mask = torch.ones_like(logits) mask[[a, torch.arange(mask.size(1)), *b]] = 0 # compute loss probs = torch.sigmoid(logits) lb_one_hot = logits.data.clone().zero_().scatter_(1, label.unsqueeze(1), 1) pt = torch.where(lb_one_hot == 1, probs, 1 - probs) alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot) loss = -alpha * ((1 - pt)**self.gamma) * torch.log(pt + 1e-12) loss[mask == 0] = 0 if self.reduction == 'mean': loss = loss.sum(dim=1).sum() / n_valid return loss class FocalLoss(nn.Module): """https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109""" def __init__(self, gamma=2): super().__init__() self.gamma = gamma def forward(self, logit, target): target = target.float() max_val = (-logit).clamp(min=0) loss = logit - logit * target + max_val + ((-max_val).exp() + (-logit - max_val).exp()).log() invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0)) loss = (invprobs * self.gamma).exp() * loss loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss return loss.mean()
flexible
{ "blob_id": "9e9303d58c7e091bf7432060fad292c16ecf85ee", "index": 9280, "step-1": "<mask token>\n\n\nclass FocalLoss(nn.Module):\n \"\"\"https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109\"\"\"\n\n def __init__(self, gamma=2):\n super().__init__()\n self.gamma = gamma\n\n def forward(self, logit, target):\n target = target.float()\n max_val = (-logit).clamp(min=0)\n loss = logit - logit * target + max_val + ((-max_val).exp() + (-\n logit - max_val).exp()).log()\n invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0))\n loss = (invprobs * self.gamma).exp() * loss\n loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss\n return loss.mean()\n", "step-2": "<mask token>\n\n\nclass FocalLoss1(nn.Module):\n <mask token>\n\n def forward(self, logits, label):\n \"\"\"[summary]\n \n Args:\n logits ([type]): tensor of shape (N, C, H, W)\n label ([type]): tensor of shape(N, H, W)\n \n Returns:\n [type]: [description]\n \"\"\"\n ignore = label.data.cpu() == self.ignore_lb\n n_valid = (ignore == 0).sum()\n label[ignore] = 0\n ignore = ignore.nonzero()\n _, M = ignore.size()\n a, *b = ignore.chunk(M, dim=1)\n mask = torch.ones_like(logits)\n mask[[a, torch.arange(mask.size(1)), *b]] = 0\n probs = torch.sigmoid(logits)\n lb_one_hot = logits.data.clone().zero_().scatter_(1, label.\n unsqueeze(1), 1)\n pt = torch.where(lb_one_hot == 1, probs, 1 - probs)\n alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot)\n loss = -alpha * (1 - pt) ** self.gamma * torch.log(pt + 1e-12)\n loss[mask == 0] = 0\n if self.reduction == 'mean':\n loss = loss.sum(dim=1).sum() / n_valid\n return loss\n\n\nclass FocalLoss(nn.Module):\n \"\"\"https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109\"\"\"\n\n def __init__(self, gamma=2):\n super().__init__()\n self.gamma = gamma\n\n def forward(self, logit, target):\n target = target.float()\n max_val = (-logit).clamp(min=0)\n loss = logit - logit * target + max_val + ((-max_val).exp() + (-\n logit - max_val).exp()).log()\n invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0))\n loss = (invprobs * self.gamma).exp() * loss\n loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss\n return loss.mean()\n", "step-3": "<mask token>\n\n\nclass FocalLoss1(nn.Module):\n\n def __init__(self, alpha=0.25, gamma=2, reduction='mean', ignore_lb=255):\n super().__init__()\n self.alpha = alpha\n self.gamma = gamma\n self.reduction = reduction\n self.ignore_lb = ignore_lb\n\n def forward(self, logits, label):\n \"\"\"[summary]\n \n Args:\n logits ([type]): tensor of shape (N, C, H, W)\n label ([type]): tensor of shape(N, H, W)\n \n Returns:\n [type]: [description]\n \"\"\"\n ignore = label.data.cpu() == self.ignore_lb\n n_valid = (ignore == 0).sum()\n label[ignore] = 0\n ignore = ignore.nonzero()\n _, M = ignore.size()\n a, *b = ignore.chunk(M, dim=1)\n mask = torch.ones_like(logits)\n mask[[a, torch.arange(mask.size(1)), *b]] = 0\n probs = torch.sigmoid(logits)\n lb_one_hot = logits.data.clone().zero_().scatter_(1, label.\n unsqueeze(1), 1)\n pt = torch.where(lb_one_hot == 1, probs, 1 - probs)\n alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot)\n loss = -alpha * (1 - pt) ** self.gamma * torch.log(pt + 1e-12)\n loss[mask == 0] = 0\n if self.reduction == 'mean':\n loss = loss.sum(dim=1).sum() / n_valid\n return loss\n\n\nclass FocalLoss(nn.Module):\n \"\"\"https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109\"\"\"\n\n def __init__(self, gamma=2):\n super().__init__()\n self.gamma = gamma\n\n def forward(self, logit, target):\n target = target.float()\n max_val = (-logit).clamp(min=0)\n loss = logit - logit * target + max_val + ((-max_val).exp() + (-\n logit - max_val).exp()).log()\n invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0))\n loss = (invprobs * self.gamma).exp() * loss\n loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss\n return loss.mean()\n", "step-4": "import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\n\nclass FocalLoss1(nn.Module):\n\n def __init__(self, alpha=0.25, gamma=2, reduction='mean', ignore_lb=255):\n super().__init__()\n self.alpha = alpha\n self.gamma = gamma\n self.reduction = reduction\n self.ignore_lb = ignore_lb\n\n def forward(self, logits, label):\n \"\"\"[summary]\n \n Args:\n logits ([type]): tensor of shape (N, C, H, W)\n label ([type]): tensor of shape(N, H, W)\n \n Returns:\n [type]: [description]\n \"\"\"\n ignore = label.data.cpu() == self.ignore_lb\n n_valid = (ignore == 0).sum()\n label[ignore] = 0\n ignore = ignore.nonzero()\n _, M = ignore.size()\n a, *b = ignore.chunk(M, dim=1)\n mask = torch.ones_like(logits)\n mask[[a, torch.arange(mask.size(1)), *b]] = 0\n probs = torch.sigmoid(logits)\n lb_one_hot = logits.data.clone().zero_().scatter_(1, label.\n unsqueeze(1), 1)\n pt = torch.where(lb_one_hot == 1, probs, 1 - probs)\n alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot)\n loss = -alpha * (1 - pt) ** self.gamma * torch.log(pt + 1e-12)\n loss[mask == 0] = 0\n if self.reduction == 'mean':\n loss = loss.sum(dim=1).sum() / n_valid\n return loss\n\n\nclass FocalLoss(nn.Module):\n \"\"\"https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109\"\"\"\n\n def __init__(self, gamma=2):\n super().__init__()\n self.gamma = gamma\n\n def forward(self, logit, target):\n target = target.float()\n max_val = (-logit).clamp(min=0)\n loss = logit - logit * target + max_val + ((-max_val).exp() + (-\n logit - max_val).exp()).log()\n invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0))\n loss = (invprobs * self.gamma).exp() * loss\n loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss\n return loss.mean()\n", "step-5": "import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\n\nclass FocalLoss1(nn.Module):\n def __init__(self, alpha=0.25, gamma=2, reduction='mean', ignore_lb=255):\n super().__init__()\n self.alpha = alpha\n self.gamma = gamma\n self.reduction = reduction\n self.ignore_lb = ignore_lb\n\n def forward(self, logits, label):\n \"\"\"[summary]\n \n Args:\n logits ([type]): tensor of shape (N, C, H, W)\n label ([type]): tensor of shape(N, H, W)\n \n Returns:\n [type]: [description]\n \"\"\"\n\n # overcome ignored label\n ignore = label.data.cpu() == self.ignore_lb\n n_valid = (ignore == 0).sum()\n label[ignore] = 0\n\n ignore = ignore.nonzero()\n _, M = ignore.size()\n a, *b = ignore.chunk(M, dim=1)\n mask = torch.ones_like(logits)\n mask[[a, torch.arange(mask.size(1)), *b]] = 0\n\n # compute loss\n probs = torch.sigmoid(logits)\n lb_one_hot = logits.data.clone().zero_().scatter_(1, label.unsqueeze(1), 1)\n pt = torch.where(lb_one_hot == 1, probs, 1 - probs)\n alpha = self.alpha * lb_one_hot + (1 - self.alpha) * (1 - lb_one_hot)\n loss = -alpha * ((1 - pt)**self.gamma) * torch.log(pt + 1e-12)\n loss[mask == 0] = 0\n if self.reduction == 'mean':\n loss = loss.sum(dim=1).sum() / n_valid\n return loss\n\n\nclass FocalLoss(nn.Module):\n \"\"\"https://www.kaggle.com/c/human-protein-atlas-image-classification/discussion/78109\"\"\"\n\n def __init__(self, gamma=2):\n super().__init__()\n self.gamma = gamma\n\n def forward(self, logit, target):\n target = target.float()\n max_val = (-logit).clamp(min=0)\n loss = logit - logit * target + max_val + ((-max_val).exp() + (-logit - max_val).exp()).log()\n invprobs = F.logsigmoid(-logit * (target * 2.0 - 1.0))\n loss = (invprobs * self.gamma).exp() * loss\n loss = loss.sum(dim=1) if len(loss.size()) == 2 else loss\n return loss.mean()\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
from pygraphblas.matrix import Matrix from pygraphblas.types import BOOL from pyformlang.regular_expression import Regex class Graph: def __init__(self): self.n_vertices = 0 self.label_matrices = dict() self.start_vertices = set() self.final_vertices = set() def from_trans(self, filename): input_file = open(filename) edges = input_file.read().rstrip().split('\n') input_file.close() max_vertice_number = 0 for edge in edges: fro, label, to = edge.split(' ') max_vertice_number = max(max_vertice_number, int(fro)) max_vertice_number = max(max_vertice_number, int(to)) self.n_vertices = max_vertice_number + 1 for edge in edges: fro, label, to = edge.split(' ') self.get_by_label(label)[int(fro), int(to)] = True def from_regex(self, filename): input_file = open(filename) regex = Regex(input_file.read().rstrip()) dfa = regex.to_epsilon_nfa().to_deterministic().minimize() self.n_vertices = len(dfa.states) state_renumeration = dict() i = 0 for state in dfa.states: state_renumeration[state] = i i += 1 for fro, label, to in dfa._transition_function.get_edges(): self.get_by_label(str(label))[state_renumeration[fro], state_renumeration[to]] = True self.start_vertices.add(state_renumeration[dfa.start_state]) for state in dfa.final_states: self.final_vertices.add(state_renumeration[state]) def transitive_closure_1(self): adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices) for label_matrix in self.label_matrices.values(): adj_matrix += label_matrix if adj_matrix.nvals != 0: while True: old = adj_matrix.nvals adj_matrix += adj_matrix @ adj_matrix if old == adj_matrix: break return adj_matrix def transitive_closure_2(self): adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices) result = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices) for label_matrix in self.label_matrices.values(): adj_matrix += label_matrix if adj_matrix.nvals != 0: while True: old = result.nvals result += adj_matrix if old == result.nvals: break return result def labels(self): return self.label_matrices.keys() def get_by_label(self, label): if label not in self.label_matrices.keys(): self.label_matrices[label] = Matrix.sparse(BOOL, self. n_vertices, self.n_vertices) return self.label_matrices[label]
normal
{ "blob_id": "2ccc3bb63445572610f6dbdfe5b1cbeef506c9a9", "index": 8613, "step-1": "<mask token>\n\n\nclass Graph:\n <mask token>\n <mask token>\n <mask token>\n\n def transitive_closure_1(self):\n adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n for label_matrix in self.label_matrices.values():\n adj_matrix += label_matrix\n if adj_matrix.nvals != 0:\n while True:\n old = adj_matrix.nvals\n adj_matrix += adj_matrix @ adj_matrix\n if old == adj_matrix:\n break\n return adj_matrix\n <mask token>\n <mask token>\n\n def get_by_label(self, label):\n if label not in self.label_matrices.keys():\n self.label_matrices[label] = Matrix.sparse(BOOL, self.\n n_vertices, self.n_vertices)\n return self.label_matrices[label]\n", "step-2": "<mask token>\n\n\nclass Graph:\n <mask token>\n\n def from_trans(self, filename):\n input_file = open(filename)\n edges = input_file.read().rstrip().split('\\n')\n input_file.close()\n max_vertice_number = 0\n for edge in edges:\n fro, label, to = edge.split(' ')\n max_vertice_number = max(max_vertice_number, int(fro))\n max_vertice_number = max(max_vertice_number, int(to))\n self.n_vertices = max_vertice_number + 1\n for edge in edges:\n fro, label, to = edge.split(' ')\n self.get_by_label(label)[int(fro), int(to)] = True\n\n def from_regex(self, filename):\n input_file = open(filename)\n regex = Regex(input_file.read().rstrip())\n dfa = regex.to_epsilon_nfa().to_deterministic().minimize()\n self.n_vertices = len(dfa.states)\n state_renumeration = dict()\n i = 0\n for state in dfa.states:\n state_renumeration[state] = i\n i += 1\n for fro, label, to in dfa._transition_function.get_edges():\n self.get_by_label(str(label))[state_renumeration[fro],\n state_renumeration[to]] = True\n self.start_vertices.add(state_renumeration[dfa.start_state])\n for state in dfa.final_states:\n self.final_vertices.add(state_renumeration[state])\n\n def transitive_closure_1(self):\n adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n for label_matrix in self.label_matrices.values():\n adj_matrix += label_matrix\n if adj_matrix.nvals != 0:\n while True:\n old = adj_matrix.nvals\n adj_matrix += adj_matrix @ adj_matrix\n if old == adj_matrix:\n break\n return adj_matrix\n <mask token>\n <mask token>\n\n def get_by_label(self, label):\n if label not in self.label_matrices.keys():\n self.label_matrices[label] = Matrix.sparse(BOOL, self.\n n_vertices, self.n_vertices)\n return self.label_matrices[label]\n", "step-3": "<mask token>\n\n\nclass Graph:\n\n def __init__(self):\n self.n_vertices = 0\n self.label_matrices = dict()\n self.start_vertices = set()\n self.final_vertices = set()\n\n def from_trans(self, filename):\n input_file = open(filename)\n edges = input_file.read().rstrip().split('\\n')\n input_file.close()\n max_vertice_number = 0\n for edge in edges:\n fro, label, to = edge.split(' ')\n max_vertice_number = max(max_vertice_number, int(fro))\n max_vertice_number = max(max_vertice_number, int(to))\n self.n_vertices = max_vertice_number + 1\n for edge in edges:\n fro, label, to = edge.split(' ')\n self.get_by_label(label)[int(fro), int(to)] = True\n\n def from_regex(self, filename):\n input_file = open(filename)\n regex = Regex(input_file.read().rstrip())\n dfa = regex.to_epsilon_nfa().to_deterministic().minimize()\n self.n_vertices = len(dfa.states)\n state_renumeration = dict()\n i = 0\n for state in dfa.states:\n state_renumeration[state] = i\n i += 1\n for fro, label, to in dfa._transition_function.get_edges():\n self.get_by_label(str(label))[state_renumeration[fro],\n state_renumeration[to]] = True\n self.start_vertices.add(state_renumeration[dfa.start_state])\n for state in dfa.final_states:\n self.final_vertices.add(state_renumeration[state])\n\n def transitive_closure_1(self):\n adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n for label_matrix in self.label_matrices.values():\n adj_matrix += label_matrix\n if adj_matrix.nvals != 0:\n while True:\n old = adj_matrix.nvals\n adj_matrix += adj_matrix @ adj_matrix\n if old == adj_matrix:\n break\n return adj_matrix\n\n def transitive_closure_2(self):\n adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n result = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n for label_matrix in self.label_matrices.values():\n adj_matrix += label_matrix\n if adj_matrix.nvals != 0:\n while True:\n old = result.nvals\n result += adj_matrix\n if old == result.nvals:\n break\n return result\n\n def labels(self):\n return self.label_matrices.keys()\n\n def get_by_label(self, label):\n if label not in self.label_matrices.keys():\n self.label_matrices[label] = Matrix.sparse(BOOL, self.\n n_vertices, self.n_vertices)\n return self.label_matrices[label]\n", "step-4": "from pygraphblas.matrix import Matrix\nfrom pygraphblas.types import BOOL\nfrom pyformlang.regular_expression import Regex\n\n\nclass Graph:\n\n def __init__(self):\n self.n_vertices = 0\n self.label_matrices = dict()\n self.start_vertices = set()\n self.final_vertices = set()\n\n def from_trans(self, filename):\n input_file = open(filename)\n edges = input_file.read().rstrip().split('\\n')\n input_file.close()\n max_vertice_number = 0\n for edge in edges:\n fro, label, to = edge.split(' ')\n max_vertice_number = max(max_vertice_number, int(fro))\n max_vertice_number = max(max_vertice_number, int(to))\n self.n_vertices = max_vertice_number + 1\n for edge in edges:\n fro, label, to = edge.split(' ')\n self.get_by_label(label)[int(fro), int(to)] = True\n\n def from_regex(self, filename):\n input_file = open(filename)\n regex = Regex(input_file.read().rstrip())\n dfa = regex.to_epsilon_nfa().to_deterministic().minimize()\n self.n_vertices = len(dfa.states)\n state_renumeration = dict()\n i = 0\n for state in dfa.states:\n state_renumeration[state] = i\n i += 1\n for fro, label, to in dfa._transition_function.get_edges():\n self.get_by_label(str(label))[state_renumeration[fro],\n state_renumeration[to]] = True\n self.start_vertices.add(state_renumeration[dfa.start_state])\n for state in dfa.final_states:\n self.final_vertices.add(state_renumeration[state])\n\n def transitive_closure_1(self):\n adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n for label_matrix in self.label_matrices.values():\n adj_matrix += label_matrix\n if adj_matrix.nvals != 0:\n while True:\n old = adj_matrix.nvals\n adj_matrix += adj_matrix @ adj_matrix\n if old == adj_matrix:\n break\n return adj_matrix\n\n def transitive_closure_2(self):\n adj_matrix = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n result = Matrix.sparse(BOOL, self.n_vertices, self.n_vertices)\n for label_matrix in self.label_matrices.values():\n adj_matrix += label_matrix\n if adj_matrix.nvals != 0:\n while True:\n old = result.nvals\n result += adj_matrix\n if old == result.nvals:\n break\n return result\n\n def labels(self):\n return self.label_matrices.keys()\n\n def get_by_label(self, label):\n if label not in self.label_matrices.keys():\n self.label_matrices[label] = Matrix.sparse(BOOL, self.\n n_vertices, self.n_vertices)\n return self.label_matrices[label]\n", "step-5": null, "step-ids": [ 3, 5, 8, 9 ] }
[ 3, 5, 8, 9 ]
<|reserved_special_token_0|> def load_path(): path = os.path.join(os.path.dirname(__file__)) if path == '': path = '.' return path def create_folder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print('Issue: Creating directory. ' + directory) <|reserved_special_token_0|> def read_wav(filename): audio_signal, sample_rate = sf.read(filename) if audio_signal.ndim > 1: audio_signal = audio_signal[:, 0] if audio_signal.dtype != 'float64': audio_signal = wav_to_float(audio_signal) return audio_signal, sample_rate <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def load_path(): path = os.path.join(os.path.dirname(__file__)) if path == '': path = '.' return path def create_folder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print('Issue: Creating directory. ' + directory) def read_dir_list(dirname, extention=''): try: return_list = [] filenames = os.listdir(dirname) for filename in filenames: full_filename = os.path.join(dirname, filename) if os.path.isdir(full_filename): return_list.extend(read_dir_list(full_filename, extention)) else: ext = os.path.splitext(full_filename)[-1][1:] if extention == '' or ext == extention: return_list.append(full_filename) return_list.sort() return return_list except PermissionError: pass <|reserved_special_token_0|> def read_wav(filename): audio_signal, sample_rate = sf.read(filename) if audio_signal.ndim > 1: audio_signal = audio_signal[:, 0] if audio_signal.dtype != 'float64': audio_signal = wav_to_float(audio_signal) return audio_signal, sample_rate <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def load_path(): path = os.path.join(os.path.dirname(__file__)) if path == '': path = '.' return path def create_folder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print('Issue: Creating directory. ' + directory) def read_dir_list(dirname, extention=''): try: return_list = [] filenames = os.listdir(dirname) for filename in filenames: full_filename = os.path.join(dirname, filename) if os.path.isdir(full_filename): return_list.extend(read_dir_list(full_filename, extention)) else: ext = os.path.splitext(full_filename)[-1][1:] if extention == '' or ext == extention: return_list.append(full_filename) return_list.sort() return return_list except PermissionError: pass def wav_to_float(x): try: max_value = np.iinfo(x.dtype).max min_value = np.iinfo(x.dtype).min except: max_value = np.finfo(x.dtype).max min_value = np.finfo(x.dtype).min x = x.astype('float64', casting='safe') x -= min_value x /= (max_value - min_value) / 2.0 x -= 1.0 return x def read_wav(filename): audio_signal, sample_rate = sf.read(filename) if audio_signal.ndim > 1: audio_signal = audio_signal[:, 0] if audio_signal.dtype != 'float64': audio_signal = wav_to_float(audio_signal) return audio_signal, sample_rate def write_wav(x, filename, sample_rate): if type(x) != np.ndarray: x = np.array(x) with warnings.catch_warnings(): warnings.simplefilter('error') sf.write(filename, x, sample_rate) <|reserved_special_token_1|> import os import numpy as np import warnings import soundfile as sf def load_path(): path = os.path.join(os.path.dirname(__file__)) if path == '': path = '.' return path def create_folder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print('Issue: Creating directory. ' + directory) def read_dir_list(dirname, extention=''): try: return_list = [] filenames = os.listdir(dirname) for filename in filenames: full_filename = os.path.join(dirname, filename) if os.path.isdir(full_filename): return_list.extend(read_dir_list(full_filename, extention)) else: ext = os.path.splitext(full_filename)[-1][1:] if extention == '' or ext == extention: return_list.append(full_filename) return_list.sort() return return_list except PermissionError: pass def wav_to_float(x): try: max_value = np.iinfo(x.dtype).max min_value = np.iinfo(x.dtype).min except: max_value = np.finfo(x.dtype).max min_value = np.finfo(x.dtype).min x = x.astype('float64', casting='safe') x -= min_value x /= (max_value - min_value) / 2.0 x -= 1.0 return x def read_wav(filename): audio_signal, sample_rate = sf.read(filename) if audio_signal.ndim > 1: audio_signal = audio_signal[:, 0] if audio_signal.dtype != 'float64': audio_signal = wav_to_float(audio_signal) return audio_signal, sample_rate def write_wav(x, filename, sample_rate): if type(x) != np.ndarray: x = np.array(x) with warnings.catch_warnings(): warnings.simplefilter('error') sf.write(filename, x, sample_rate) <|reserved_special_token_1|> import os import numpy as np import warnings import soundfile as sf def load_path(): path = os.path.join(os.path.dirname(__file__)) if path == "": path = "." return path def create_folder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print ('Issue: Creating directory. ' + directory) def read_dir_list(dirname, extention=""): try: return_list = [] filenames = os.listdir(dirname) for filename in filenames: full_filename = os.path.join(dirname, filename) if os.path.isdir(full_filename): return_list.extend(read_dir_list(full_filename, extention)) else: ext = os.path.splitext(full_filename)[-1][1:] if extention == "" or ext == extention: return_list.append(full_filename) return_list.sort() return return_list except PermissionError: pass def wav_to_float(x): try: max_value = np.iinfo(x.dtype).max min_value = np.iinfo(x.dtype).min except: max_value = np.finfo(x.dtype).max min_value = np.finfo(x.dtype).min x = x.astype('float64', casting='safe') x -= min_value x /= ((max_value - min_value) / 2.) x -= 1. return x def read_wav(filename): # Reads in a wav audio file, takes the first channel, converts the signal to float64 representation audio_signal, sample_rate = sf.read(filename) if audio_signal.ndim > 1: audio_signal = audio_signal[:, 0] if audio_signal.dtype != 'float64': audio_signal = wav_to_float(audio_signal) return audio_signal, sample_rate def write_wav(x, filename, sample_rate): if type(x) != np.ndarray: x = np.array(x) with warnings.catch_warnings(): warnings.simplefilter("error") sf.write(filename, x, sample_rate)
flexible
{ "blob_id": "cab233976653b8135276ff849955f32766833354", "index": 7555, "step-1": "<mask token>\n\n\ndef load_path():\n path = os.path.join(os.path.dirname(__file__))\n if path == '':\n path = '.'\n return path\n\n\ndef create_folder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Issue: Creating directory. ' + directory)\n\n\n<mask token>\n\n\ndef read_wav(filename):\n audio_signal, sample_rate = sf.read(filename)\n if audio_signal.ndim > 1:\n audio_signal = audio_signal[:, 0]\n if audio_signal.dtype != 'float64':\n audio_signal = wav_to_float(audio_signal)\n return audio_signal, sample_rate\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef load_path():\n path = os.path.join(os.path.dirname(__file__))\n if path == '':\n path = '.'\n return path\n\n\ndef create_folder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Issue: Creating directory. ' + directory)\n\n\ndef read_dir_list(dirname, extention=''):\n try:\n return_list = []\n filenames = os.listdir(dirname)\n for filename in filenames:\n full_filename = os.path.join(dirname, filename)\n if os.path.isdir(full_filename):\n return_list.extend(read_dir_list(full_filename, extention))\n else:\n ext = os.path.splitext(full_filename)[-1][1:]\n if extention == '' or ext == extention:\n return_list.append(full_filename)\n return_list.sort()\n return return_list\n except PermissionError:\n pass\n\n\n<mask token>\n\n\ndef read_wav(filename):\n audio_signal, sample_rate = sf.read(filename)\n if audio_signal.ndim > 1:\n audio_signal = audio_signal[:, 0]\n if audio_signal.dtype != 'float64':\n audio_signal = wav_to_float(audio_signal)\n return audio_signal, sample_rate\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef load_path():\n path = os.path.join(os.path.dirname(__file__))\n if path == '':\n path = '.'\n return path\n\n\ndef create_folder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Issue: Creating directory. ' + directory)\n\n\ndef read_dir_list(dirname, extention=''):\n try:\n return_list = []\n filenames = os.listdir(dirname)\n for filename in filenames:\n full_filename = os.path.join(dirname, filename)\n if os.path.isdir(full_filename):\n return_list.extend(read_dir_list(full_filename, extention))\n else:\n ext = os.path.splitext(full_filename)[-1][1:]\n if extention == '' or ext == extention:\n return_list.append(full_filename)\n return_list.sort()\n return return_list\n except PermissionError:\n pass\n\n\ndef wav_to_float(x):\n try:\n max_value = np.iinfo(x.dtype).max\n min_value = np.iinfo(x.dtype).min\n except:\n max_value = np.finfo(x.dtype).max\n min_value = np.finfo(x.dtype).min\n x = x.astype('float64', casting='safe')\n x -= min_value\n x /= (max_value - min_value) / 2.0\n x -= 1.0\n return x\n\n\ndef read_wav(filename):\n audio_signal, sample_rate = sf.read(filename)\n if audio_signal.ndim > 1:\n audio_signal = audio_signal[:, 0]\n if audio_signal.dtype != 'float64':\n audio_signal = wav_to_float(audio_signal)\n return audio_signal, sample_rate\n\n\ndef write_wav(x, filename, sample_rate):\n if type(x) != np.ndarray:\n x = np.array(x)\n with warnings.catch_warnings():\n warnings.simplefilter('error')\n sf.write(filename, x, sample_rate)\n", "step-4": "import os\nimport numpy as np\nimport warnings\nimport soundfile as sf\n\n\ndef load_path():\n path = os.path.join(os.path.dirname(__file__))\n if path == '':\n path = '.'\n return path\n\n\ndef create_folder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Issue: Creating directory. ' + directory)\n\n\ndef read_dir_list(dirname, extention=''):\n try:\n return_list = []\n filenames = os.listdir(dirname)\n for filename in filenames:\n full_filename = os.path.join(dirname, filename)\n if os.path.isdir(full_filename):\n return_list.extend(read_dir_list(full_filename, extention))\n else:\n ext = os.path.splitext(full_filename)[-1][1:]\n if extention == '' or ext == extention:\n return_list.append(full_filename)\n return_list.sort()\n return return_list\n except PermissionError:\n pass\n\n\ndef wav_to_float(x):\n try:\n max_value = np.iinfo(x.dtype).max\n min_value = np.iinfo(x.dtype).min\n except:\n max_value = np.finfo(x.dtype).max\n min_value = np.finfo(x.dtype).min\n x = x.astype('float64', casting='safe')\n x -= min_value\n x /= (max_value - min_value) / 2.0\n x -= 1.0\n return x\n\n\ndef read_wav(filename):\n audio_signal, sample_rate = sf.read(filename)\n if audio_signal.ndim > 1:\n audio_signal = audio_signal[:, 0]\n if audio_signal.dtype != 'float64':\n audio_signal = wav_to_float(audio_signal)\n return audio_signal, sample_rate\n\n\ndef write_wav(x, filename, sample_rate):\n if type(x) != np.ndarray:\n x = np.array(x)\n with warnings.catch_warnings():\n warnings.simplefilter('error')\n sf.write(filename, x, sample_rate)\n", "step-5": "import os\nimport numpy as np\nimport warnings\nimport soundfile as sf\n\n\ndef load_path():\n path = os.path.join(os.path.dirname(__file__))\n if path == \"\":\n path = \".\"\n return path\n\n\ndef create_folder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print ('Issue: Creating directory. ' + directory)\n\ndef read_dir_list(dirname, extention=\"\"):\n try:\n return_list = []\n filenames = os.listdir(dirname)\n for filename in filenames:\n full_filename = os.path.join(dirname, filename)\n if os.path.isdir(full_filename):\n return_list.extend(read_dir_list(full_filename, extention))\n else:\n ext = os.path.splitext(full_filename)[-1][1:]\n if extention == \"\" or ext == extention:\n return_list.append(full_filename)\n return_list.sort()\n return return_list\n except PermissionError:\n pass\n\ndef wav_to_float(x):\n try:\n max_value = np.iinfo(x.dtype).max\n min_value = np.iinfo(x.dtype).min\n except:\n max_value = np.finfo(x.dtype).max\n min_value = np.finfo(x.dtype).min\n x = x.astype('float64', casting='safe')\n x -= min_value\n x /= ((max_value - min_value) / 2.)\n x -= 1.\n return x\n\ndef read_wav(filename):\n # Reads in a wav audio file, takes the first channel, converts the signal to float64 representation\n audio_signal, sample_rate = sf.read(filename)\n\n if audio_signal.ndim > 1:\n audio_signal = audio_signal[:, 0]\n\n if audio_signal.dtype != 'float64':\n audio_signal = wav_to_float(audio_signal)\n\n return audio_signal, sample_rate\n\ndef write_wav(x, filename, sample_rate):\n if type(x) != np.ndarray:\n x = np.array(x)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n sf.write(filename, x, sample_rate)\n", "step-ids": [ 3, 4, 6, 7, 8 ] }
[ 3, 4, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for i in range(1, n + 1): print(i) <|reserved_special_token_1|> n = int(input('nhap gia tri')) for i in range(1, n + 1): print(i) <|reserved_special_token_1|> n =int(input("nhap gia tri")) for i in range(1,n+1): print(i)
flexible
{ "blob_id": "21b295e28a7e4443ea116df1b22ff5074dca955a", "index": 246, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(1, n + 1):\n print(i)\n", "step-3": "n = int(input('nhap gia tri'))\nfor i in range(1, n + 1):\n print(i)\n", "step-4": "n =int(input(\"nhap gia tri\"))\nfor i in range(1,n+1):\n\n\n\n\n\n\n\n\n\n\n\n\n print(i)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(response.status_code) print(response.apparent_encoding) <|reserved_special_token_0|> for music in list_music: print(music['name']) print('所属专辑:' + music['album']['name']) print('歌曲时长:' + str(music['interval']) + '秒') print('歌曲播放链接:https://y.qq.com/n/yqq/song/' + music['mid'] + '.html\n\n') <|reserved_special_token_1|> <|reserved_special_token_0|> headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11' } client_url = ( 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=69467462525912938&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0%E4%BC%A6&g_tk=490628805&loginUin=757585105&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0' ) response = requests.get(url=client_url, headers=headers) print(response.status_code) print(response.apparent_encoding) response.encoding = response.apparent_encoding json_response = response.json() list_music = json_response['data']['song']['list'] for music in list_music: print(music['name']) print('所属专辑:' + music['album']['name']) print('歌曲时长:' + str(music['interval']) + '秒') print('歌曲播放链接:https://y.qq.com/n/yqq/song/' + music['mid'] + '.html\n\n') <|reserved_special_token_1|> import requests from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11' } client_url = ( 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=69467462525912938&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0%E4%BC%A6&g_tk=490628805&loginUin=757585105&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0' ) response = requests.get(url=client_url, headers=headers) print(response.status_code) print(response.apparent_encoding) response.encoding = response.apparent_encoding json_response = response.json() list_music = json_response['data']['song']['list'] for music in list_music: print(music['name']) print('所属专辑:' + music['album']['name']) print('歌曲时长:' + str(music['interval']) + '秒') print('歌曲播放链接:https://y.qq.com/n/yqq/song/' + music['mid'] + '.html\n\n') <|reserved_special_token_1|> # !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 # -*- coding:utf-8 -*- # @Author : Jiazhixiang import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11" } # start_url = "https://y.qq.com/portal/search.html#page=1&searchid=1&remoteplace=txt.yqq.top&t=song&w=%E5%91%A8%E6%9D%B0%E4%BC%A6" client_url = "https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=69467462525912938&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0%E4%BC%A6&g_tk=490628805&loginUin=757585105&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0" response = requests.get(url=client_url, headers=headers) print(response.status_code) print(response.apparent_encoding) response.encoding = response.apparent_encoding # response = response.text # print(type(response)) json_response = response.json() # print(json_response) # print(type(json_response)) list_music = json_response['data']['song']['list'] for music in list_music: print(music['name']) print("所属专辑:" + music['album']['name']) print("歌曲时长:" + str(music['interval']) + "秒") # https: // y.qq.com / n / yqq / song / 001qvvgF38HVc4.html print("歌曲播放链接:https://y.qq.com/n/yqq/song/" + music['mid'] + ".html\n\n")
flexible
{ "blob_id": "9833af7f5f740e18cbd4d16f59474b4bacaf070c", "index": 2026, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(response.status_code)\nprint(response.apparent_encoding)\n<mask token>\nfor music in list_music:\n print(music['name'])\n print('所属专辑:' + music['album']['name'])\n print('歌曲时长:' + str(music['interval']) + '秒')\n print('歌曲播放链接:https://y.qq.com/n/yqq/song/' + music['mid'] + '.html\\n\\n')\n", "step-3": "<mask token>\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11'\n }\nclient_url = (\n 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=69467462525912938&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0%E4%BC%A6&g_tk=490628805&loginUin=757585105&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0'\n )\nresponse = requests.get(url=client_url, headers=headers)\nprint(response.status_code)\nprint(response.apparent_encoding)\nresponse.encoding = response.apparent_encoding\njson_response = response.json()\nlist_music = json_response['data']['song']['list']\nfor music in list_music:\n print(music['name'])\n print('所属专辑:' + music['album']['name'])\n print('歌曲时长:' + str(music['interval']) + '秒')\n print('歌曲播放链接:https://y.qq.com/n/yqq/song/' + music['mid'] + '.html\\n\\n')\n", "step-4": "import requests\nfrom bs4 import BeautifulSoup\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11'\n }\nclient_url = (\n 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=69467462525912938&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0%E4%BC%A6&g_tk=490628805&loginUin=757585105&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0'\n )\nresponse = requests.get(url=client_url, headers=headers)\nprint(response.status_code)\nprint(response.apparent_encoding)\nresponse.encoding = response.apparent_encoding\njson_response = response.json()\nlist_music = json_response['data']['song']['list']\nfor music in list_music:\n print(music['name'])\n print('所属专辑:' + music['album']['name'])\n print('歌曲时长:' + str(music['interval']) + '秒')\n print('歌曲播放链接:https://y.qq.com/n/yqq/song/' + music['mid'] + '.html\\n\\n')\n", "step-5": "# !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3\n# -*- coding:utf-8 -*-\n# @Author : Jiazhixiang\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11\"\n}\n# start_url = \"https://y.qq.com/portal/search.html#page=1&searchid=1&remoteplace=txt.yqq.top&t=song&w=%E5%91%A8%E6%9D%B0%E4%BC%A6\"\nclient_url = \"https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=69467462525912938&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0%E4%BC%A6&g_tk=490628805&loginUin=757585105&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0\"\nresponse = requests.get(url=client_url, headers=headers)\nprint(response.status_code)\nprint(response.apparent_encoding)\nresponse.encoding = response.apparent_encoding\n# response = response.text\n# print(type(response))\njson_response = response.json()\n# print(json_response)\n# print(type(json_response))\nlist_music = json_response['data']['song']['list']\nfor music in list_music:\n print(music['name'])\n print(\"所属专辑:\" + music['album']['name'])\n print(\"歌曲时长:\" + str(music['interval']) + \"秒\")\n # https: // y.qq.com / n / yqq / song / 001qvvgF38HVc4.html\n print(\"歌曲播放链接:https://y.qq.com/n/yqq/song/\" + music['mid'] + \".html\\n\\n\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> modulus_size = 2048 n, e = 0, 0 k = modulus_size // 8 queries = 0 print_queries_every = 1 number_of_time_to_confirm_conforming = 10 encrypt_openssl = True t_start = 0 cwd = '' host = '10.0.0.1' port = 4430 sock = 0 max_message_size = 2048 <|reserved_special_token_1|> # RSA key modulus_size = 2048 (n, e) = (0, 0) # Not being initialize here # modulus size in bytes k = modulus_size // 8 # keep track of the oracle calls queries = 0 print_queries_every = 1 number_of_time_to_confirm_conforming = 10 # Choose to use OpenSSL encrypt function or our own implementations encrypt_openssl = True # start timer t_start = 0 # Not being initialize here # Current Working Directory of the project cwd = "" # Server info host = '10.0.0.1' port = 4430 sock = 0 # Not being initialize here max_message_size = 2048
flexible
{ "blob_id": "415d58e502e8a33f7a37c4fb2da34e838246ea9c", "index": 2057, "step-1": "<mask token>\n", "step-2": "modulus_size = 2048\nn, e = 0, 0\nk = modulus_size // 8\nqueries = 0\nprint_queries_every = 1\nnumber_of_time_to_confirm_conforming = 10\nencrypt_openssl = True\nt_start = 0\ncwd = ''\nhost = '10.0.0.1'\nport = 4430\nsock = 0\nmax_message_size = 2048\n", "step-3": "\n# RSA key\nmodulus_size = 2048\n(n, e) = (0, 0) # Not being initialize here\n\n# modulus size in bytes\nk = modulus_size // 8\n\n# keep track of the oracle calls\nqueries = 0\nprint_queries_every = 1\nnumber_of_time_to_confirm_conforming = 10\n\n# Choose to use OpenSSL encrypt function or our own implementations\nencrypt_openssl = True\n\n# start timer\nt_start = 0 # Not being initialize here\n\n# Current Working Directory of the project\ncwd = \"\"\n\n# Server info\nhost = '10.0.0.1'\nport = 4430\nsock = 0 # Not being initialize here\nmax_message_size = 2048\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.append(os.pardir) <|reserved_special_token_0|> for i in range(iters_num): print(i) batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] grad = network.gradient(x_batch, t_batch) for key in ('W1', 'b1', 'W2', 'b2'): network.params[key] -= learning_rate * grad[key] loss = network.loss(x_batch, t_batch) train_loss_list.append(loss) print('{} : {}'.format(i, train_loss_list[i])) print(train_loss_list) <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.append(os.pardir) <|reserved_special_token_0|> (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True) train_loss_list = [] iters_num = 1000 train_size = x_train.shape[0] batch_size = 100 learning_rate = 0.1 network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10) for i in range(iters_num): print(i) batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] grad = network.gradient(x_batch, t_batch) for key in ('W1', 'b1', 'W2', 'b2'): network.params[key] -= learning_rate * grad[key] loss = network.loss(x_batch, t_batch) train_loss_list.append(loss) print('{} : {}'.format(i, train_loss_list[i])) print(train_loss_list) <|reserved_special_token_1|> import sys, os sys.path.append(os.pardir) import numpy as np from dataset.mnist import load_mnist from two_layer_net import TwoLayerNet (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True) train_loss_list = [] iters_num = 1000 train_size = x_train.shape[0] batch_size = 100 learning_rate = 0.1 network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10) for i in range(iters_num): print(i) batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] grad = network.gradient(x_batch, t_batch) for key in ('W1', 'b1', 'W2', 'b2'): network.params[key] -= learning_rate * grad[key] loss = network.loss(x_batch, t_batch) train_loss_list.append(loss) print('{} : {}'.format(i, train_loss_list[i])) print(train_loss_list) <|reserved_special_token_1|> import sys, os sys.path.append(os.pardir) import numpy as np from dataset.mnist import load_mnist from two_layer_net import TwoLayerNet (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label = True) train_loss_list = [] #hiper param iters_num = 1000 train_size = x_train.shape[0] batch_size = 100 learning_rate = 0.1 network = TwoLayerNet(input_size = 784, hidden_size=50, output_size=10) for i in range(iters_num): print(i) #get batch batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] #calc gradient grad = network.gradient(x_batch, t_batch) #update param for key in ('W1', 'b1', 'W2', 'b2'): network.params[key] -= learning_rate * grad[key] #recode loss = network.loss(x_batch, t_batch) train_loss_list.append(loss) print("{} : {}".format(i, train_loss_list[i])) print(train_loss_list)
flexible
{ "blob_id": "dbe3aa107de8e62822803d1740773a4b22f41edf", "index": 971, "step-1": "<mask token>\n", "step-2": "<mask token>\nsys.path.append(os.pardir)\n<mask token>\nfor i in range(iters_num):\n print(i)\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n grad = network.gradient(x_batch, t_batch)\n for key in ('W1', 'b1', 'W2', 'b2'):\n network.params[key] -= learning_rate * grad[key]\n loss = network.loss(x_batch, t_batch)\n train_loss_list.append(loss)\n print('{} : {}'.format(i, train_loss_list[i]))\nprint(train_loss_list)\n", "step-3": "<mask token>\nsys.path.append(os.pardir)\n<mask token>\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True,\n one_hot_label=True)\ntrain_loss_list = []\niters_num = 1000\ntrain_size = x_train.shape[0]\nbatch_size = 100\nlearning_rate = 0.1\nnetwork = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)\nfor i in range(iters_num):\n print(i)\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n grad = network.gradient(x_batch, t_batch)\n for key in ('W1', 'b1', 'W2', 'b2'):\n network.params[key] -= learning_rate * grad[key]\n loss = network.loss(x_batch, t_batch)\n train_loss_list.append(loss)\n print('{} : {}'.format(i, train_loss_list[i]))\nprint(train_loss_list)\n", "step-4": "import sys, os\nsys.path.append(os.pardir)\nimport numpy as np\nfrom dataset.mnist import load_mnist\nfrom two_layer_net import TwoLayerNet\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True,\n one_hot_label=True)\ntrain_loss_list = []\niters_num = 1000\ntrain_size = x_train.shape[0]\nbatch_size = 100\nlearning_rate = 0.1\nnetwork = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)\nfor i in range(iters_num):\n print(i)\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n grad = network.gradient(x_batch, t_batch)\n for key in ('W1', 'b1', 'W2', 'b2'):\n network.params[key] -= learning_rate * grad[key]\n loss = network.loss(x_batch, t_batch)\n train_loss_list.append(loss)\n print('{} : {}'.format(i, train_loss_list[i]))\nprint(train_loss_list)\n", "step-5": "import sys, os\nsys.path.append(os.pardir)\nimport numpy as np\nfrom dataset.mnist import load_mnist\nfrom two_layer_net import TwoLayerNet\n\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label = True)\n\ntrain_loss_list = []\n\n#hiper param\niters_num = 1000\ntrain_size = x_train.shape[0]\nbatch_size = 100\nlearning_rate = 0.1\n\nnetwork = TwoLayerNet(input_size = 784, hidden_size=50, output_size=10)\nfor i in range(iters_num):\n print(i)\n #get batch\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n\n #calc gradient\n grad = network.gradient(x_batch, t_batch)\n\n #update param\n for key in ('W1', 'b1', 'W2', 'b2'):\n network.params[key] -= learning_rate * grad[key]\n\n\n #recode\n loss = network.loss(x_batch, t_batch)\n train_loss_list.append(loss)\n print(\"{} : {}\".format(i, train_loss_list[i]))\nprint(train_loss_list)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python3 import os, re import csv, unittest from langtag import langtag from sldr.iana import Iana langtagjson = os.path.join(os.path.dirname(__file__), '..', 'pub', 'langtags.json') bannedchars = list(range(33, 45)) + [47] + list(range(58, 63)) + [94, 96] def nonascii(s): cs = [ord(x) for x in s] if any(not (32 <= x < 123) or x in bannedchars for x in cs): return True class Basic(unittest.TestCase): extraScripts = ["Toto", "Vith"] extraLangs = ("000", "cxh", "dsk", "dyr", "eud", "ikh", "izm", "lgs", # going in ~23/Mar/2023 'lvl', 'nzr', 'pze', 'rsw', 'tvi', 'uly', 'vjk', 'wtb', 'ycr', 'ykh', 'zem', 'zlu') # going in ~23/Mar/2023 def setUp(self): self.fname = os.path.join(os.path.dirname(__file__), '../source/langtags.csv') with open(self.fname) as csvfile: reader = csv.DictReader(csvfile, restkey="_") self.rows = list(reader) self.fieldnames = reader.fieldnames self.numlines = reader.line_num self.iana = Iana() def _region_test(self, x): if x in self.iana.region: return True elif x in ("XX", "XK"): return True return False def _allRows(self): for r in self.rows: t = langtag(r['likely_subtag']) if t.lang.startswith("x-"): continue yield (r, t) def test_lang(self): ''' Tests that all lang subtags are in iana ''' fails = [] for r, t in self._allRows(): l = langtag(r['Lang_Id']) if l.lang != t.lang and "-" not in l.lang and "-" not in t.lang: self.fail("{Lang_Id} has different lang to {likely_subtag} ({0} != {1})".format(l.lang, t.lang, **r)) if t.lang not in self.iana.language and "-" not in t.lang and t.lang not in self.extraLangs: fails.append(r['Lang_Id']) if not l.test(fname=langtagjson): self.fail("{Lang_Id} failed conformance check".format(**r)) if len(fails): self.fail(f"{fails} langs not in IANA") def test_region(self): ''' Test that region values are sensible and that they equal the default region. Unknown regions do not have to be specified. ''' for r,t in self._allRows(): reg = t.region if not self._region_test(t.region): self.fail("{likely_subtag} has irregular region".format(**r)) for s in r['regions'].split(): if not self._region_test(s.strip()): self.fail("{Lang_Id} has irregular region: {0} in regions".format(s, **r)) def test_script(self): ''' Qaa? type scripts must have an -x- for the script name ''' for r, t in self._allRows(): scr = t.script if scr is not None and (scr.startswith("Qaa") or scr.startswith("Qab")): if scr not in ("Qaax", "Qaby", "Qabz") and (t.extensions is None or 'x' not in t.extensions): self.fail("{Lang_Id} has no extension for script name".format(**r)) elif scr not in self.iana.script and scr not in self.extraScripts: self.fail("{Lang_Id} has irregular script {}".format(scr, **r)) elif t.script not in self.iana.script and t.script not in self.extraScripts: self.fail("{likely_subtag} has irregular script".format(**r)) def test_variants(self): ''' Test that all variants are in IANA ''' for r, t in self._allRows(): l = langtag(r['Lang_Id']) if t.vars is None and l.vars is None: continue if sorted(t.vars) != sorted(l.vars): self.fail("{Lang_Id} and {likely_subtag} have different variants".format(**r)) for v in t.vars: if v not in self.iana.variant: self.fail("{likely_subtag} has bad variant {0}".format(v, **r)) def test_csv_columns(self): ''' Test that everyone has the right number of columns ''' lc = self.fieldnames[-1] for r in self.rows: if len(r.get("_", [])): self.fail("{Lang_Id} has too many columns".format(**r)) elif r[lc] is None: self.fail("{Lang_Id} has too few columns".format(**r)) def test_pua(self): ''' Test that anything with -x- in Lang_Id has it in likely_subtag too ''' for r, t in self._allRows(): l = langtag(r['Lang_Id']) if t.ns is None and l.ns is None: continue if len(t.ns) == 1 and 'x' in t.ns and len(t.ns['x']) == 1: continue # allow a private script extension if sorted(t.ns.keys()) != sorted(l.ns.keys()): self.fail("{Lang_Id} and {likely_subtag} have different extension namespaces".format(**r)) for k, v in t.ns.items(): if sorted(v) != sorted(l.ns[k]): self.fail("{Lang_Id} and {likely_subtag} have different extensions in the {0} namespace".format(k, **r)) def test_ascii(self): ''' Test that all tags are pure ascii ''' for r, t in self._allRows(): for cid in ('Lang_Id', 'likely_subtag', 'regions', 'ISO 639-3', 'Macro', 'variants'): if nonascii(r[cid]): self.fail("{Lang_Id} has non ASCII in column {0} value {1}".format(cid, r[cid], **r)) def test_iso639(self): ''' Test that the iso639 column is either empty or 3 lower ascii chars. ''' k = 'ISO 639-3' for r, t in self._allRows(): if r[k] == '': continue if len(r[k]) != 3 or r[k].lower() != r[k] or any(not (96 < ord(x) < 123) for x in r[k]): self.fail("{Lang_Id} has faulty ISO639 code of {ISO 639-3}".format(**r)) def test_deprecated(self): for r, t in self._allRows(): l = langtag(r['Lang_Id']) inf = self.iana.language.get(l.lang, {}) if 'Deprecated' in inf: if r['deprecated'] == '': self.fail("{Lang_Id} was deprecated: {} in IANA but not in the database".format(inf['Deprecated'], **r)) if __name__ == "__main__": unittest.main()
normal
{ "blob_id": "e4f194c3dbc3e1d62866343642e41fa1ecdeab93", "index": 7380, "step-1": "<mask token>\n\n\nclass Basic(unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n\n def _region_test(self, x):\n if x in self.iana.region:\n return True\n elif x in ('XX', 'XK'):\n return True\n return False\n\n def _allRows(self):\n for r in self.rows:\n t = langtag(r['likely_subtag'])\n if t.lang.startswith('x-'):\n continue\n yield r, t\n\n def test_lang(self):\n \"\"\" Tests that all lang subtags are in iana \"\"\"\n fails = []\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if l.lang != t.lang and '-' not in l.lang and '-' not in t.lang:\n self.fail(\n '{Lang_Id} has different lang to {likely_subtag} ({0} != {1})'\n .format(l.lang, t.lang, **r))\n if (t.lang not in self.iana.language and '-' not in t.lang and \n t.lang not in self.extraLangs):\n fails.append(r['Lang_Id'])\n if not l.test(fname=langtagjson):\n self.fail('{Lang_Id} failed conformance check'.format(**r))\n if len(fails):\n self.fail(f'{fails} langs not in IANA')\n\n def test_region(self):\n \"\"\" Test that region values are sensible and that they equal the default region.\n Unknown regions do not have to be specified. \"\"\"\n for r, t in self._allRows():\n reg = t.region\n if not self._region_test(t.region):\n self.fail('{likely_subtag} has irregular region'.format(**r))\n for s in r['regions'].split():\n if not self._region_test(s.strip()):\n self.fail('{Lang_Id} has irregular region: {0} in regions'\n .format(s, **r))\n <mask token>\n\n def test_variants(self):\n \"\"\" Test that all variants are in IANA \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.vars is None and l.vars is None:\n continue\n if sorted(t.vars) != sorted(l.vars):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different variants'\n .format(**r))\n for v in t.vars:\n if v not in self.iana.variant:\n self.fail('{likely_subtag} has bad variant {0}'.format(\n v, **r))\n\n def test_csv_columns(self):\n \"\"\" Test that everyone has the right number of columns \"\"\"\n lc = self.fieldnames[-1]\n for r in self.rows:\n if len(r.get('_', [])):\n self.fail('{Lang_Id} has too many columns'.format(**r))\n elif r[lc] is None:\n self.fail('{Lang_Id} has too few columns'.format(**r))\n\n def test_pua(self):\n \"\"\" Test that anything with -x- in Lang_Id has it in likely_subtag too \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.ns is None and l.ns is None:\n continue\n if len(t.ns) == 1 and 'x' in t.ns and len(t.ns['x']) == 1:\n continue\n if sorted(t.ns.keys()) != sorted(l.ns.keys()):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extension namespaces'\n .format(**r))\n for k, v in t.ns.items():\n if sorted(v) != sorted(l.ns[k]):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extensions in the {0} namespace'\n .format(k, **r))\n\n def test_ascii(self):\n \"\"\" Test that all tags are pure ascii \"\"\"\n for r, t in self._allRows():\n for cid in ('Lang_Id', 'likely_subtag', 'regions', 'ISO 639-3',\n 'Macro', 'variants'):\n if nonascii(r[cid]):\n self.fail('{Lang_Id} has non ASCII in column {0} value {1}'\n .format(cid, r[cid], **r))\n\n def test_iso639(self):\n \"\"\" Test that the iso639 column is either empty or 3 lower ascii chars. \"\"\"\n k = 'ISO 639-3'\n for r, t in self._allRows():\n if r[k] == '':\n continue\n if len(r[k]) != 3 or r[k].lower() != r[k] or any(not 96 < ord(x\n ) < 123 for x in r[k]):\n self.fail('{Lang_Id} has faulty ISO639 code of {ISO 639-3}'\n .format(**r))\n\n def test_deprecated(self):\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n inf = self.iana.language.get(l.lang, {})\n if 'Deprecated' in inf:\n if r['deprecated'] == '':\n self.fail(\n '{Lang_Id} was deprecated: {} in IANA but not in the database'\n .format(inf['Deprecated'], **r))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Basic(unittest.TestCase):\n <mask token>\n <mask token>\n\n def setUp(self):\n self.fname = os.path.join(os.path.dirname(__file__),\n '../source/langtags.csv')\n with open(self.fname) as csvfile:\n reader = csv.DictReader(csvfile, restkey='_')\n self.rows = list(reader)\n self.fieldnames = reader.fieldnames\n self.numlines = reader.line_num\n self.iana = Iana()\n\n def _region_test(self, x):\n if x in self.iana.region:\n return True\n elif x in ('XX', 'XK'):\n return True\n return False\n\n def _allRows(self):\n for r in self.rows:\n t = langtag(r['likely_subtag'])\n if t.lang.startswith('x-'):\n continue\n yield r, t\n\n def test_lang(self):\n \"\"\" Tests that all lang subtags are in iana \"\"\"\n fails = []\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if l.lang != t.lang and '-' not in l.lang and '-' not in t.lang:\n self.fail(\n '{Lang_Id} has different lang to {likely_subtag} ({0} != {1})'\n .format(l.lang, t.lang, **r))\n if (t.lang not in self.iana.language and '-' not in t.lang and \n t.lang not in self.extraLangs):\n fails.append(r['Lang_Id'])\n if not l.test(fname=langtagjson):\n self.fail('{Lang_Id} failed conformance check'.format(**r))\n if len(fails):\n self.fail(f'{fails} langs not in IANA')\n\n def test_region(self):\n \"\"\" Test that region values are sensible and that they equal the default region.\n Unknown regions do not have to be specified. \"\"\"\n for r, t in self._allRows():\n reg = t.region\n if not self._region_test(t.region):\n self.fail('{likely_subtag} has irregular region'.format(**r))\n for s in r['regions'].split():\n if not self._region_test(s.strip()):\n self.fail('{Lang_Id} has irregular region: {0} in regions'\n .format(s, **r))\n\n def test_script(self):\n \"\"\" Qaa? type scripts must have an -x- for the script name \"\"\"\n for r, t in self._allRows():\n scr = t.script\n if scr is not None and (scr.startswith('Qaa') or scr.startswith\n ('Qab')):\n if scr not in ('Qaax', 'Qaby', 'Qabz') and (t.extensions is\n None or 'x' not in t.extensions):\n self.fail('{Lang_Id} has no extension for script name'.\n format(**r))\n elif scr not in self.iana.script and scr not in self.extraScripts:\n self.fail('{Lang_Id} has irregular script {}'.format(scr, **r))\n elif t.script not in self.iana.script and t.script not in self.extraScripts:\n self.fail('{likely_subtag} has irregular script'.format(**r))\n\n def test_variants(self):\n \"\"\" Test that all variants are in IANA \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.vars is None and l.vars is None:\n continue\n if sorted(t.vars) != sorted(l.vars):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different variants'\n .format(**r))\n for v in t.vars:\n if v not in self.iana.variant:\n self.fail('{likely_subtag} has bad variant {0}'.format(\n v, **r))\n\n def test_csv_columns(self):\n \"\"\" Test that everyone has the right number of columns \"\"\"\n lc = self.fieldnames[-1]\n for r in self.rows:\n if len(r.get('_', [])):\n self.fail('{Lang_Id} has too many columns'.format(**r))\n elif r[lc] is None:\n self.fail('{Lang_Id} has too few columns'.format(**r))\n\n def test_pua(self):\n \"\"\" Test that anything with -x- in Lang_Id has it in likely_subtag too \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.ns is None and l.ns is None:\n continue\n if len(t.ns) == 1 and 'x' in t.ns and len(t.ns['x']) == 1:\n continue\n if sorted(t.ns.keys()) != sorted(l.ns.keys()):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extension namespaces'\n .format(**r))\n for k, v in t.ns.items():\n if sorted(v) != sorted(l.ns[k]):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extensions in the {0} namespace'\n .format(k, **r))\n\n def test_ascii(self):\n \"\"\" Test that all tags are pure ascii \"\"\"\n for r, t in self._allRows():\n for cid in ('Lang_Id', 'likely_subtag', 'regions', 'ISO 639-3',\n 'Macro', 'variants'):\n if nonascii(r[cid]):\n self.fail('{Lang_Id} has non ASCII in column {0} value {1}'\n .format(cid, r[cid], **r))\n\n def test_iso639(self):\n \"\"\" Test that the iso639 column is either empty or 3 lower ascii chars. \"\"\"\n k = 'ISO 639-3'\n for r, t in self._allRows():\n if r[k] == '':\n continue\n if len(r[k]) != 3 or r[k].lower() != r[k] or any(not 96 < ord(x\n ) < 123 for x in r[k]):\n self.fail('{Lang_Id} has faulty ISO639 code of {ISO 639-3}'\n .format(**r))\n\n def test_deprecated(self):\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n inf = self.iana.language.get(l.lang, {})\n if 'Deprecated' in inf:\n if r['deprecated'] == '':\n self.fail(\n '{Lang_Id} was deprecated: {} in IANA but not in the database'\n .format(inf['Deprecated'], **r))\n\n\n<mask token>\n", "step-3": "<mask token>\nlangtagjson = os.path.join(os.path.dirname(__file__), '..', 'pub',\n 'langtags.json')\nbannedchars = list(range(33, 45)) + [47] + list(range(58, 63)) + [94, 96]\n\n\ndef nonascii(s):\n cs = [ord(x) for x in s]\n if any(not 32 <= x < 123 or x in bannedchars for x in cs):\n return True\n\n\nclass Basic(unittest.TestCase):\n extraScripts = ['Toto', 'Vith']\n extraLangs = ('000', 'cxh', 'dsk', 'dyr', 'eud', 'ikh', 'izm', 'lgs',\n 'lvl', 'nzr', 'pze', 'rsw', 'tvi', 'uly', 'vjk', 'wtb', 'ycr',\n 'ykh', 'zem', 'zlu')\n\n def setUp(self):\n self.fname = os.path.join(os.path.dirname(__file__),\n '../source/langtags.csv')\n with open(self.fname) as csvfile:\n reader = csv.DictReader(csvfile, restkey='_')\n self.rows = list(reader)\n self.fieldnames = reader.fieldnames\n self.numlines = reader.line_num\n self.iana = Iana()\n\n def _region_test(self, x):\n if x in self.iana.region:\n return True\n elif x in ('XX', 'XK'):\n return True\n return False\n\n def _allRows(self):\n for r in self.rows:\n t = langtag(r['likely_subtag'])\n if t.lang.startswith('x-'):\n continue\n yield r, t\n\n def test_lang(self):\n \"\"\" Tests that all lang subtags are in iana \"\"\"\n fails = []\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if l.lang != t.lang and '-' not in l.lang and '-' not in t.lang:\n self.fail(\n '{Lang_Id} has different lang to {likely_subtag} ({0} != {1})'\n .format(l.lang, t.lang, **r))\n if (t.lang not in self.iana.language and '-' not in t.lang and \n t.lang not in self.extraLangs):\n fails.append(r['Lang_Id'])\n if not l.test(fname=langtagjson):\n self.fail('{Lang_Id} failed conformance check'.format(**r))\n if len(fails):\n self.fail(f'{fails} langs not in IANA')\n\n def test_region(self):\n \"\"\" Test that region values are sensible and that they equal the default region.\n Unknown regions do not have to be specified. \"\"\"\n for r, t in self._allRows():\n reg = t.region\n if not self._region_test(t.region):\n self.fail('{likely_subtag} has irregular region'.format(**r))\n for s in r['regions'].split():\n if not self._region_test(s.strip()):\n self.fail('{Lang_Id} has irregular region: {0} in regions'\n .format(s, **r))\n\n def test_script(self):\n \"\"\" Qaa? type scripts must have an -x- for the script name \"\"\"\n for r, t in self._allRows():\n scr = t.script\n if scr is not None and (scr.startswith('Qaa') or scr.startswith\n ('Qab')):\n if scr not in ('Qaax', 'Qaby', 'Qabz') and (t.extensions is\n None or 'x' not in t.extensions):\n self.fail('{Lang_Id} has no extension for script name'.\n format(**r))\n elif scr not in self.iana.script and scr not in self.extraScripts:\n self.fail('{Lang_Id} has irregular script {}'.format(scr, **r))\n elif t.script not in self.iana.script and t.script not in self.extraScripts:\n self.fail('{likely_subtag} has irregular script'.format(**r))\n\n def test_variants(self):\n \"\"\" Test that all variants are in IANA \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.vars is None and l.vars is None:\n continue\n if sorted(t.vars) != sorted(l.vars):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different variants'\n .format(**r))\n for v in t.vars:\n if v not in self.iana.variant:\n self.fail('{likely_subtag} has bad variant {0}'.format(\n v, **r))\n\n def test_csv_columns(self):\n \"\"\" Test that everyone has the right number of columns \"\"\"\n lc = self.fieldnames[-1]\n for r in self.rows:\n if len(r.get('_', [])):\n self.fail('{Lang_Id} has too many columns'.format(**r))\n elif r[lc] is None:\n self.fail('{Lang_Id} has too few columns'.format(**r))\n\n def test_pua(self):\n \"\"\" Test that anything with -x- in Lang_Id has it in likely_subtag too \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.ns is None and l.ns is None:\n continue\n if len(t.ns) == 1 and 'x' in t.ns and len(t.ns['x']) == 1:\n continue\n if sorted(t.ns.keys()) != sorted(l.ns.keys()):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extension namespaces'\n .format(**r))\n for k, v in t.ns.items():\n if sorted(v) != sorted(l.ns[k]):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extensions in the {0} namespace'\n .format(k, **r))\n\n def test_ascii(self):\n \"\"\" Test that all tags are pure ascii \"\"\"\n for r, t in self._allRows():\n for cid in ('Lang_Id', 'likely_subtag', 'regions', 'ISO 639-3',\n 'Macro', 'variants'):\n if nonascii(r[cid]):\n self.fail('{Lang_Id} has non ASCII in column {0} value {1}'\n .format(cid, r[cid], **r))\n\n def test_iso639(self):\n \"\"\" Test that the iso639 column is either empty or 3 lower ascii chars. \"\"\"\n k = 'ISO 639-3'\n for r, t in self._allRows():\n if r[k] == '':\n continue\n if len(r[k]) != 3 or r[k].lower() != r[k] or any(not 96 < ord(x\n ) < 123 for x in r[k]):\n self.fail('{Lang_Id} has faulty ISO639 code of {ISO 639-3}'\n .format(**r))\n\n def test_deprecated(self):\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n inf = self.iana.language.get(l.lang, {})\n if 'Deprecated' in inf:\n if r['deprecated'] == '':\n self.fail(\n '{Lang_Id} was deprecated: {} in IANA but not in the database'\n .format(inf['Deprecated'], **r))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-4": "import os, re\nimport csv, unittest\nfrom langtag import langtag\nfrom sldr.iana import Iana\nlangtagjson = os.path.join(os.path.dirname(__file__), '..', 'pub',\n 'langtags.json')\nbannedchars = list(range(33, 45)) + [47] + list(range(58, 63)) + [94, 96]\n\n\ndef nonascii(s):\n cs = [ord(x) for x in s]\n if any(not 32 <= x < 123 or x in bannedchars for x in cs):\n return True\n\n\nclass Basic(unittest.TestCase):\n extraScripts = ['Toto', 'Vith']\n extraLangs = ('000', 'cxh', 'dsk', 'dyr', 'eud', 'ikh', 'izm', 'lgs',\n 'lvl', 'nzr', 'pze', 'rsw', 'tvi', 'uly', 'vjk', 'wtb', 'ycr',\n 'ykh', 'zem', 'zlu')\n\n def setUp(self):\n self.fname = os.path.join(os.path.dirname(__file__),\n '../source/langtags.csv')\n with open(self.fname) as csvfile:\n reader = csv.DictReader(csvfile, restkey='_')\n self.rows = list(reader)\n self.fieldnames = reader.fieldnames\n self.numlines = reader.line_num\n self.iana = Iana()\n\n def _region_test(self, x):\n if x in self.iana.region:\n return True\n elif x in ('XX', 'XK'):\n return True\n return False\n\n def _allRows(self):\n for r in self.rows:\n t = langtag(r['likely_subtag'])\n if t.lang.startswith('x-'):\n continue\n yield r, t\n\n def test_lang(self):\n \"\"\" Tests that all lang subtags are in iana \"\"\"\n fails = []\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if l.lang != t.lang and '-' not in l.lang and '-' not in t.lang:\n self.fail(\n '{Lang_Id} has different lang to {likely_subtag} ({0} != {1})'\n .format(l.lang, t.lang, **r))\n if (t.lang not in self.iana.language and '-' not in t.lang and \n t.lang not in self.extraLangs):\n fails.append(r['Lang_Id'])\n if not l.test(fname=langtagjson):\n self.fail('{Lang_Id} failed conformance check'.format(**r))\n if len(fails):\n self.fail(f'{fails} langs not in IANA')\n\n def test_region(self):\n \"\"\" Test that region values are sensible and that they equal the default region.\n Unknown regions do not have to be specified. \"\"\"\n for r, t in self._allRows():\n reg = t.region\n if not self._region_test(t.region):\n self.fail('{likely_subtag} has irregular region'.format(**r))\n for s in r['regions'].split():\n if not self._region_test(s.strip()):\n self.fail('{Lang_Id} has irregular region: {0} in regions'\n .format(s, **r))\n\n def test_script(self):\n \"\"\" Qaa? type scripts must have an -x- for the script name \"\"\"\n for r, t in self._allRows():\n scr = t.script\n if scr is not None and (scr.startswith('Qaa') or scr.startswith\n ('Qab')):\n if scr not in ('Qaax', 'Qaby', 'Qabz') and (t.extensions is\n None or 'x' not in t.extensions):\n self.fail('{Lang_Id} has no extension for script name'.\n format(**r))\n elif scr not in self.iana.script and scr not in self.extraScripts:\n self.fail('{Lang_Id} has irregular script {}'.format(scr, **r))\n elif t.script not in self.iana.script and t.script not in self.extraScripts:\n self.fail('{likely_subtag} has irregular script'.format(**r))\n\n def test_variants(self):\n \"\"\" Test that all variants are in IANA \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.vars is None and l.vars is None:\n continue\n if sorted(t.vars) != sorted(l.vars):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different variants'\n .format(**r))\n for v in t.vars:\n if v not in self.iana.variant:\n self.fail('{likely_subtag} has bad variant {0}'.format(\n v, **r))\n\n def test_csv_columns(self):\n \"\"\" Test that everyone has the right number of columns \"\"\"\n lc = self.fieldnames[-1]\n for r in self.rows:\n if len(r.get('_', [])):\n self.fail('{Lang_Id} has too many columns'.format(**r))\n elif r[lc] is None:\n self.fail('{Lang_Id} has too few columns'.format(**r))\n\n def test_pua(self):\n \"\"\" Test that anything with -x- in Lang_Id has it in likely_subtag too \"\"\"\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.ns is None and l.ns is None:\n continue\n if len(t.ns) == 1 and 'x' in t.ns and len(t.ns['x']) == 1:\n continue\n if sorted(t.ns.keys()) != sorted(l.ns.keys()):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extension namespaces'\n .format(**r))\n for k, v in t.ns.items():\n if sorted(v) != sorted(l.ns[k]):\n self.fail(\n '{Lang_Id} and {likely_subtag} have different extensions in the {0} namespace'\n .format(k, **r))\n\n def test_ascii(self):\n \"\"\" Test that all tags are pure ascii \"\"\"\n for r, t in self._allRows():\n for cid in ('Lang_Id', 'likely_subtag', 'regions', 'ISO 639-3',\n 'Macro', 'variants'):\n if nonascii(r[cid]):\n self.fail('{Lang_Id} has non ASCII in column {0} value {1}'\n .format(cid, r[cid], **r))\n\n def test_iso639(self):\n \"\"\" Test that the iso639 column is either empty or 3 lower ascii chars. \"\"\"\n k = 'ISO 639-3'\n for r, t in self._allRows():\n if r[k] == '':\n continue\n if len(r[k]) != 3 or r[k].lower() != r[k] or any(not 96 < ord(x\n ) < 123 for x in r[k]):\n self.fail('{Lang_Id} has faulty ISO639 code of {ISO 639-3}'\n .format(**r))\n\n def test_deprecated(self):\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n inf = self.iana.language.get(l.lang, {})\n if 'Deprecated' in inf:\n if r['deprecated'] == '':\n self.fail(\n '{Lang_Id} was deprecated: {} in IANA but not in the database'\n .format(inf['Deprecated'], **r))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-5": "#!/usr/bin/python3\n\nimport os, re\nimport csv, unittest\nfrom langtag import langtag\nfrom sldr.iana import Iana\n\nlangtagjson = os.path.join(os.path.dirname(__file__), '..', 'pub', 'langtags.json')\nbannedchars = list(range(33, 45)) + [47] + list(range(58, 63)) + [94, 96]\ndef nonascii(s):\n cs = [ord(x) for x in s]\n if any(not (32 <= x < 123) or x in bannedchars for x in cs):\n return True\n\nclass Basic(unittest.TestCase):\n\n extraScripts = [\"Toto\", \"Vith\"]\n extraLangs = (\"000\", \n \"cxh\", \"dsk\", \"dyr\", \"eud\", \"ikh\", \"izm\", \"lgs\", # going in ~23/Mar/2023\n 'lvl', 'nzr', 'pze', 'rsw', 'tvi', 'uly', 'vjk', 'wtb', 'ycr', 'ykh', 'zem', 'zlu') # going in ~23/Mar/2023\n\n def setUp(self):\n self.fname = os.path.join(os.path.dirname(__file__), '../source/langtags.csv')\n with open(self.fname) as csvfile:\n reader = csv.DictReader(csvfile, restkey=\"_\")\n self.rows = list(reader)\n self.fieldnames = reader.fieldnames\n self.numlines = reader.line_num\n self.iana = Iana()\n\n def _region_test(self, x):\n if x in self.iana.region:\n return True\n elif x in (\"XX\", \"XK\"):\n return True\n return False\n\n def _allRows(self):\n for r in self.rows:\n t = langtag(r['likely_subtag'])\n if t.lang.startswith(\"x-\"):\n continue\n yield (r, t)\n\n def test_lang(self):\n ''' Tests that all lang subtags are in iana '''\n fails = []\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if l.lang != t.lang and \"-\" not in l.lang and \"-\" not in t.lang:\n self.fail(\"{Lang_Id} has different lang to {likely_subtag} ({0} != {1})\".format(l.lang, t.lang, **r))\n if t.lang not in self.iana.language and \"-\" not in t.lang and t.lang not in self.extraLangs:\n fails.append(r['Lang_Id'])\n if not l.test(fname=langtagjson):\n self.fail(\"{Lang_Id} failed conformance check\".format(**r))\n if len(fails):\n self.fail(f\"{fails} langs not in IANA\")\n\n\n def test_region(self):\n ''' Test that region values are sensible and that they equal the default region.\n Unknown regions do not have to be specified. '''\n for r,t in self._allRows():\n reg = t.region\n if not self._region_test(t.region):\n self.fail(\"{likely_subtag} has irregular region\".format(**r))\n for s in r['regions'].split():\n if not self._region_test(s.strip()):\n self.fail(\"{Lang_Id} has irregular region: {0} in regions\".format(s, **r))\n\n def test_script(self):\n ''' Qaa? type scripts must have an -x- for the script name '''\n for r, t in self._allRows():\n scr = t.script\n if scr is not None and (scr.startswith(\"Qaa\") or scr.startswith(\"Qab\")):\n if scr not in (\"Qaax\", \"Qaby\", \"Qabz\") and (t.extensions is None or 'x' not in t.extensions):\n self.fail(\"{Lang_Id} has no extension for script name\".format(**r))\n elif scr not in self.iana.script and scr not in self.extraScripts:\n self.fail(\"{Lang_Id} has irregular script {}\".format(scr, **r))\n elif t.script not in self.iana.script and t.script not in self.extraScripts:\n self.fail(\"{likely_subtag} has irregular script\".format(**r))\n\n def test_variants(self):\n ''' Test that all variants are in IANA '''\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.vars is None and l.vars is None:\n continue\n if sorted(t.vars) != sorted(l.vars):\n self.fail(\"{Lang_Id} and {likely_subtag} have different variants\".format(**r))\n for v in t.vars:\n if v not in self.iana.variant:\n self.fail(\"{likely_subtag} has bad variant {0}\".format(v, **r))\n\n def test_csv_columns(self):\n ''' Test that everyone has the right number of columns '''\n lc = self.fieldnames[-1]\n for r in self.rows:\n if len(r.get(\"_\", [])):\n self.fail(\"{Lang_Id} has too many columns\".format(**r))\n elif r[lc] is None:\n self.fail(\"{Lang_Id} has too few columns\".format(**r))\n\n def test_pua(self):\n ''' Test that anything with -x- in Lang_Id has it in likely_subtag too '''\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n if t.ns is None and l.ns is None:\n continue\n if len(t.ns) == 1 and 'x' in t.ns and len(t.ns['x']) == 1:\n continue # allow a private script extension\n if sorted(t.ns.keys()) != sorted(l.ns.keys()):\n self.fail(\"{Lang_Id} and {likely_subtag} have different extension namespaces\".format(**r))\n for k, v in t.ns.items():\n if sorted(v) != sorted(l.ns[k]):\n self.fail(\"{Lang_Id} and {likely_subtag} have different extensions in the {0} namespace\".format(k, **r))\n\n def test_ascii(self):\n ''' Test that all tags are pure ascii '''\n for r, t in self._allRows():\n for cid in ('Lang_Id', 'likely_subtag', 'regions', 'ISO 639-3', 'Macro', 'variants'):\n if nonascii(r[cid]):\n self.fail(\"{Lang_Id} has non ASCII in column {0} value {1}\".format(cid, r[cid], **r))\n\n def test_iso639(self):\n ''' Test that the iso639 column is either empty or 3 lower ascii chars. '''\n k = 'ISO 639-3'\n for r, t in self._allRows():\n if r[k] == '':\n continue\n if len(r[k]) != 3 or r[k].lower() != r[k] or any(not (96 < ord(x) < 123) for x in r[k]):\n self.fail(\"{Lang_Id} has faulty ISO639 code of {ISO 639-3}\".format(**r))\n\n def test_deprecated(self):\n for r, t in self._allRows():\n l = langtag(r['Lang_Id'])\n inf = self.iana.language.get(l.lang, {})\n if 'Deprecated' in inf:\n if r['deprecated'] == '':\n self.fail(\"{Lang_Id} was deprecated: {} in IANA but not in the database\".format(inf['Deprecated'], **r))\n\nif __name__ == \"__main__\":\n unittest.main()\n", "step-ids": [ 11, 13, 17, 18, 19 ] }
[ 11, 13, 17, 18, 19 ]
from tkinter import * root = Tk() photo = PhotoImage(file='flag.png') panel = Label(root, image=photo) panel.pack() root.mainloop()
normal
{ "blob_id": "2d192963bfe046bce1a0c82e0179380693f5c541", "index": 9518, "step-1": "<mask token>\n", "step-2": "<mask token>\npanel.pack()\nroot.mainloop()\n", "step-3": "<mask token>\nroot = Tk()\nphoto = PhotoImage(file='flag.png')\npanel = Label(root, image=photo)\npanel.pack()\nroot.mainloop()\n", "step-4": "from tkinter import *\nroot = Tk()\nphoto = PhotoImage(file='flag.png')\npanel = Label(root, image=photo)\npanel.pack()\nroot.mainloop()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import sys import time import pymorphy2 import pyglet import pyttsx3 import threading import warnings import pytils warnings.filterwarnings("ignore") """ Количество раундов, вдохов в раунде, задержка дыхания на вдохе""" rounds, breaths, hold = 4, 30, 13 def play_wav(src): wav = pyglet.media.load(sys.path[0] + '\\src\\wav\\' + src + '.wav') wav.play() time.sleep(wav.duration) def play_wav_inline(src): wav = pyglet.media.load(sys.path[0] + '\\src\\wav\\' + src + '.wav') wav.play() def correct_numerals(phrase, morph=pymorphy2.MorphAnalyzer()): new_phrase = [] py_gen = 1 phrase = phrase.split(' ') while phrase: word = phrase.pop(-1) if 'NUMB' in morph.parse(word)[0].tag: new_phrase.append(pytils.numeral.sum_string(int(word), py_gen)) else: new_phrase.append(word) py_gen = pytils.numeral.FEMALE if 'femn' in morph.parse(word)[0].tag else pytils.numeral.MALE return ' '.join(new_phrase[::-1]) def nums(phrase, morph=pymorphy2.MorphAnalyzer()): """ согласование существительных с числительными, стоящими перед ними """ phrase = phrase.replace(' ', ' ').replace(',', ' ,') numeral = '' new_phrase = [] for word in phrase.split(' '): if 'NUMB' in morph.parse(word)[0].tag: numeral = word if numeral: word = str(morph.parse(word)[0].make_agree_with_number(abs(int(numeral))).word) new_phrase.append(word) return ' '.join(new_phrase).replace(' ,', ',') def speak(what): speech_voice = 3 # голосовой движок rate = 120 tts = pyttsx3.init() voices = tts.getProperty("voices") tts.setProperty('rate', rate) tts.setProperty("voice", voices[speech_voice].id) print('🔊', what) what = correct_numerals(what) tts.say(what) tts.runAndWait() # tts.stop() class Workout: def __init__(self, rounds=3, breaths=30, hold=15): self.rounds = rounds self.breaths = breaths self.hold = hold self.round_times = [] self.lock = threading.Lock() # взаимоблокировка отдельных голосовых потоков def __str__(self): return '\n♻{} 🗣{} ⏱{}'.format(self.rounds, self.breaths, self.hold) def __hold_breath(self): start_time = time.time() input() seconds = int(time.time() - start_time) mins = seconds // 60 secs = seconds % 60 self.round_times.append('{:02}:{:02}'.format(mins, secs)) play_wav_inline('inhale') self.say('Глубокий вдох. ' + nums("{} минута {} секунда".format(mins, secs))) def __clock_tick(self): for i in range(self.hold): if i < hold - 3: time.sleep(1) else: play_wav('clock') play_wav_inline('gong2') def __breathe_round(self, round): self.say('Раунд ' + str(round)) for i in range(self.breaths): if i % 10 == 0: play_wav_inline('gong') play_wav('inhale') print(i + 1, end=' ') play_wav('exhale') print() self.say('Задерживаем дыхание на выдохе') self.__hold_breath() # self.say('Держим ' + nums(str(self.hold) + ' секунда')) self.__clock_tick() play_wav_inline('exhale') self.say('Выдох') time.sleep(1) def breathe(self): self.say('Выполняем ' + nums(str(self.rounds) + ' раунд')) self.say('Каждый раунд это ' + nums(str(self.breaths) + ' глубокий вдох - и спокойный выдох')) self.say('Приготовились...') for i in range(self.rounds): self.__breathe_round(i + 1) self.say('Восстанавливаем дыхание.') def statistics(self): print('=============') for i in range(len(self.round_times)): print('Раунд', i, self.round_times[i]) print('=============') def say(self, what): self.lock.acquire() thread = threading.Thread(target=speak, kwargs={'what': what}) thread.start() thread.join() self.lock.release() workout = Workout(rounds, breaths, hold) workout.breathe() workout.statistics()
normal
{ "blob_id": "a98be930058269a6adbc9a28d1c0ad5d9abba136", "index": 35, "step-1": "<mask token>\n\n\ndef nums(phrase, morph=pymorphy2.MorphAnalyzer()):\n \"\"\" согласование существительных с числительными, стоящими перед ними \"\"\"\n phrase = phrase.replace(' ', ' ').replace(',', ' ,')\n numeral = ''\n new_phrase = []\n for word in phrase.split(' '):\n if 'NUMB' in morph.parse(word)[0].tag:\n numeral = word\n if numeral:\n word = str(morph.parse(word)[0].make_agree_with_number(abs(int(\n numeral))).word)\n new_phrase.append(word)\n return ' '.join(new_phrase).replace(' ,', ',')\n\n\n<mask token>\n\n\nclass Workout:\n\n def __init__(self, rounds=3, breaths=30, hold=15):\n self.rounds = rounds\n self.breaths = breaths\n self.hold = hold\n self.round_times = []\n self.lock = threading.Lock()\n\n def __str__(self):\n return '\\n♻{} 🗣{} ⏱{}'.format(self.rounds, self.breaths, self.hold)\n\n def __hold_breath(self):\n start_time = time.time()\n input()\n seconds = int(time.time() - start_time)\n mins = seconds // 60\n secs = seconds % 60\n self.round_times.append('{:02}:{:02}'.format(mins, secs))\n play_wav_inline('inhale')\n self.say('Глубокий вдох. ' + nums('{} минута {} секунда'.format(\n mins, secs)))\n\n def __clock_tick(self):\n for i in range(self.hold):\n if i < hold - 3:\n time.sleep(1)\n else:\n play_wav('clock')\n play_wav_inline('gong2')\n\n def __breathe_round(self, round):\n self.say('Раунд ' + str(round))\n for i in range(self.breaths):\n if i % 10 == 0:\n play_wav_inline('gong')\n play_wav('inhale')\n print(i + 1, end=' ')\n play_wav('exhale')\n print()\n self.say('Задерживаем дыхание на выдохе')\n self.__hold_breath()\n self.__clock_tick()\n play_wav_inline('exhale')\n self.say('Выдох')\n time.sleep(1)\n\n def breathe(self):\n self.say('Выполняем ' + nums(str(self.rounds) + ' раунд'))\n self.say('Каждый раунд это ' + nums(str(self.breaths) +\n ' глубокий вдох - и спокойный выдох'))\n self.say('Приготовились...')\n for i in range(self.rounds):\n self.__breathe_round(i + 1)\n self.say('Восстанавливаем дыхание.')\n\n def statistics(self):\n print('=============')\n for i in range(len(self.round_times)):\n print('Раунд', i, self.round_times[i])\n print('=============')\n\n def say(self, what):\n self.lock.acquire()\n thread = threading.Thread(target=speak, kwargs={'what': what})\n thread.start()\n thread.join()\n self.lock.release()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef play_wav(src):\n wav = pyglet.media.load(sys.path[0] + '\\\\src\\\\wav\\\\' + src + '.wav')\n wav.play()\n time.sleep(wav.duration)\n\n\n<mask token>\n\n\ndef nums(phrase, morph=pymorphy2.MorphAnalyzer()):\n \"\"\" согласование существительных с числительными, стоящими перед ними \"\"\"\n phrase = phrase.replace(' ', ' ').replace(',', ' ,')\n numeral = ''\n new_phrase = []\n for word in phrase.split(' '):\n if 'NUMB' in morph.parse(word)[0].tag:\n numeral = word\n if numeral:\n word = str(morph.parse(word)[0].make_agree_with_number(abs(int(\n numeral))).word)\n new_phrase.append(word)\n return ' '.join(new_phrase).replace(' ,', ',')\n\n\n<mask token>\n\n\nclass Workout:\n\n def __init__(self, rounds=3, breaths=30, hold=15):\n self.rounds = rounds\n self.breaths = breaths\n self.hold = hold\n self.round_times = []\n self.lock = threading.Lock()\n\n def __str__(self):\n return '\\n♻{} 🗣{} ⏱{}'.format(self.rounds, self.breaths, self.hold)\n\n def __hold_breath(self):\n start_time = time.time()\n input()\n seconds = int(time.time() - start_time)\n mins = seconds // 60\n secs = seconds % 60\n self.round_times.append('{:02}:{:02}'.format(mins, secs))\n play_wav_inline('inhale')\n self.say('Глубокий вдох. ' + nums('{} минута {} секунда'.format(\n mins, secs)))\n\n def __clock_tick(self):\n for i in range(self.hold):\n if i < hold - 3:\n time.sleep(1)\n else:\n play_wav('clock')\n play_wav_inline('gong2')\n\n def __breathe_round(self, round):\n self.say('Раунд ' + str(round))\n for i in range(self.breaths):\n if i % 10 == 0:\n play_wav_inline('gong')\n play_wav('inhale')\n print(i + 1, end=' ')\n play_wav('exhale')\n print()\n self.say('Задерживаем дыхание на выдохе')\n self.__hold_breath()\n self.__clock_tick()\n play_wav_inline('exhale')\n self.say('Выдох')\n time.sleep(1)\n\n def breathe(self):\n self.say('Выполняем ' + nums(str(self.rounds) + ' раунд'))\n self.say('Каждый раунд это ' + nums(str(self.breaths) +\n ' глубокий вдох - и спокойный выдох'))\n self.say('Приготовились...')\n for i in range(self.rounds):\n self.__breathe_round(i + 1)\n self.say('Восстанавливаем дыхание.')\n\n def statistics(self):\n print('=============')\n for i in range(len(self.round_times)):\n print('Раунд', i, self.round_times[i])\n print('=============')\n\n def say(self, what):\n self.lock.acquire()\n thread = threading.Thread(target=speak, kwargs={'what': what})\n thread.start()\n thread.join()\n self.lock.release()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef play_wav(src):\n wav = pyglet.media.load(sys.path[0] + '\\\\src\\\\wav\\\\' + src + '.wav')\n wav.play()\n time.sleep(wav.duration)\n\n\ndef play_wav_inline(src):\n wav = pyglet.media.load(sys.path[0] + '\\\\src\\\\wav\\\\' + src + '.wav')\n wav.play()\n\n\n<mask token>\n\n\ndef nums(phrase, morph=pymorphy2.MorphAnalyzer()):\n \"\"\" согласование существительных с числительными, стоящими перед ними \"\"\"\n phrase = phrase.replace(' ', ' ').replace(',', ' ,')\n numeral = ''\n new_phrase = []\n for word in phrase.split(' '):\n if 'NUMB' in morph.parse(word)[0].tag:\n numeral = word\n if numeral:\n word = str(morph.parse(word)[0].make_agree_with_number(abs(int(\n numeral))).word)\n new_phrase.append(word)\n return ' '.join(new_phrase).replace(' ,', ',')\n\n\ndef speak(what):\n speech_voice = 3\n rate = 120\n tts = pyttsx3.init()\n voices = tts.getProperty('voices')\n tts.setProperty('rate', rate)\n tts.setProperty('voice', voices[speech_voice].id)\n print('🔊', what)\n what = correct_numerals(what)\n tts.say(what)\n tts.runAndWait()\n\n\nclass Workout:\n\n def __init__(self, rounds=3, breaths=30, hold=15):\n self.rounds = rounds\n self.breaths = breaths\n self.hold = hold\n self.round_times = []\n self.lock = threading.Lock()\n\n def __str__(self):\n return '\\n♻{} 🗣{} ⏱{}'.format(self.rounds, self.breaths, self.hold)\n\n def __hold_breath(self):\n start_time = time.time()\n input()\n seconds = int(time.time() - start_time)\n mins = seconds // 60\n secs = seconds % 60\n self.round_times.append('{:02}:{:02}'.format(mins, secs))\n play_wav_inline('inhale')\n self.say('Глубокий вдох. ' + nums('{} минута {} секунда'.format(\n mins, secs)))\n\n def __clock_tick(self):\n for i in range(self.hold):\n if i < hold - 3:\n time.sleep(1)\n else:\n play_wav('clock')\n play_wav_inline('gong2')\n\n def __breathe_round(self, round):\n self.say('Раунд ' + str(round))\n for i in range(self.breaths):\n if i % 10 == 0:\n play_wav_inline('gong')\n play_wav('inhale')\n print(i + 1, end=' ')\n play_wav('exhale')\n print()\n self.say('Задерживаем дыхание на выдохе')\n self.__hold_breath()\n self.__clock_tick()\n play_wav_inline('exhale')\n self.say('Выдох')\n time.sleep(1)\n\n def breathe(self):\n self.say('Выполняем ' + nums(str(self.rounds) + ' раунд'))\n self.say('Каждый раунд это ' + nums(str(self.breaths) +\n ' глубокий вдох - и спокойный выдох'))\n self.say('Приготовились...')\n for i in range(self.rounds):\n self.__breathe_round(i + 1)\n self.say('Восстанавливаем дыхание.')\n\n def statistics(self):\n print('=============')\n for i in range(len(self.round_times)):\n print('Раунд', i, self.round_times[i])\n print('=============')\n\n def say(self, what):\n self.lock.acquire()\n thread = threading.Thread(target=speak, kwargs={'what': what})\n thread.start()\n thread.join()\n self.lock.release()\n\n\n<mask token>\n", "step-4": "import sys\nimport time\nimport pymorphy2\nimport pyglet\nimport pyttsx3\nimport threading\nimport warnings\nimport pytils\nwarnings.filterwarnings('ignore')\n<mask token>\nrounds, breaths, hold = 4, 30, 13\n\n\ndef play_wav(src):\n wav = pyglet.media.load(sys.path[0] + '\\\\src\\\\wav\\\\' + src + '.wav')\n wav.play()\n time.sleep(wav.duration)\n\n\ndef play_wav_inline(src):\n wav = pyglet.media.load(sys.path[0] + '\\\\src\\\\wav\\\\' + src + '.wav')\n wav.play()\n\n\ndef correct_numerals(phrase, morph=pymorphy2.MorphAnalyzer()):\n new_phrase = []\n py_gen = 1\n phrase = phrase.split(' ')\n while phrase:\n word = phrase.pop(-1)\n if 'NUMB' in morph.parse(word)[0].tag:\n new_phrase.append(pytils.numeral.sum_string(int(word), py_gen))\n else:\n new_phrase.append(word)\n py_gen = pytils.numeral.FEMALE if 'femn' in morph.parse(word)[0\n ].tag else pytils.numeral.MALE\n return ' '.join(new_phrase[::-1])\n\n\ndef nums(phrase, morph=pymorphy2.MorphAnalyzer()):\n \"\"\" согласование существительных с числительными, стоящими перед ними \"\"\"\n phrase = phrase.replace(' ', ' ').replace(',', ' ,')\n numeral = ''\n new_phrase = []\n for word in phrase.split(' '):\n if 'NUMB' in morph.parse(word)[0].tag:\n numeral = word\n if numeral:\n word = str(morph.parse(word)[0].make_agree_with_number(abs(int(\n numeral))).word)\n new_phrase.append(word)\n return ' '.join(new_phrase).replace(' ,', ',')\n\n\ndef speak(what):\n speech_voice = 3\n rate = 120\n tts = pyttsx3.init()\n voices = tts.getProperty('voices')\n tts.setProperty('rate', rate)\n tts.setProperty('voice', voices[speech_voice].id)\n print('🔊', what)\n what = correct_numerals(what)\n tts.say(what)\n tts.runAndWait()\n\n\nclass Workout:\n\n def __init__(self, rounds=3, breaths=30, hold=15):\n self.rounds = rounds\n self.breaths = breaths\n self.hold = hold\n self.round_times = []\n self.lock = threading.Lock()\n\n def __str__(self):\n return '\\n♻{} 🗣{} ⏱{}'.format(self.rounds, self.breaths, self.hold)\n\n def __hold_breath(self):\n start_time = time.time()\n input()\n seconds = int(time.time() - start_time)\n mins = seconds // 60\n secs = seconds % 60\n self.round_times.append('{:02}:{:02}'.format(mins, secs))\n play_wav_inline('inhale')\n self.say('Глубокий вдох. ' + nums('{} минута {} секунда'.format(\n mins, secs)))\n\n def __clock_tick(self):\n for i in range(self.hold):\n if i < hold - 3:\n time.sleep(1)\n else:\n play_wav('clock')\n play_wav_inline('gong2')\n\n def __breathe_round(self, round):\n self.say('Раунд ' + str(round))\n for i in range(self.breaths):\n if i % 10 == 0:\n play_wav_inline('gong')\n play_wav('inhale')\n print(i + 1, end=' ')\n play_wav('exhale')\n print()\n self.say('Задерживаем дыхание на выдохе')\n self.__hold_breath()\n self.__clock_tick()\n play_wav_inline('exhale')\n self.say('Выдох')\n time.sleep(1)\n\n def breathe(self):\n self.say('Выполняем ' + nums(str(self.rounds) + ' раунд'))\n self.say('Каждый раунд это ' + nums(str(self.breaths) +\n ' глубокий вдох - и спокойный выдох'))\n self.say('Приготовились...')\n for i in range(self.rounds):\n self.__breathe_round(i + 1)\n self.say('Восстанавливаем дыхание.')\n\n def statistics(self):\n print('=============')\n for i in range(len(self.round_times)):\n print('Раунд', i, self.round_times[i])\n print('=============')\n\n def say(self, what):\n self.lock.acquire()\n thread = threading.Thread(target=speak, kwargs={'what': what})\n thread.start()\n thread.join()\n self.lock.release()\n\n\nworkout = Workout(rounds, breaths, hold)\nworkout.breathe()\nworkout.statistics()\n", "step-5": "import sys\nimport time\nimport pymorphy2\nimport pyglet\nimport pyttsx3\nimport threading\nimport warnings\nimport pytils\n\nwarnings.filterwarnings(\"ignore\")\n\n\"\"\" Количество раундов, вдохов в раунде, задержка дыхания на вдохе\"\"\"\nrounds, breaths, hold = 4, 30, 13\n\n\ndef play_wav(src):\n wav = pyglet.media.load(sys.path[0] + '\\\\src\\\\wav\\\\' + src + '.wav')\n wav.play()\n time.sleep(wav.duration)\n\n\ndef play_wav_inline(src):\n wav = pyglet.media.load(sys.path[0] + '\\\\src\\\\wav\\\\' + src + '.wav')\n wav.play()\n\n\ndef correct_numerals(phrase, morph=pymorphy2.MorphAnalyzer()):\n new_phrase = []\n py_gen = 1\n phrase = phrase.split(' ')\n while phrase:\n word = phrase.pop(-1)\n if 'NUMB' in morph.parse(word)[0].tag:\n new_phrase.append(pytils.numeral.sum_string(int(word), py_gen))\n else:\n new_phrase.append(word)\n py_gen = pytils.numeral.FEMALE if 'femn' in morph.parse(word)[0].tag else pytils.numeral.MALE\n return ' '.join(new_phrase[::-1])\n\n\ndef nums(phrase, morph=pymorphy2.MorphAnalyzer()):\n \"\"\" согласование существительных с числительными, стоящими перед ними \"\"\"\n phrase = phrase.replace(' ', ' ').replace(',', ' ,')\n numeral = ''\n new_phrase = []\n for word in phrase.split(' '):\n if 'NUMB' in morph.parse(word)[0].tag:\n numeral = word\n if numeral:\n word = str(morph.parse(word)[0].make_agree_with_number(abs(int(numeral))).word)\n new_phrase.append(word)\n\n return ' '.join(new_phrase).replace(' ,', ',')\n\n\ndef speak(what):\n speech_voice = 3 # голосовой движок\n rate = 120\n tts = pyttsx3.init()\n voices = tts.getProperty(\"voices\")\n tts.setProperty('rate', rate)\n tts.setProperty(\"voice\", voices[speech_voice].id)\n print('🔊', what)\n what = correct_numerals(what)\n tts.say(what)\n tts.runAndWait()\n # tts.stop()\n\n\nclass Workout:\n\n def __init__(self, rounds=3, breaths=30, hold=15):\n self.rounds = rounds\n self.breaths = breaths\n self.hold = hold\n self.round_times = []\n self.lock = threading.Lock() # взаимоблокировка отдельных голосовых потоков\n\n def __str__(self):\n return '\\n♻{} 🗣{} ⏱{}'.format(self.rounds, self.breaths, self.hold)\n\n def __hold_breath(self):\n start_time = time.time()\n input()\n seconds = int(time.time() - start_time)\n mins = seconds // 60\n secs = seconds % 60\n self.round_times.append('{:02}:{:02}'.format(mins, secs))\n play_wav_inline('inhale')\n self.say('Глубокий вдох. ' + nums(\"{} минута {} секунда\".format(mins, secs)))\n\n def __clock_tick(self):\n for i in range(self.hold):\n if i < hold - 3:\n time.sleep(1)\n else:\n play_wav('clock')\n play_wav_inline('gong2')\n\n def __breathe_round(self, round):\n self.say('Раунд ' + str(round))\n for i in range(self.breaths):\n if i % 10 == 0:\n play_wav_inline('gong')\n play_wav('inhale')\n print(i + 1, end=' ')\n play_wav('exhale')\n print()\n self.say('Задерживаем дыхание на выдохе')\n self.__hold_breath()\n # self.say('Держим ' + nums(str(self.hold) + ' секунда'))\n self.__clock_tick()\n play_wav_inline('exhale')\n self.say('Выдох')\n time.sleep(1)\n\n def breathe(self):\n self.say('Выполняем ' + nums(str(self.rounds) + ' раунд'))\n self.say('Каждый раунд это ' + nums(str(self.breaths) + ' глубокий вдох - и спокойный выдох'))\n self.say('Приготовились...')\n for i in range(self.rounds):\n self.__breathe_round(i + 1)\n self.say('Восстанавливаем дыхание.')\n\n def statistics(self):\n print('=============')\n for i in range(len(self.round_times)):\n print('Раунд', i, self.round_times[i])\n print('=============')\n\n def say(self, what):\n self.lock.acquire()\n thread = threading.Thread(target=speak, kwargs={'what': what})\n thread.start()\n thread.join()\n self.lock.release()\n\n\nworkout = Workout(rounds, breaths, hold)\nworkout.breathe()\n\nworkout.statistics()\n", "step-ids": [ 10, 11, 13, 17, 18 ] }
[ 10, 11, 13, 17, 18 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> while a != 0: t = a % 10 s = s + t a = a // 10 print(s) <|reserved_special_token_1|> a = int(input()) s = 0 t = 0 while a != 0: t = a % 10 s = s + t a = a // 10 print(s) <|reserved_special_token_1|> a=int(input()) s=0 t=0 while(a!=0): t=a%10 s=s+t a=a//10 print(s)
flexible
{ "blob_id": "6050e83e73faaf40cbd5455efd3ad01e4e131188", "index": 2587, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile a != 0:\n t = a % 10\n s = s + t\n a = a // 10\nprint(s)\n", "step-3": "a = int(input())\ns = 0\nt = 0\nwhile a != 0:\n t = a % 10\n s = s + t\n a = a // 10\nprint(s)\n", "step-4": "a=int(input())\ns=0\nt=0\nwhile(a!=0):\n t=a%10\n s=s+t\n a=a//10\nprint(s)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> try: stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0][ 'StackId'] cfn.delete_stack(StackName=stack_id) print(f'Deleting Stack: {stack_id}') except Exception as e: print('Something went wrong! Make sure to manually delete the stack!') print(e) exit(-1) <|reserved_special_token_1|> <|reserved_special_token_0|> cfn = boto3.client('cloudformation') try: stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0][ 'StackId'] cfn.delete_stack(StackName=stack_id) print(f'Deleting Stack: {stack_id}') except Exception as e: print('Something went wrong! Make sure to manually delete the stack!') print(e) exit(-1) <|reserved_special_token_1|> import boto3 from time import sleep cfn = boto3.client('cloudformation') try: stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0][ 'StackId'] cfn.delete_stack(StackName=stack_id) print(f'Deleting Stack: {stack_id}') except Exception as e: print('Something went wrong! Make sure to manually delete the stack!') print(e) exit(-1) <|reserved_special_token_1|> import boto3 from time import sleep cfn = boto3.client('cloudformation') try: # Get base stack outputs. stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0]['StackId'] cfn.delete_stack(StackName=stack_id) print(f"Deleting Stack: {stack_id}") except Exception as e: print('Something went wrong! Make sure to manually delete the stack!') print(e) exit(-1)
flexible
{ "blob_id": "b3fb210bcdec2ed552c37c6221c1f0f0419d7469", "index": 8478, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0][\n 'StackId']\n cfn.delete_stack(StackName=stack_id)\n print(f'Deleting Stack: {stack_id}')\nexcept Exception as e:\n print('Something went wrong! Make sure to manually delete the stack!')\n print(e)\n exit(-1)\n", "step-3": "<mask token>\ncfn = boto3.client('cloudformation')\ntry:\n stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0][\n 'StackId']\n cfn.delete_stack(StackName=stack_id)\n print(f'Deleting Stack: {stack_id}')\nexcept Exception as e:\n print('Something went wrong! Make sure to manually delete the stack!')\n print(e)\n exit(-1)\n", "step-4": "import boto3\nfrom time import sleep\ncfn = boto3.client('cloudformation')\ntry:\n stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0][\n 'StackId']\n cfn.delete_stack(StackName=stack_id)\n print(f'Deleting Stack: {stack_id}')\nexcept Exception as e:\n print('Something went wrong! Make sure to manually delete the stack!')\n print(e)\n exit(-1)\n", "step-5": "import boto3\nfrom time import sleep\n\ncfn = boto3.client('cloudformation')\n\ntry:\n # Get base stack outputs.\n stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0]['StackId']\n cfn.delete_stack(StackName=stack_id)\n print(f\"Deleting Stack: {stack_id}\")\nexcept Exception as e:\n print('Something went wrong! Make sure to manually delete the stack!')\n print(e)\n exit(-1)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
class boxCar: def __init__(self, *args, **kwargs): print('print the keyword arguments dictionary {0} by {1}'.format( kwargs, 'WANGH')) self.name = kwargs['name'] self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF'] self.configuration = {} def addEcu(self, ecu, domain): if domain.upper() in self.domains: self.configuration.setdefault(domain.upper(), []).append(ecu. upper()) else: print('please input one of the following domain {}'.format([ 'Info', 'Body', 'PWT', 'ADAS', 'Infra'])) <|reserved_special_token_0|> <|reserved_special_token_0|> def setTestPhase(self, phase): if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']: self.testPhase = phase.upper() else: print('please input one of the following domain {}'.format([ 'E1', 'E2', 'E3', 'E4', 'TT', 'PP'])) <|reserved_special_token_0|> <|reserved_special_token_1|> class boxCar: def __init__(self, *args, **kwargs): print('print the keyword arguments dictionary {0} by {1}'.format( kwargs, 'WANGH')) self.name = kwargs['name'] self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF'] self.configuration = {} def addEcu(self, ecu, domain): if domain.upper() in self.domains: self.configuration.setdefault(domain.upper(), []).append(ecu. upper()) else: print('please input one of the following domain {}'.format([ 'Info', 'Body', 'PWT', 'ADAS', 'Infra'])) def deleteEcu(self, ecu, domain): pass def getConfiguration(self): return self.configuration def setTestPhase(self, phase): if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']: self.testPhase = phase.upper() else: print('please input one of the following domain {}'.format([ 'E1', 'E2', 'E3', 'E4', 'TT', 'PP'])) <|reserved_special_token_0|> <|reserved_special_token_1|> class boxCar: def __init__(self, *args, **kwargs): print('print the keyword arguments dictionary {0} by {1}'.format( kwargs, 'WANGH')) self.name = kwargs['name'] self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF'] self.configuration = {} def addEcu(self, ecu, domain): if domain.upper() in self.domains: self.configuration.setdefault(domain.upper(), []).append(ecu. upper()) else: print('please input one of the following domain {}'.format([ 'Info', 'Body', 'PWT', 'ADAS', 'Infra'])) def deleteEcu(self, ecu, domain): pass def getConfiguration(self): return self.configuration def setTestPhase(self, phase): if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']: self.testPhase = phase.upper() else: print('please input one of the following domain {}'.format([ 'E1', 'E2', 'E3', 'E4', 'TT', 'PP'])) def test(): boxcar = boxCar(name='CM01') print(boxcar.name) <|reserved_special_token_0|> <|reserved_special_token_1|> class boxCar: def __init__(self, *args, **kwargs): print('print the keyword arguments dictionary {0} by {1}'.format( kwargs, 'WANGH')) self.name = kwargs['name'] self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF'] self.configuration = {} def addEcu(self, ecu, domain): if domain.upper() in self.domains: self.configuration.setdefault(domain.upper(), []).append(ecu. upper()) else: print('please input one of the following domain {}'.format([ 'Info', 'Body', 'PWT', 'ADAS', 'Infra'])) def deleteEcu(self, ecu, domain): pass def getConfiguration(self): return self.configuration def setTestPhase(self, phase): if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']: self.testPhase = phase.upper() else: print('please input one of the following domain {}'.format([ 'E1', 'E2', 'E3', 'E4', 'TT', 'PP'])) def test(): boxcar = boxCar(name='CM01') print(boxcar.name) if __name__ == '__main__': test() <|reserved_special_token_1|> class boxCar: def __init__(self, *args, **kwargs): print("print the keyword arguments dictionary {0} by {1}".format(kwargs, "WANGH")) self.name = kwargs["name"] self.domains = ["BODY","PWT","INFO","ADAS","INF"] self.configuration = {} def addEcu(self, ecu, domain): if domain.upper() in self.domains: self.configuration.setdefault(domain.upper(),[]).append(ecu.upper()) else: print("please input one of the following domain {}".format( ["Info", "Body", "PWT", "ADAS", "Infra"] )) def deleteEcu(self, ecu, domain): pass def getConfiguration(self): return self.configuration def setTestPhase(self, phase): if phase.upper() in ["E1", "E2", "E3", "E4","TT", "PP"]: self.testPhase = phase.upper() else: print("please input one of the following domain {}".format( ["E1", "E2", "E3", "E4","TT", "PP"] )) def test(): boxcar=boxCar(name="CM01") print(boxcar.name) # print(boxcar.domains) # print(boxcar.configuration) # boxcar.addEcu("CEM","body") # boxcar.addEcu("BECM","PWT") # boxcar.addEcu("BNCM", "body") # print(boxcar.configuration) # boxcar.setTestPhase("E1") # print(boxcar.testPhase) if __name__ == "__main__": test()
flexible
{ "blob_id": "c3fae13b488a717419adb8292597746a383b332c", "index": 7547, "step-1": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n <mask token>\n <mask token>\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\n<mask token>\n", "step-2": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\n<mask token>\n", "step-3": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\ndef test():\n boxcar = boxCar(name='CM01')\n print(boxcar.name)\n\n\n<mask token>\n", "step-4": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\ndef test():\n boxcar = boxCar(name='CM01')\n print(boxcar.name)\n\n\nif __name__ == '__main__':\n test()\n", "step-5": "class boxCar:\n def __init__(self, *args, **kwargs):\n print(\"print the keyword arguments dictionary {0} by {1}\".format(kwargs, \"WANGH\"))\n self.name = kwargs[\"name\"]\n self.domains = [\"BODY\",\"PWT\",\"INFO\",\"ADAS\",\"INF\"]\n self.configuration = {}\n \n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(),[]).append(ecu.upper())\n else: \n print(\"please input one of the following domain {}\".format(\n [\"Info\", \"Body\", \"PWT\", \"ADAS\", \"Infra\"]\n ))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in [\"E1\", \"E2\", \"E3\", \"E4\",\"TT\", \"PP\"]:\n self.testPhase = phase.upper()\n else:\n print(\"please input one of the following domain {}\".format(\n [\"E1\", \"E2\", \"E3\", \"E4\",\"TT\", \"PP\"]\n ))\n\ndef test():\n boxcar=boxCar(name=\"CM01\")\n print(boxcar.name)\n # print(boxcar.domains)\n # print(boxcar.configuration)\n # boxcar.addEcu(\"CEM\",\"body\")\n # boxcar.addEcu(\"BECM\",\"PWT\")\n # boxcar.addEcu(\"BNCM\", \"body\")\n # print(boxcar.configuration)\n # boxcar.setTestPhase(\"E1\")\n # print(boxcar.testPhase)\n\nif __name__ == \"__main__\":\n test()\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
<|reserved_special_token_0|> class data_generator(DataGenerator): <|reserved_special_token_0|> def __init__(self, pattern='', is_pre=True, *args, **kwargs): super(data_generator, self).__init__(*args, **kwargs) self.pattern = pattern self.is_pre = is_pre def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_output_ids = [], [], [] for is_end, text in self.sample(random): if self.is_pre: token_ids, segment_ids = tokenizer.encode(first_text=self. pattern, second_text=text, maxlen=maxlen) else: token_ids, segment_ids = tokenizer.encode(first_text=text, second_text=self.pattern, maxlen=maxlen) source_ids, target_ids = token_ids[:], token_ids[:] batch_token_ids.append(source_ids) batch_segment_ids.append(segment_ids) if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) yield [batch_token_ids, batch_segment_ids], None batch_token_ids, batch_segment_ids = [], [] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class data_generator(DataGenerator): """Data Generator""" def __init__(self, pattern='', is_pre=True, *args, **kwargs): super(data_generator, self).__init__(*args, **kwargs) self.pattern = pattern self.is_pre = is_pre def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_output_ids = [], [], [] for is_end, text in self.sample(random): if self.is_pre: token_ids, segment_ids = tokenizer.encode(first_text=self. pattern, second_text=text, maxlen=maxlen) else: token_ids, segment_ids = tokenizer.encode(first_text=text, second_text=self.pattern, maxlen=maxlen) source_ids, target_ids = token_ids[:], token_ids[:] batch_token_ids.append(source_ids) batch_segment_ids.append(segment_ids) if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) yield [batch_token_ids, batch_segment_ids], None batch_token_ids, batch_segment_ids = [], [] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class data_generator(DataGenerator): """Data Generator""" def __init__(self, pattern='', is_pre=True, *args, **kwargs): super(data_generator, self).__init__(*args, **kwargs) self.pattern = pattern self.is_pre = is_pre def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_output_ids = [], [], [] for is_end, text in self.sample(random): if self.is_pre: token_ids, segment_ids = tokenizer.encode(first_text=self. pattern, second_text=text, maxlen=maxlen) else: token_ids, segment_ids = tokenizer.encode(first_text=text, second_text=self.pattern, maxlen=maxlen) source_ids, target_ids = token_ids[:], token_ids[:] batch_token_ids.append(source_ids) batch_segment_ids.append(segment_ids) if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) yield [batch_token_ids, batch_segment_ids], None batch_token_ids, batch_segment_ids = [], [] def predict(data_generator_list, data): print('\n*******************Start to Zero-Shot predict*******************', flush=True) patterns_logits = [[] for _ in patterns] samples_logits = [[] for _ in data] for i in range(len(data_generator_list)): print('\nPattern{}'.format(i), flush=True) data_generator = data_generator_list[i] counter = 0 for x, _ in tqdm(data_generator): outputs = model.predict(x[:2]) for out in outputs: logit_pos = out[0].T patterns_logits[i].append(logit_pos) samples_logits[counter].append(logit_pos) counter += 1 preds = [] for i in range(len(patterns_logits[0])): pred = numpy.argmax([logits[i] for logits in patterns_logits]) preds.append(int(pred)) return preds, samples_logits if __name__ == '__main__': maxlen = 128 batch_size = 40 model_name = 'uer-mixed-bert-base' bert_model = Model(model_name=model_name) label_names = ['entertainment', 'sports', 'music', 'games', 'economics', 'education'] patterns = ['This is {} news'.format(label) for label in label_names] is_pre = True demo_data_en = [ 'FIFA unveils biennial World Cup plan, UEFA threatens boycott', 'COVID vaccines hold up against severe Delta: US data', 'Justin Drew Bieber was born on March 1, 1994 at St. ', 'Horizon launches latest chip to take on global rivals', 'Twitch video gamers rise up to stop ‘hate raids’'] demo_data = demo_data_en demo_generator_list = [] for p in patterns: demo_generator_list.append(data_generator(pattern=p, is_pre=is_pre, data=demo_data, batch_size=batch_size)) tokenizer = Tokenizer('.' + bert_model.dict_path, do_lower_case=True) model = build_transformer_model(config_path='.' + bert_model. config_path, checkpoint_path='.' + bert_model.checkpoint_path, with_nsp=True) preds, samples_logits = predict(demo_generator_list, demo_data) for i, (p, d) in enumerate(zip(preds, demo_data)): pred_label = label_names[p] print('Sample {}:'.format(i)) print('Original Text: {}'.format(d)) print('Predict label: {}'.format(pred_label)) print('Logits: {}'.format(samples_logits[i])) print() <|reserved_special_token_1|> import numpy from tqdm import tqdm from bert4keras.tokenizers import Tokenizer from bert4keras.models import build_transformer_model from bert4keras.snippets import sequence_padding, DataGenerator from utils import * class data_generator(DataGenerator): """Data Generator""" def __init__(self, pattern='', is_pre=True, *args, **kwargs): super(data_generator, self).__init__(*args, **kwargs) self.pattern = pattern self.is_pre = is_pre def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_output_ids = [], [], [] for is_end, text in self.sample(random): if self.is_pre: token_ids, segment_ids = tokenizer.encode(first_text=self. pattern, second_text=text, maxlen=maxlen) else: token_ids, segment_ids = tokenizer.encode(first_text=text, second_text=self.pattern, maxlen=maxlen) source_ids, target_ids = token_ids[:], token_ids[:] batch_token_ids.append(source_ids) batch_segment_ids.append(segment_ids) if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) yield [batch_token_ids, batch_segment_ids], None batch_token_ids, batch_segment_ids = [], [] def predict(data_generator_list, data): print('\n*******************Start to Zero-Shot predict*******************', flush=True) patterns_logits = [[] for _ in patterns] samples_logits = [[] for _ in data] for i in range(len(data_generator_list)): print('\nPattern{}'.format(i), flush=True) data_generator = data_generator_list[i] counter = 0 for x, _ in tqdm(data_generator): outputs = model.predict(x[:2]) for out in outputs: logit_pos = out[0].T patterns_logits[i].append(logit_pos) samples_logits[counter].append(logit_pos) counter += 1 preds = [] for i in range(len(patterns_logits[0])): pred = numpy.argmax([logits[i] for logits in patterns_logits]) preds.append(int(pred)) return preds, samples_logits if __name__ == '__main__': maxlen = 128 batch_size = 40 model_name = 'uer-mixed-bert-base' bert_model = Model(model_name=model_name) label_names = ['entertainment', 'sports', 'music', 'games', 'economics', 'education'] patterns = ['This is {} news'.format(label) for label in label_names] is_pre = True demo_data_en = [ 'FIFA unveils biennial World Cup plan, UEFA threatens boycott', 'COVID vaccines hold up against severe Delta: US data', 'Justin Drew Bieber was born on March 1, 1994 at St. ', 'Horizon launches latest chip to take on global rivals', 'Twitch video gamers rise up to stop ‘hate raids’'] demo_data = demo_data_en demo_generator_list = [] for p in patterns: demo_generator_list.append(data_generator(pattern=p, is_pre=is_pre, data=demo_data, batch_size=batch_size)) tokenizer = Tokenizer('.' + bert_model.dict_path, do_lower_case=True) model = build_transformer_model(config_path='.' + bert_model. config_path, checkpoint_path='.' + bert_model.checkpoint_path, with_nsp=True) preds, samples_logits = predict(demo_generator_list, demo_data) for i, (p, d) in enumerate(zip(preds, demo_data)): pred_label = label_names[p] print('Sample {}:'.format(i)) print('Original Text: {}'.format(d)) print('Predict label: {}'.format(pred_label)) print('Logits: {}'.format(samples_logits[i])) print() <|reserved_special_token_1|> #! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Sponge_sy" # Date: 2021/9/11 import numpy from tqdm import tqdm from bert4keras.tokenizers import Tokenizer from bert4keras.models import build_transformer_model from bert4keras.snippets import sequence_padding, DataGenerator from utils import * class data_generator(DataGenerator): """Data Generator""" def __init__(self, pattern="", is_pre=True, *args, **kwargs): super(data_generator, self).__init__(*args, **kwargs) self.pattern = pattern self.is_pre = is_pre def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_output_ids = [], [], [] for is_end, text in self.sample(random): if (self.is_pre): token_ids, segment_ids = tokenizer.encode(first_text=self.pattern, second_text=text, maxlen=maxlen) else: token_ids, segment_ids = tokenizer.encode(first_text=text, second_text=self.pattern, maxlen=maxlen) source_ids, target_ids = token_ids[:], token_ids[:] batch_token_ids.append(source_ids) batch_segment_ids.append(segment_ids) if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) yield [batch_token_ids, batch_segment_ids], None batch_token_ids, batch_segment_ids, = [], [] def predict(data_generator_list, data): print("\n*******************Start to Zero-Shot predict*******************", flush=True) patterns_logits = [[] for _ in patterns] samples_logits = [[] for _ in data] for i in range(len(data_generator_list)): print("\nPattern{}".format(i), flush=True) data_generator = data_generator_list[i] counter = 0 for (x, _) in tqdm(data_generator): outputs = model.predict(x[:2]) for out in outputs: logit_pos = out[0].T patterns_logits[i].append(logit_pos) samples_logits[counter].append(logit_pos) counter += 1 preds = [] for i in range(len(patterns_logits[0])): pred = numpy.argmax([logits[i] for logits in patterns_logits]) preds.append(int(pred)) return preds, samples_logits if __name__ == "__main__": # Load the hyper-parameters----------------------------------------------------------- maxlen = 128 # The max length 128 is used in our paper batch_size = 40 # Will not influence the results # Choose a model---------------------------------------------------------------------- # Recommend to use 'uer-mixed-bert-base' # model_names = ['google-bert', 'google-bert-small', 'google-bert-zh', # 'hfl-bert-wwm', 'hfl-bert-wwm-ext', # 'uer-mixed-bert-tiny', 'uer-mixed-bert-small', # 'uer-mixed-bert-base', 'uer-mixed-bert-large'] model_name = 'uer-mixed-bert-base' # Choose a dataset---------------------------------------------------------------------- # dataset_names = ['eprstmt', 'tnews', 'csldcp', 'iflytek'] # dataset_name = 'eprstmt' # Load model and dataset class bert_model = Model(model_name=model_name) # Create a template -------------------------------------------------------------------- label_names = ['entertainment', 'sports', 'music', 'games', 'economics', 'education'] patterns = ["This is {} news".format(label) for label in label_names] # Prefix or Suffix------------------------------------------------------------------- is_pre = True # Load the demo set-------------------------------------------------------------------- demo_data_en = ['FIFA unveils biennial World Cup plan, UEFA threatens boycott', 'COVID vaccines hold up against severe Delta: US data', 'Justin Drew Bieber was born on March 1, 1994 at St. ', 'Horizon launches latest chip to take on global rivals', 'Twitch video gamers rise up to stop ‘hate raids’'] demo_data = demo_data_en demo_generator_list = [] for p in patterns: demo_generator_list.append(data_generator(pattern=p, is_pre=is_pre, data=demo_data, batch_size=batch_size)) # Build BERT model--------------------------------------------------------------------- tokenizer = Tokenizer('.' + bert_model.dict_path, do_lower_case=True) # Load BERET model with NSP head model = build_transformer_model( config_path='.' + bert_model.config_path, checkpoint_path='.' + bert_model.checkpoint_path, with_nsp=True, ) # Zero-Shot predict and evaluate------------------------------------------------------- preds, samples_logits = predict(demo_generator_list, demo_data) for i, (p, d) in enumerate(zip(preds, demo_data)): pred_label = label_names[p] print("Sample {}:".format(i)) print("Original Text: {}".format(d)) print("Predict label: {}".format(pred_label)) print("Logits: {}".format(samples_logits[i])) print()
flexible
{ "blob_id": "5cb390b06026bc0899c0b10dc93f3ec1f2ffefa6", "index": 9727, "step-1": "<mask token>\n\n\nclass data_generator(DataGenerator):\n <mask token>\n\n def __init__(self, pattern='', is_pre=True, *args, **kwargs):\n super(data_generator, self).__init__(*args, **kwargs)\n self.pattern = pattern\n self.is_pre = is_pre\n\n def __iter__(self, random=False):\n batch_token_ids, batch_segment_ids, batch_output_ids = [], [], []\n for is_end, text in self.sample(random):\n if self.is_pre:\n token_ids, segment_ids = tokenizer.encode(first_text=self.\n pattern, second_text=text, maxlen=maxlen)\n else:\n token_ids, segment_ids = tokenizer.encode(first_text=text,\n second_text=self.pattern, maxlen=maxlen)\n source_ids, target_ids = token_ids[:], token_ids[:]\n batch_token_ids.append(source_ids)\n batch_segment_ids.append(segment_ids)\n if len(batch_token_ids) == self.batch_size or is_end:\n batch_token_ids = sequence_padding(batch_token_ids)\n batch_segment_ids = sequence_padding(batch_segment_ids)\n yield [batch_token_ids, batch_segment_ids], None\n batch_token_ids, batch_segment_ids = [], []\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass data_generator(DataGenerator):\n \"\"\"Data Generator\"\"\"\n\n def __init__(self, pattern='', is_pre=True, *args, **kwargs):\n super(data_generator, self).__init__(*args, **kwargs)\n self.pattern = pattern\n self.is_pre = is_pre\n\n def __iter__(self, random=False):\n batch_token_ids, batch_segment_ids, batch_output_ids = [], [], []\n for is_end, text in self.sample(random):\n if self.is_pre:\n token_ids, segment_ids = tokenizer.encode(first_text=self.\n pattern, second_text=text, maxlen=maxlen)\n else:\n token_ids, segment_ids = tokenizer.encode(first_text=text,\n second_text=self.pattern, maxlen=maxlen)\n source_ids, target_ids = token_ids[:], token_ids[:]\n batch_token_ids.append(source_ids)\n batch_segment_ids.append(segment_ids)\n if len(batch_token_ids) == self.batch_size or is_end:\n batch_token_ids = sequence_padding(batch_token_ids)\n batch_segment_ids = sequence_padding(batch_segment_ids)\n yield [batch_token_ids, batch_segment_ids], None\n batch_token_ids, batch_segment_ids = [], []\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass data_generator(DataGenerator):\n \"\"\"Data Generator\"\"\"\n\n def __init__(self, pattern='', is_pre=True, *args, **kwargs):\n super(data_generator, self).__init__(*args, **kwargs)\n self.pattern = pattern\n self.is_pre = is_pre\n\n def __iter__(self, random=False):\n batch_token_ids, batch_segment_ids, batch_output_ids = [], [], []\n for is_end, text in self.sample(random):\n if self.is_pre:\n token_ids, segment_ids = tokenizer.encode(first_text=self.\n pattern, second_text=text, maxlen=maxlen)\n else:\n token_ids, segment_ids = tokenizer.encode(first_text=text,\n second_text=self.pattern, maxlen=maxlen)\n source_ids, target_ids = token_ids[:], token_ids[:]\n batch_token_ids.append(source_ids)\n batch_segment_ids.append(segment_ids)\n if len(batch_token_ids) == self.batch_size or is_end:\n batch_token_ids = sequence_padding(batch_token_ids)\n batch_segment_ids = sequence_padding(batch_segment_ids)\n yield [batch_token_ids, batch_segment_ids], None\n batch_token_ids, batch_segment_ids = [], []\n\n\ndef predict(data_generator_list, data):\n print('\\n*******************Start to Zero-Shot predict*******************',\n flush=True)\n patterns_logits = [[] for _ in patterns]\n samples_logits = [[] for _ in data]\n for i in range(len(data_generator_list)):\n print('\\nPattern{}'.format(i), flush=True)\n data_generator = data_generator_list[i]\n counter = 0\n for x, _ in tqdm(data_generator):\n outputs = model.predict(x[:2])\n for out in outputs:\n logit_pos = out[0].T\n patterns_logits[i].append(logit_pos)\n samples_logits[counter].append(logit_pos)\n counter += 1\n preds = []\n for i in range(len(patterns_logits[0])):\n pred = numpy.argmax([logits[i] for logits in patterns_logits])\n preds.append(int(pred))\n return preds, samples_logits\n\n\nif __name__ == '__main__':\n maxlen = 128\n batch_size = 40\n model_name = 'uer-mixed-bert-base'\n bert_model = Model(model_name=model_name)\n label_names = ['entertainment', 'sports', 'music', 'games', 'economics',\n 'education']\n patterns = ['This is {} news'.format(label) for label in label_names]\n is_pre = True\n demo_data_en = [\n 'FIFA unveils biennial World Cup plan, UEFA threatens boycott',\n 'COVID vaccines hold up against severe Delta: US data',\n 'Justin Drew Bieber was born on March 1, 1994 at St. ',\n 'Horizon launches latest chip to take on global rivals',\n 'Twitch video gamers rise up to stop ‘hate raids’']\n demo_data = demo_data_en\n demo_generator_list = []\n for p in patterns:\n demo_generator_list.append(data_generator(pattern=p, is_pre=is_pre,\n data=demo_data, batch_size=batch_size))\n tokenizer = Tokenizer('.' + bert_model.dict_path, do_lower_case=True)\n model = build_transformer_model(config_path='.' + bert_model.\n config_path, checkpoint_path='.' + bert_model.checkpoint_path,\n with_nsp=True)\n preds, samples_logits = predict(demo_generator_list, demo_data)\n for i, (p, d) in enumerate(zip(preds, demo_data)):\n pred_label = label_names[p]\n print('Sample {}:'.format(i))\n print('Original Text: {}'.format(d))\n print('Predict label: {}'.format(pred_label))\n print('Logits: {}'.format(samples_logits[i]))\n print()\n", "step-4": "import numpy\nfrom tqdm import tqdm\nfrom bert4keras.tokenizers import Tokenizer\nfrom bert4keras.models import build_transformer_model\nfrom bert4keras.snippets import sequence_padding, DataGenerator\nfrom utils import *\n\n\nclass data_generator(DataGenerator):\n \"\"\"Data Generator\"\"\"\n\n def __init__(self, pattern='', is_pre=True, *args, **kwargs):\n super(data_generator, self).__init__(*args, **kwargs)\n self.pattern = pattern\n self.is_pre = is_pre\n\n def __iter__(self, random=False):\n batch_token_ids, batch_segment_ids, batch_output_ids = [], [], []\n for is_end, text in self.sample(random):\n if self.is_pre:\n token_ids, segment_ids = tokenizer.encode(first_text=self.\n pattern, second_text=text, maxlen=maxlen)\n else:\n token_ids, segment_ids = tokenizer.encode(first_text=text,\n second_text=self.pattern, maxlen=maxlen)\n source_ids, target_ids = token_ids[:], token_ids[:]\n batch_token_ids.append(source_ids)\n batch_segment_ids.append(segment_ids)\n if len(batch_token_ids) == self.batch_size or is_end:\n batch_token_ids = sequence_padding(batch_token_ids)\n batch_segment_ids = sequence_padding(batch_segment_ids)\n yield [batch_token_ids, batch_segment_ids], None\n batch_token_ids, batch_segment_ids = [], []\n\n\ndef predict(data_generator_list, data):\n print('\\n*******************Start to Zero-Shot predict*******************',\n flush=True)\n patterns_logits = [[] for _ in patterns]\n samples_logits = [[] for _ in data]\n for i in range(len(data_generator_list)):\n print('\\nPattern{}'.format(i), flush=True)\n data_generator = data_generator_list[i]\n counter = 0\n for x, _ in tqdm(data_generator):\n outputs = model.predict(x[:2])\n for out in outputs:\n logit_pos = out[0].T\n patterns_logits[i].append(logit_pos)\n samples_logits[counter].append(logit_pos)\n counter += 1\n preds = []\n for i in range(len(patterns_logits[0])):\n pred = numpy.argmax([logits[i] for logits in patterns_logits])\n preds.append(int(pred))\n return preds, samples_logits\n\n\nif __name__ == '__main__':\n maxlen = 128\n batch_size = 40\n model_name = 'uer-mixed-bert-base'\n bert_model = Model(model_name=model_name)\n label_names = ['entertainment', 'sports', 'music', 'games', 'economics',\n 'education']\n patterns = ['This is {} news'.format(label) for label in label_names]\n is_pre = True\n demo_data_en = [\n 'FIFA unveils biennial World Cup plan, UEFA threatens boycott',\n 'COVID vaccines hold up against severe Delta: US data',\n 'Justin Drew Bieber was born on March 1, 1994 at St. ',\n 'Horizon launches latest chip to take on global rivals',\n 'Twitch video gamers rise up to stop ‘hate raids’']\n demo_data = demo_data_en\n demo_generator_list = []\n for p in patterns:\n demo_generator_list.append(data_generator(pattern=p, is_pre=is_pre,\n data=demo_data, batch_size=batch_size))\n tokenizer = Tokenizer('.' + bert_model.dict_path, do_lower_case=True)\n model = build_transformer_model(config_path='.' + bert_model.\n config_path, checkpoint_path='.' + bert_model.checkpoint_path,\n with_nsp=True)\n preds, samples_logits = predict(demo_generator_list, demo_data)\n for i, (p, d) in enumerate(zip(preds, demo_data)):\n pred_label = label_names[p]\n print('Sample {}:'.format(i))\n print('Original Text: {}'.format(d))\n print('Predict label: {}'.format(pred_label))\n print('Logits: {}'.format(samples_logits[i]))\n print()\n", "step-5": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Sponge_sy\"\n# Date: 2021/9/11\n\n\nimport numpy\nfrom tqdm import tqdm\nfrom bert4keras.tokenizers import Tokenizer\nfrom bert4keras.models import build_transformer_model\nfrom bert4keras.snippets import sequence_padding, DataGenerator\nfrom utils import *\n\n\nclass data_generator(DataGenerator):\n \"\"\"Data Generator\"\"\"\n\n def __init__(self, pattern=\"\", is_pre=True, *args, **kwargs):\n super(data_generator, self).__init__(*args, **kwargs)\n self.pattern = pattern\n self.is_pre = is_pre\n\n def __iter__(self, random=False):\n batch_token_ids, batch_segment_ids, batch_output_ids = [], [], []\n for is_end, text in self.sample(random):\n if (self.is_pre):\n token_ids, segment_ids = tokenizer.encode(first_text=self.pattern, second_text=text, maxlen=maxlen)\n else:\n token_ids, segment_ids = tokenizer.encode(first_text=text, second_text=self.pattern, maxlen=maxlen)\n source_ids, target_ids = token_ids[:], token_ids[:]\n batch_token_ids.append(source_ids)\n batch_segment_ids.append(segment_ids)\n\n if len(batch_token_ids) == self.batch_size or is_end:\n batch_token_ids = sequence_padding(batch_token_ids)\n batch_segment_ids = sequence_padding(batch_segment_ids)\n yield [batch_token_ids, batch_segment_ids], None\n batch_token_ids, batch_segment_ids, = [], []\n\ndef predict(data_generator_list, data):\n print(\"\\n*******************Start to Zero-Shot predict*******************\", flush=True)\n patterns_logits = [[] for _ in patterns]\n samples_logits = [[] for _ in data]\n for i in range(len(data_generator_list)):\n print(\"\\nPattern{}\".format(i), flush=True)\n data_generator = data_generator_list[i]\n counter = 0\n for (x, _) in tqdm(data_generator):\n outputs = model.predict(x[:2])\n for out in outputs:\n logit_pos = out[0].T\n patterns_logits[i].append(logit_pos)\n samples_logits[counter].append(logit_pos)\n counter += 1\n preds = []\n for i in range(len(patterns_logits[0])):\n pred = numpy.argmax([logits[i] for logits in patterns_logits])\n preds.append(int(pred))\n return preds, samples_logits\n\nif __name__ == \"__main__\":\n\n # Load the hyper-parameters-----------------------------------------------------------\n maxlen = 128 # The max length 128 is used in our paper\n batch_size = 40 # Will not influence the results\n\n # Choose a model----------------------------------------------------------------------\n # Recommend to use 'uer-mixed-bert-base'\n # model_names = ['google-bert', 'google-bert-small', 'google-bert-zh',\n # 'hfl-bert-wwm', 'hfl-bert-wwm-ext',\n # 'uer-mixed-bert-tiny', 'uer-mixed-bert-small',\n # 'uer-mixed-bert-base', 'uer-mixed-bert-large']\n model_name = 'uer-mixed-bert-base'\n\n # Choose a dataset----------------------------------------------------------------------\n # dataset_names = ['eprstmt', 'tnews', 'csldcp', 'iflytek']\n # dataset_name = 'eprstmt'\n\n # Load model and dataset class\n bert_model = Model(model_name=model_name)\n\n # Create a template --------------------------------------------------------------------\n label_names = ['entertainment', 'sports', 'music', 'games', 'economics', 'education']\n patterns = [\"This is {} news\".format(label) for label in label_names]\n\n # Prefix or Suffix-------------------------------------------------------------------\n is_pre = True\n\n # Load the demo set--------------------------------------------------------------------\n\n demo_data_en = ['FIFA unveils biennial World Cup plan, UEFA threatens boycott',\n 'COVID vaccines hold up against severe Delta: US data',\n 'Justin Drew Bieber was born on March 1, 1994 at St. ',\n 'Horizon launches latest chip to take on global rivals',\n 'Twitch video gamers rise up to stop ‘hate raids’']\n\n demo_data = demo_data_en\n demo_generator_list = []\n for p in patterns:\n demo_generator_list.append(data_generator(pattern=p, is_pre=is_pre, data=demo_data, batch_size=batch_size))\n\n # Build BERT model---------------------------------------------------------------------\n tokenizer = Tokenizer('.' + bert_model.dict_path, do_lower_case=True)\n # Load BERET model with NSP head\n model = build_transformer_model(\n config_path='.' + bert_model.config_path, checkpoint_path='.' + bert_model.checkpoint_path, with_nsp=True,\n )\n\n # Zero-Shot predict and evaluate-------------------------------------------------------\n preds, samples_logits = predict(demo_generator_list, demo_data)\n for i, (p, d) in enumerate(zip(preds, demo_data)):\n pred_label = label_names[p]\n print(\"Sample {}:\".format(i))\n print(\"Original Text: {}\".format(d))\n print(\"Predict label: {}\".format(pred_label))\n print(\"Logits: {}\".format(samples_logits[i]))\n print()\n", "step-ids": [ 3, 4, 6, 7, 8 ] }
[ 3, 4, 6, 7, 8 ]
<|reserved_special_token_0|> def prune_weights(weight): for i in range(weight.shape[-1]): tmp = deepcopy(weight[..., i]) tmp = np.abs(tmp) tmp = np.sort(np.array(tmp)) threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)] weight[..., i][np.abs(weight[..., i]) < threshold] = 0 sparse_matrix = deepcopy(weight) sparse_matrix[sparse_matrix != 0] = 1 return weight, sparse_matrix <|reserved_special_token_0|> def huffman_encode(arr): frequency_map = defaultdict(int) for value in np.nditer(arr): value = int(value) frequency_map[value] += 1 heap = [Node(frequency, value, None, None) for value, frequency in frequency_map.items()] heapify(heap) while len(heap) > 1: node1 = heappop(heap) node2 = heappop(heap) merged = Node(node1.frequency + node2.frequency, None, node1, node2) heappush(heap, merged) value2code = dict() def generate_code(node, code): if node is None: return if node.value is not None: value2code[node.value] = code return generate_code(node.left, code + '0') generate_code(node.right, code + '1') root = heappop(heap) generate_code(root, '') data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr)) codebook_encoding = encode_huffman_tree(root) return data_encoding, codebook_encoding <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def prune_weights(weight): for i in range(weight.shape[-1]): tmp = deepcopy(weight[..., i]) tmp = np.abs(tmp) tmp = np.sort(np.array(tmp)) threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)] weight[..., i][np.abs(weight[..., i]) < threshold] = 0 sparse_matrix = deepcopy(weight) sparse_matrix[sparse_matrix != 0] = 1 return weight, sparse_matrix <|reserved_special_token_0|> def int2bitstr(integer): four_bytes = struct.pack('>I', integer) return ''.join(f'{byte:08b}' for byte in four_bytes) def bitstr2int(bitstr): byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len( bitstr), 8)) return struct.unpack('>I', byte_arr)[0] def huffman_encode(arr): frequency_map = defaultdict(int) for value in np.nditer(arr): value = int(value) frequency_map[value] += 1 heap = [Node(frequency, value, None, None) for value, frequency in frequency_map.items()] heapify(heap) while len(heap) > 1: node1 = heappop(heap) node2 = heappop(heap) merged = Node(node1.frequency + node2.frequency, None, node1, node2) heappush(heap, merged) value2code = dict() def generate_code(node, code): if node is None: return if node.value is not None: value2code[node.value] = code return generate_code(node.left, code + '0') generate_code(node.right, code + '1') root = heappop(heap) generate_code(root, '') data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr)) codebook_encoding = encode_huffman_tree(root) return data_encoding, codebook_encoding <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_batch(batch_size): index = np.random.randint(0, np.shape(x_train)[0], batch_size) return x_train[index, :], y_train[index] def prune_weights(weight): for i in range(weight.shape[-1]): tmp = deepcopy(weight[..., i]) tmp = np.abs(tmp) tmp = np.sort(np.array(tmp)) threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)] weight[..., i][np.abs(weight[..., i]) < threshold] = 0 sparse_matrix = deepcopy(weight) sparse_matrix[sparse_matrix != 0] = 1 return weight, sparse_matrix <|reserved_special_token_0|> def int2bitstr(integer): four_bytes = struct.pack('>I', integer) return ''.join(f'{byte:08b}' for byte in four_bytes) def bitstr2int(bitstr): byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len( bitstr), 8)) return struct.unpack('>I', byte_arr)[0] def huffman_encode(arr): frequency_map = defaultdict(int) for value in np.nditer(arr): value = int(value) frequency_map[value] += 1 heap = [Node(frequency, value, None, None) for value, frequency in frequency_map.items()] heapify(heap) while len(heap) > 1: node1 = heappop(heap) node2 = heappop(heap) merged = Node(node1.frequency + node2.frequency, None, node1, node2) heappush(heap, merged) value2code = dict() def generate_code(node, code): if node is None: return if node.value is not None: value2code[node.value] = code return generate_code(node.left, code + '0') generate_code(node.right, code + '1') root = heappop(heap) generate_code(root, '') data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr)) codebook_encoding = encode_huffman_tree(root) return data_encoding, codebook_encoding <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_batch(batch_size): index = np.random.randint(0, np.shape(x_train)[0], batch_size) return x_train[index, :], y_train[index] def prune_weights(weight): for i in range(weight.shape[-1]): tmp = deepcopy(weight[..., i]) tmp = np.abs(tmp) tmp = np.sort(np.array(tmp)) threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)] weight[..., i][np.abs(weight[..., i]) < threshold] = 0 sparse_matrix = deepcopy(weight) sparse_matrix[sparse_matrix != 0] = 1 return weight, sparse_matrix <|reserved_special_token_0|> def encode_huffman_tree(root): """ Encodes a huffman tree to string of '0's and '1's """ code_list = [] def encode_node(node): if node.value is not None: code_list.append('1') lst = list(int2bitstr(node.value)) code_list.extend(lst) else: code_list.append('0') encode_node(node.left) encode_node(node.right) encode_node(root) return ''.join(code_list) def int2bitstr(integer): four_bytes = struct.pack('>I', integer) return ''.join(f'{byte:08b}' for byte in four_bytes) def bitstr2int(bitstr): byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len( bitstr), 8)) return struct.unpack('>I', byte_arr)[0] def huffman_encode(arr): frequency_map = defaultdict(int) for value in np.nditer(arr): value = int(value) frequency_map[value] += 1 heap = [Node(frequency, value, None, None) for value, frequency in frequency_map.items()] heapify(heap) while len(heap) > 1: node1 = heappop(heap) node2 = heappop(heap) merged = Node(node1.frequency + node2.frequency, None, node1, node2) heappush(heap, merged) value2code = dict() def generate_code(node, code): if node is None: return if node.value is not None: value2code[node.value] = code return generate_code(node.left, code + '0') generate_code(node.right, code + '1') root = heappop(heap) generate_code(root, '') data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr)) codebook_encoding = encode_huffman_tree(root) return data_encoding, codebook_encoding <|reserved_special_token_0|> <|reserved_special_token_1|> import tensorflow as tf from sklearn.cluster import KMeans import tensorflow.keras as keras from copy import deepcopy import numpy as np import h5py from collections import defaultdict, namedtuple from heapq import heappush, heappop, heapify import struct tf.enable_eager_execution() mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1).astype(np.float32) x_test = x_test.reshape(-1, 28, 28, 1).astype(np.float32) x_train, x_test = x_train / 255.0, x_test / 255.0 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) print(x_test.shape) COMPRESSION_RATE = 0.9 BATCH_SIZE = 50 NUM_BATCHES = 1000 NUM_EPOCH = 1 BITS = 5 MAX_SPAN = 2 ** BITS LEARNING_RATE = 0.001 model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (5, 5), activation='relu', input_shape=[28, 28, 1]), tf.keras.layers.Conv2D(64, (5, 5), activation='relu'), tf.keras.layers.MaxPool2D(pool_size=(2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer=tf.train.AdamOptimizer(learning_rate=LEARNING_RATE), loss='categorical_crossentropy', metrics=['accuracy']) # history = model.fit(x_train, y_train, validation_split=0.2, epochs=5, batch_size=50) # score = model.evaluate(x_test, y_test) # print(score[1]) # model.save_weights('./result/my_model.h5', save_format='h5') model.load_weights('./result/my_model.h5') score = model.evaluate(x_test, y_test) print(score[1]) def get_batch(batch_size): index = np.random.randint(0, np.shape(x_train)[0], batch_size) return x_train[index, :], y_train[index] def prune_weights(weight): for i in range(weight.shape[-1]): tmp = deepcopy(weight[..., i]) tmp = np.abs(tmp) tmp = np.sort(np.array(tmp)) # compute threshold threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)] weight[..., i][np.abs(weight[..., i]) < threshold] = 0 sparse_matrix = deepcopy(weight) sparse_matrix[sparse_matrix != 0] = 1 return weight, sparse_matrix Sparse_layer = {} # Pruning for layer_id in range(len(model.layers)): layer = model.layers[layer_id] weight = layer.get_weights() # weight:weight[0] # bias:weight[1] if len(weight) > 0: if layer_id != 0: w = deepcopy(weight) new_weight, sparse_matrix = prune_weights(w[0]) Sparse_layer[layer_id] = sparse_matrix w[0] = new_weight layer.set_weights(w) score = model.evaluate(x_test, y_test, verbose=0) print(score[1]) # Retrain for epoch in range(NUM_EPOCH): for j in range(x_train.shape[0] // BATCH_SIZE): begin = j*BATCH_SIZE if j*BATCH_SIZE + BATCH_SIZE > x_train.shape[0]: end = x_train.shape[0] else: end = j*BATCH_SIZE + BATCH_SIZE X, Y = x_train[begin:end], y_train[begin:end] # train on each batch model.train_on_batch(X, Y) # apply Sparse connection for layer_id in Sparse_layer: w = model.layers[layer_id].get_weights() w[0] = w[0] * Sparse_layer[layer_id] model.layers[layer_id].set_weights(w) score = model.evaluate(x_test, y_test, verbose=0) print('val loss: {}'.format(score[0])) print('val acc: {}'.format(score[1])) score = model.evaluate(x_test, y_test, verbose=0) print(score[1]) cluster_index = dict() cluster_centroids = dict() # Weight Share and Quantization for layer_id in Sparse_layer: layer = model.layers[layer_id] weight = layer.get_weights() w = deepcopy(weight) shape = w[0].shape weight_array = w[0].flatten() nonzero_weight = w[0][Sparse_layer[layer_id] != 0].flatten() nonzero_index = np.where(Sparse_layer[layer_id].flatten() != 0)[0] max_weight = max(nonzero_weight) min_weight = min(nonzero_weight) space = np.linspace(min_weight, max_weight, num=2 ** BITS) kmeans = KMeans(n_clusters=len(space), init=space.reshape(-1, 1), n_init=1, precompute_distances=True, algorithm="full") kmeans.fit(nonzero_weight.reshape(-1, 1)) # cluster index of each weight layer_cluster_index = kmeans.labels_ # value of the centroids layer_centroids = kmeans.cluster_centers_.flatten() # Add to dict cluster_index[layer_id] = layer_cluster_index cluster_centroids[layer_id] = layer_centroids # set new weight new_weight = kmeans.cluster_centers_[kmeans.labels_].flatten() for idx in range(len(nonzero_index)): index = nonzero_index[idx] weight_array[index] = new_weight[idx] # new_weight = kmeans.cluster_centers_[kmeans.labels_].reshape(shape) # w[0] = new_weight w[0] = weight_array.reshape(shape) layer.set_weights(w) score = model.evaluate(x_test, y_test, verbose=0) print(score[1]) # calculate gradient and get the fine-tuned centroids # for epoch in range(NUM_EPOCH): # for j in range(x_train.shape[0] // BATCH_SIZE): # begin = j * BATCH_SIZE # if j * BATCH_SIZE + BATCH_SIZE > x_train.shape[0]: # end = x_train.shape[0] # else: # end = j * BATCH_SIZE + BATCH_SIZE # X, Y = x_train[begin:end], y_train[begin:end] # with tf.GradientTape() as tape: # y_predict = model(X) # loss = tf.losses.softmax_cross_entropy(onehot_labels=Y, logits=y_predict) # grads = tape.gradient(loss, model.variables) # gradient_num = 0 # for layer_id in Sparse_layer: # gradient_num += 2 # gradient = grads[gradient_num].numpy().flatten() # # # Get the gradient of the nonzero position # nonzero_gradient = gradient[Sparse_layer[layer_id].flatten() != 0].flatten() # nonzero_index = np.where(Sparse_layer[layer_id].flatten() != 0)[0] # # print(len(nonzero_gradient)) # # gradient_index = np.zeros(2 ** BITS) # # Calculate the sum of gradient of the same cluster # for i in range(len(nonzero_gradient)): # gradient_index[cluster_index[layer_id][i]] += gradient[i] # # Update centroid # fine_tuned_centroids = cluster_centroids[layer_id]-LEARNING_RATE*gradient_index # cluster_centroids[layer_id] = fine_tuned_centroids # # w = model.layers[layer_id].get_weights() # shape = w[0].shape # weight_array = w[0].flatten() # new_weight = fine_tuned_centroids[cluster_index[layer_id]] # for idx in range(len(nonzero_index)): # index = nonzero_index[idx] # weight_array[index] = new_weight[idx] # # w[0] = weight_array.reshape(shape) # model.layers[layer_id].set_weights(w) # score = model.evaluate(x_test, y_test, verbose=0) # print('val loss: {}'.format(score[0])) # print('val acc: {}'.format(score[1])) print('-------------------') score = model.evaluate(x_test, y_test, verbose=0) print(score[1]) layer_relative_index = dict() layer_weight_cluster_index = dict() Node = namedtuple('Node', ['frequency', 'value', 'left', 'right']) Node.__lt__ = lambda x, y: x.frequency < y.frequency def encode_huffman_tree(root): """ Encodes a huffman tree to string of '0's and '1's """ # converter = {'float32':float2bitstr, 'int32':int2bitstr} code_list = [] def encode_node(node): if node.value is not None: # node is leaf node code_list.append('1') lst = list(int2bitstr(node.value)) code_list.extend(lst) else: code_list.append('0') encode_node(node.left) encode_node(node.right) encode_node(root) return ''.join(code_list) def int2bitstr(integer): four_bytes = struct.pack('>I', integer) # bytes return ''.join(f'{byte:08b}' for byte in four_bytes) # string of '0's and '1's def bitstr2int(bitstr): byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len(bitstr), 8)) return struct.unpack('>I', byte_arr)[0] def huffman_encode(arr): # count the frequency of each number in array frequency_map = defaultdict(int) for value in np.nditer(arr): value = int(value) frequency_map[value] += 1 heap = [Node(frequency, value, None, None) for value, frequency in frequency_map.items()] heapify(heap) # Merge nodes while len(heap) > 1: node1 = heappop(heap) node2 = heappop(heap) merged = Node(node1.frequency + node2.frequency, None, node1, node2) heappush(heap, merged) # Generate code value mapping value2code = dict() def generate_code(node, code): if node is None: return if node.value is not None: value2code[node.value] = code return generate_code(node.left, code + '0') generate_code(node.right, code + '1') root = heappop(heap) generate_code(root, '') data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr)) codebook_encoding = encode_huffman_tree(root) return data_encoding, codebook_encoding # Matrix sparsity with relative index for layer_id in Sparse_layer: layer = model.layers[layer_id] weight = layer.get_weights() w = deepcopy(weight) shape = w[0].shape weight_array = w[0].flatten() # nonzero_weight = w[0][Sparse_layer[layer_id] != 0].flatten() # print(len(nonzero_weight)) nonzero_weight_cluster_index = cluster_index[layer_id] print(len(nonzero_weight_cluster_index)) nonzero_index = np.where(Sparse_layer[layer_id].flatten() != 0)[0] first = nonzero_index[0] relative = np.insert(np.diff(nonzero_index), 0, first) relative_diff_index = relative.tolist() weight_cluster_index = nonzero_weight_cluster_index.tolist() shift = 0 for i in np.where(relative > MAX_SPAN)[0].tolist(): while relative_diff_index[i + shift] > MAX_SPAN: relative_diff_index.insert(i + shift, MAX_SPAN) weight_cluster_index.insert(i + shift, 0) shift += 1 relative_diff_index[i + shift] -= MAX_SPAN layer_relative_index[layer_id] = np.array(relative_diff_index) data_encoding, codebook_encoding = huffman_encode(np.array(weight_cluster_index)) # layer_weight_cluster_index[layer_id] = np.array(weight_cluster_index) layer_weight_cluster_index[layer_id] = np.array([data_encoding, codebook_encoding]) print('----------------') # print(layer_weight_value[5]) # encode file_name = './result/compressed_model2' file = h5py.File('{}.h5'.format(file_name), mode='w') for layer_id in range(len(model.layers)): layer = model.layers[layer_id] weight = layer.get_weights() if len(weight) > 0: file_layer = file.create_group(layer.name) shape = weight[0].shape if layer_id != 0: print(len(weight[0].shape)) pshape = file_layer.create_dataset('shape', np.array(shape).shape, dtype='int32') pindex = file_layer.create_dataset('index', layer_relative_index[layer_id].shape, dtype='int32') # pcluster_index = file_layer.create_dataset('cluster_index', layer_weight_cluster_index[layer_id].shape, # dtype='int32') pcluster_index = file_layer.create_dataset('cluster_index', layer_weight_cluster_index[layer_id].shape, dtype=h5py.special_dtype(vlen=str)) pcentroid = file_layer.create_dataset('centroid', cluster_centroids[layer_id].shape, dtype='float32') pshape[:] = np.array(shape) pindex[:] = layer_relative_index[layer_id] pcluster_index[:] = layer_weight_cluster_index[layer_id] pcentroid[:] = cluster_centroids[layer_id] else: pweight = file_layer.create_dataset('weight', weight[0].shape, dtype='float32') pweight[:] = weight[0] pbias = file_layer.create_dataset('bias', weight[1].shape, dtype='float32') pbias[:] = weight[1] file.flush() file.close()
flexible
{ "blob_id": "086aefaad7a4b743e5a05b3a44db971dbdbf16b6", "index": 8299, "step-1": "<mask token>\n\n\ndef prune_weights(weight):\n for i in range(weight.shape[-1]):\n tmp = deepcopy(weight[..., i])\n tmp = np.abs(tmp)\n tmp = np.sort(np.array(tmp))\n threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)]\n weight[..., i][np.abs(weight[..., i]) < threshold] = 0\n sparse_matrix = deepcopy(weight)\n sparse_matrix[sparse_matrix != 0] = 1\n return weight, sparse_matrix\n\n\n<mask token>\n\n\ndef huffman_encode(arr):\n frequency_map = defaultdict(int)\n for value in np.nditer(arr):\n value = int(value)\n frequency_map[value] += 1\n heap = [Node(frequency, value, None, None) for value, frequency in\n frequency_map.items()]\n heapify(heap)\n while len(heap) > 1:\n node1 = heappop(heap)\n node2 = heappop(heap)\n merged = Node(node1.frequency + node2.frequency, None, node1, node2)\n heappush(heap, merged)\n value2code = dict()\n\n def generate_code(node, code):\n if node is None:\n return\n if node.value is not None:\n value2code[node.value] = code\n return\n generate_code(node.left, code + '0')\n generate_code(node.right, code + '1')\n root = heappop(heap)\n generate_code(root, '')\n data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr))\n codebook_encoding = encode_huffman_tree(root)\n return data_encoding, codebook_encoding\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef prune_weights(weight):\n for i in range(weight.shape[-1]):\n tmp = deepcopy(weight[..., i])\n tmp = np.abs(tmp)\n tmp = np.sort(np.array(tmp))\n threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)]\n weight[..., i][np.abs(weight[..., i]) < threshold] = 0\n sparse_matrix = deepcopy(weight)\n sparse_matrix[sparse_matrix != 0] = 1\n return weight, sparse_matrix\n\n\n<mask token>\n\n\ndef int2bitstr(integer):\n four_bytes = struct.pack('>I', integer)\n return ''.join(f'{byte:08b}' for byte in four_bytes)\n\n\ndef bitstr2int(bitstr):\n byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len(\n bitstr), 8))\n return struct.unpack('>I', byte_arr)[0]\n\n\ndef huffman_encode(arr):\n frequency_map = defaultdict(int)\n for value in np.nditer(arr):\n value = int(value)\n frequency_map[value] += 1\n heap = [Node(frequency, value, None, None) for value, frequency in\n frequency_map.items()]\n heapify(heap)\n while len(heap) > 1:\n node1 = heappop(heap)\n node2 = heappop(heap)\n merged = Node(node1.frequency + node2.frequency, None, node1, node2)\n heappush(heap, merged)\n value2code = dict()\n\n def generate_code(node, code):\n if node is None:\n return\n if node.value is not None:\n value2code[node.value] = code\n return\n generate_code(node.left, code + '0')\n generate_code(node.right, code + '1')\n root = heappop(heap)\n generate_code(root, '')\n data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr))\n codebook_encoding = encode_huffman_tree(root)\n return data_encoding, codebook_encoding\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_batch(batch_size):\n index = np.random.randint(0, np.shape(x_train)[0], batch_size)\n return x_train[index, :], y_train[index]\n\n\ndef prune_weights(weight):\n for i in range(weight.shape[-1]):\n tmp = deepcopy(weight[..., i])\n tmp = np.abs(tmp)\n tmp = np.sort(np.array(tmp))\n threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)]\n weight[..., i][np.abs(weight[..., i]) < threshold] = 0\n sparse_matrix = deepcopy(weight)\n sparse_matrix[sparse_matrix != 0] = 1\n return weight, sparse_matrix\n\n\n<mask token>\n\n\ndef int2bitstr(integer):\n four_bytes = struct.pack('>I', integer)\n return ''.join(f'{byte:08b}' for byte in four_bytes)\n\n\ndef bitstr2int(bitstr):\n byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len(\n bitstr), 8))\n return struct.unpack('>I', byte_arr)[0]\n\n\ndef huffman_encode(arr):\n frequency_map = defaultdict(int)\n for value in np.nditer(arr):\n value = int(value)\n frequency_map[value] += 1\n heap = [Node(frequency, value, None, None) for value, frequency in\n frequency_map.items()]\n heapify(heap)\n while len(heap) > 1:\n node1 = heappop(heap)\n node2 = heappop(heap)\n merged = Node(node1.frequency + node2.frequency, None, node1, node2)\n heappush(heap, merged)\n value2code = dict()\n\n def generate_code(node, code):\n if node is None:\n return\n if node.value is not None:\n value2code[node.value] = code\n return\n generate_code(node.left, code + '0')\n generate_code(node.right, code + '1')\n root = heappop(heap)\n generate_code(root, '')\n data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr))\n codebook_encoding = encode_huffman_tree(root)\n return data_encoding, codebook_encoding\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef get_batch(batch_size):\n index = np.random.randint(0, np.shape(x_train)[0], batch_size)\n return x_train[index, :], y_train[index]\n\n\ndef prune_weights(weight):\n for i in range(weight.shape[-1]):\n tmp = deepcopy(weight[..., i])\n tmp = np.abs(tmp)\n tmp = np.sort(np.array(tmp))\n threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)]\n weight[..., i][np.abs(weight[..., i]) < threshold] = 0\n sparse_matrix = deepcopy(weight)\n sparse_matrix[sparse_matrix != 0] = 1\n return weight, sparse_matrix\n\n\n<mask token>\n\n\ndef encode_huffman_tree(root):\n \"\"\"\n Encodes a huffman tree to string of '0's and '1's\n \"\"\"\n code_list = []\n\n def encode_node(node):\n if node.value is not None:\n code_list.append('1')\n lst = list(int2bitstr(node.value))\n code_list.extend(lst)\n else:\n code_list.append('0')\n encode_node(node.left)\n encode_node(node.right)\n encode_node(root)\n return ''.join(code_list)\n\n\ndef int2bitstr(integer):\n four_bytes = struct.pack('>I', integer)\n return ''.join(f'{byte:08b}' for byte in four_bytes)\n\n\ndef bitstr2int(bitstr):\n byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len(\n bitstr), 8))\n return struct.unpack('>I', byte_arr)[0]\n\n\ndef huffman_encode(arr):\n frequency_map = defaultdict(int)\n for value in np.nditer(arr):\n value = int(value)\n frequency_map[value] += 1\n heap = [Node(frequency, value, None, None) for value, frequency in\n frequency_map.items()]\n heapify(heap)\n while len(heap) > 1:\n node1 = heappop(heap)\n node2 = heappop(heap)\n merged = Node(node1.frequency + node2.frequency, None, node1, node2)\n heappush(heap, merged)\n value2code = dict()\n\n def generate_code(node, code):\n if node is None:\n return\n if node.value is not None:\n value2code[node.value] = code\n return\n generate_code(node.left, code + '0')\n generate_code(node.right, code + '1')\n root = heappop(heap)\n generate_code(root, '')\n data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr))\n codebook_encoding = encode_huffman_tree(root)\n return data_encoding, codebook_encoding\n\n\n<mask token>\n", "step-5": "import tensorflow as tf\nfrom sklearn.cluster import KMeans\nimport tensorflow.keras as keras\nfrom copy import deepcopy\nimport numpy as np\nimport h5py\nfrom collections import defaultdict, namedtuple\nfrom heapq import heappush, heappop, heapify\nimport struct\ntf.enable_eager_execution()\n\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(-1, 28, 28, 1).astype(np.float32)\nx_test = x_test.reshape(-1, 28, 28, 1).astype(np.float32)\nx_train, x_test = x_train / 255.0, x_test / 255.0\ny_train = keras.utils.to_categorical(y_train, 10)\ny_test = keras.utils.to_categorical(y_test, 10)\nprint(x_test.shape)\n\nCOMPRESSION_RATE = 0.9\nBATCH_SIZE = 50\nNUM_BATCHES = 1000\nNUM_EPOCH = 1\nBITS = 5\nMAX_SPAN = 2 ** BITS\nLEARNING_RATE = 0.001\n\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Conv2D(32, (5, 5), activation='relu', input_shape=[28, 28, 1]),\n tf.keras.layers.Conv2D(64, (5, 5), activation='relu'),\n tf.keras.layers.MaxPool2D(pool_size=(2, 2)),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dropout(0.5),\n tf.keras.layers.Dense(128, activation=tf.nn.relu),\n tf.keras.layers.Dropout(0.5),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\nmodel.compile(optimizer=tf.train.AdamOptimizer(learning_rate=LEARNING_RATE),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n\n# history = model.fit(x_train, y_train, validation_split=0.2, epochs=5, batch_size=50)\n# score = model.evaluate(x_test, y_test)\n# print(score[1])\n\n# model.save_weights('./result/my_model.h5', save_format='h5')\n\nmodel.load_weights('./result/my_model.h5')\nscore = model.evaluate(x_test, y_test)\nprint(score[1])\n\n\ndef get_batch(batch_size):\n index = np.random.randint(0, np.shape(x_train)[0], batch_size)\n return x_train[index, :], y_train[index]\n\n\ndef prune_weights(weight):\n for i in range(weight.shape[-1]):\n tmp = deepcopy(weight[..., i])\n tmp = np.abs(tmp)\n tmp = np.sort(np.array(tmp))\n # compute threshold\n threshold = tmp[int(tmp.shape[0] * COMPRESSION_RATE)]\n weight[..., i][np.abs(weight[..., i]) < threshold] = 0\n sparse_matrix = deepcopy(weight)\n sparse_matrix[sparse_matrix != 0] = 1\n return weight, sparse_matrix\n\n\nSparse_layer = {}\n\n# Pruning\nfor layer_id in range(len(model.layers)):\n layer = model.layers[layer_id]\n weight = layer.get_weights()\n # weight:weight[0]\n # bias:weight[1]\n if len(weight) > 0:\n if layer_id != 0:\n w = deepcopy(weight)\n new_weight, sparse_matrix = prune_weights(w[0])\n Sparse_layer[layer_id] = sparse_matrix\n w[0] = new_weight\n layer.set_weights(w)\n\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(score[1])\n\n# Retrain\nfor epoch in range(NUM_EPOCH):\n for j in range(x_train.shape[0] // BATCH_SIZE):\n begin = j*BATCH_SIZE\n if j*BATCH_SIZE + BATCH_SIZE > x_train.shape[0]:\n end = x_train.shape[0]\n else:\n end = j*BATCH_SIZE + BATCH_SIZE\n X, Y = x_train[begin:end], y_train[begin:end]\n # train on each batch\n model.train_on_batch(X, Y)\n # apply Sparse connection\n for layer_id in Sparse_layer:\n w = model.layers[layer_id].get_weights()\n w[0] = w[0] * Sparse_layer[layer_id]\n model.layers[layer_id].set_weights(w)\n score = model.evaluate(x_test, y_test, verbose=0)\n print('val loss: {}'.format(score[0]))\n print('val acc: {}'.format(score[1]))\n\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(score[1])\n\ncluster_index = dict()\ncluster_centroids = dict()\n\n\n# Weight Share and Quantization\nfor layer_id in Sparse_layer:\n layer = model.layers[layer_id]\n weight = layer.get_weights()\n w = deepcopy(weight)\n shape = w[0].shape\n\n weight_array = w[0].flatten()\n nonzero_weight = w[0][Sparse_layer[layer_id] != 0].flatten()\n nonzero_index = np.where(Sparse_layer[layer_id].flatten() != 0)[0]\n\n max_weight = max(nonzero_weight)\n min_weight = min(nonzero_weight)\n space = np.linspace(min_weight, max_weight, num=2 ** BITS)\n kmeans = KMeans(n_clusters=len(space), init=space.reshape(-1, 1), n_init=1, precompute_distances=True,\n algorithm=\"full\")\n kmeans.fit(nonzero_weight.reshape(-1, 1))\n # cluster index of each weight\n layer_cluster_index = kmeans.labels_\n # value of the centroids\n layer_centroids = kmeans.cluster_centers_.flatten()\n # Add to dict\n cluster_index[layer_id] = layer_cluster_index\n cluster_centroids[layer_id] = layer_centroids\n\n # set new weight\n new_weight = kmeans.cluster_centers_[kmeans.labels_].flatten()\n for idx in range(len(nonzero_index)):\n index = nonzero_index[idx]\n weight_array[index] = new_weight[idx]\n # new_weight = kmeans.cluster_centers_[kmeans.labels_].reshape(shape)\n # w[0] = new_weight\n w[0] = weight_array.reshape(shape)\n layer.set_weights(w)\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(score[1])\n\n\n# calculate gradient and get the fine-tuned centroids\n# for epoch in range(NUM_EPOCH):\n# for j in range(x_train.shape[0] // BATCH_SIZE):\n# begin = j * BATCH_SIZE\n# if j * BATCH_SIZE + BATCH_SIZE > x_train.shape[0]:\n# end = x_train.shape[0]\n# else:\n# end = j * BATCH_SIZE + BATCH_SIZE\n# X, Y = x_train[begin:end], y_train[begin:end]\n# with tf.GradientTape() as tape:\n# y_predict = model(X)\n# loss = tf.losses.softmax_cross_entropy(onehot_labels=Y, logits=y_predict)\n# grads = tape.gradient(loss, model.variables)\n# gradient_num = 0\n# for layer_id in Sparse_layer:\n# gradient_num += 2\n# gradient = grads[gradient_num].numpy().flatten()\n#\n# # Get the gradient of the nonzero position\n# nonzero_gradient = gradient[Sparse_layer[layer_id].flatten() != 0].flatten()\n# nonzero_index = np.where(Sparse_layer[layer_id].flatten() != 0)[0]\n# # print(len(nonzero_gradient))\n#\n# gradient_index = np.zeros(2 ** BITS)\n# # Calculate the sum of gradient of the same cluster\n# for i in range(len(nonzero_gradient)):\n# gradient_index[cluster_index[layer_id][i]] += gradient[i]\n# # Update centroid\n# fine_tuned_centroids = cluster_centroids[layer_id]-LEARNING_RATE*gradient_index\n# cluster_centroids[layer_id] = fine_tuned_centroids\n#\n# w = model.layers[layer_id].get_weights()\n# shape = w[0].shape\n# weight_array = w[0].flatten()\n# new_weight = fine_tuned_centroids[cluster_index[layer_id]]\n# for idx in range(len(nonzero_index)):\n# index = nonzero_index[idx]\n# weight_array[index] = new_weight[idx]\n#\n# w[0] = weight_array.reshape(shape)\n# model.layers[layer_id].set_weights(w)\n# score = model.evaluate(x_test, y_test, verbose=0)\n# print('val loss: {}'.format(score[0]))\n# print('val acc: {}'.format(score[1]))\n\n\nprint('-------------------')\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(score[1])\n\n\nlayer_relative_index = dict()\nlayer_weight_cluster_index = dict()\n\nNode = namedtuple('Node', ['frequency', 'value', 'left', 'right'])\nNode.__lt__ = lambda x, y: x.frequency < y.frequency\n\n\ndef encode_huffman_tree(root):\n \"\"\"\n Encodes a huffman tree to string of '0's and '1's\n \"\"\"\n # converter = {'float32':float2bitstr, 'int32':int2bitstr}\n code_list = []\n\n def encode_node(node):\n if node.value is not None: # node is leaf node\n code_list.append('1')\n lst = list(int2bitstr(node.value))\n code_list.extend(lst)\n else:\n code_list.append('0')\n encode_node(node.left)\n encode_node(node.right)\n\n encode_node(root)\n return ''.join(code_list)\n\n\ndef int2bitstr(integer):\n four_bytes = struct.pack('>I', integer) # bytes\n return ''.join(f'{byte:08b}' for byte in four_bytes) # string of '0's and '1's\n\n\ndef bitstr2int(bitstr):\n byte_arr = bytearray(int(bitstr[i:i + 8], 2) for i in range(0, len(bitstr), 8))\n return struct.unpack('>I', byte_arr)[0]\n\n\ndef huffman_encode(arr):\n # count the frequency of each number in array\n frequency_map = defaultdict(int)\n for value in np.nditer(arr):\n value = int(value)\n frequency_map[value] += 1\n\n heap = [Node(frequency, value, None, None) for value, frequency in frequency_map.items()]\n heapify(heap)\n\n # Merge nodes\n while len(heap) > 1:\n node1 = heappop(heap)\n node2 = heappop(heap)\n merged = Node(node1.frequency + node2.frequency, None, node1, node2)\n heappush(heap, merged)\n\n # Generate code value mapping\n value2code = dict()\n\n def generate_code(node, code):\n if node is None:\n return\n if node.value is not None:\n value2code[node.value] = code\n return\n generate_code(node.left, code + '0')\n generate_code(node.right, code + '1')\n\n root = heappop(heap)\n generate_code(root, '')\n\n data_encoding = ''.join(value2code[int(value)] for value in np.nditer(arr))\n\n codebook_encoding = encode_huffman_tree(root)\n\n return data_encoding, codebook_encoding\n\n\n# Matrix sparsity with relative index\nfor layer_id in Sparse_layer:\n layer = model.layers[layer_id]\n weight = layer.get_weights()\n w = deepcopy(weight)\n shape = w[0].shape\n\n weight_array = w[0].flatten()\n # nonzero_weight = w[0][Sparse_layer[layer_id] != 0].flatten()\n # print(len(nonzero_weight))\n nonzero_weight_cluster_index = cluster_index[layer_id]\n print(len(nonzero_weight_cluster_index))\n nonzero_index = np.where(Sparse_layer[layer_id].flatten() != 0)[0]\n\n first = nonzero_index[0]\n\n relative = np.insert(np.diff(nonzero_index), 0, first)\n\n relative_diff_index = relative.tolist()\n\n weight_cluster_index = nonzero_weight_cluster_index.tolist()\n\n shift = 0\n for i in np.where(relative > MAX_SPAN)[0].tolist():\n while relative_diff_index[i + shift] > MAX_SPAN:\n relative_diff_index.insert(i + shift, MAX_SPAN)\n weight_cluster_index.insert(i + shift, 0)\n shift += 1\n relative_diff_index[i + shift] -= MAX_SPAN\n\n layer_relative_index[layer_id] = np.array(relative_diff_index)\n data_encoding, codebook_encoding = huffman_encode(np.array(weight_cluster_index))\n # layer_weight_cluster_index[layer_id] = np.array(weight_cluster_index)\n layer_weight_cluster_index[layer_id] = np.array([data_encoding, codebook_encoding])\n print('----------------')\n\n# print(layer_weight_value[5])\n\n# encode\nfile_name = './result/compressed_model2'\nfile = h5py.File('{}.h5'.format(file_name), mode='w')\n\nfor layer_id in range(len(model.layers)):\n layer = model.layers[layer_id]\n weight = layer.get_weights()\n if len(weight) > 0:\n file_layer = file.create_group(layer.name)\n shape = weight[0].shape\n if layer_id != 0:\n print(len(weight[0].shape))\n pshape = file_layer.create_dataset('shape', np.array(shape).shape, dtype='int32')\n pindex = file_layer.create_dataset('index', layer_relative_index[layer_id].shape, dtype='int32')\n # pcluster_index = file_layer.create_dataset('cluster_index', layer_weight_cluster_index[layer_id].shape,\n # dtype='int32')\n pcluster_index = file_layer.create_dataset('cluster_index', layer_weight_cluster_index[layer_id].shape,\n dtype=h5py.special_dtype(vlen=str))\n\n pcentroid = file_layer.create_dataset('centroid', cluster_centroids[layer_id].shape, dtype='float32')\n pshape[:] = np.array(shape)\n pindex[:] = layer_relative_index[layer_id]\n pcluster_index[:] = layer_weight_cluster_index[layer_id]\n pcentroid[:] = cluster_centroids[layer_id]\n else:\n pweight = file_layer.create_dataset('weight', weight[0].shape, dtype='float32')\n pweight[:] = weight[0]\n pbias = file_layer.create_dataset('bias', weight[1].shape, dtype='float32')\n pbias[:] = weight[1]\n\nfile.flush()\nfile.close()\n\n\n\n", "step-ids": [ 2, 4, 5, 6, 10 ] }
[ 2, 4, 5, 6, 10 ]
<|reserved_special_token_0|> class Settings: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Settings: <|reserved_special_token_0|> def __init__(self): self.colour = 230, 230, 230 self.screen_width = 1200 self.screen_height = 800 self.ship_speed = 1.5 self.bullet_speed = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 self.alien_speed = 1 self.alien_fleet = 1 self.alien_fleet_drop_speed = 10 <|reserved_special_token_1|> <|reserved_special_token_0|> class Settings: """docstring for Setting""" def __init__(self): self.colour = 230, 230, 230 self.screen_width = 1200 self.screen_height = 800 self.ship_speed = 1.5 self.bullet_speed = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 self.alien_speed = 1 self.alien_fleet = 1 self.alien_fleet_drop_speed = 10 <|reserved_special_token_1|> import pygame import sys class Settings: """docstring for Setting""" def __init__(self): self.colour = 230, 230, 230 self.screen_width = 1200 self.screen_height = 800 self.ship_speed = 1.5 self.bullet_speed = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 self.alien_speed = 1 self.alien_fleet = 1 self.alien_fleet_drop_speed = 10 <|reserved_special_token_1|> import pygame import sys # класс для хранения настроек class Settings(): """docstring for Setting""" def __init__(self): # параметры экрана self.colour = (230, 230, 230) self.screen_width = 1200 self.screen_height = 800 # параметры коробля self.ship_speed = 1.5 # параметры пули self.bullet_speed = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60,60,60) # скорость и перемещение флота self.alien_speed = 1 self.alien_fleet = 1 self.alien_fleet_drop_speed = 10
flexible
{ "blob_id": "2402188380bc0189b88e3cfcbaabf64a9919b3d5", "index": 8810, "step-1": "<mask token>\n\n\nclass Settings:\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Settings:\n <mask token>\n\n def __init__(self):\n self.colour = 230, 230, 230\n self.screen_width = 1200\n self.screen_height = 800\n self.ship_speed = 1.5\n self.bullet_speed = 1\n self.bullet_width = 3\n self.bullet_height = 15\n self.bullet_color = 60, 60, 60\n self.alien_speed = 1\n self.alien_fleet = 1\n self.alien_fleet_drop_speed = 10\n", "step-3": "<mask token>\n\n\nclass Settings:\n \"\"\"docstring for Setting\"\"\"\n\n def __init__(self):\n self.colour = 230, 230, 230\n self.screen_width = 1200\n self.screen_height = 800\n self.ship_speed = 1.5\n self.bullet_speed = 1\n self.bullet_width = 3\n self.bullet_height = 15\n self.bullet_color = 60, 60, 60\n self.alien_speed = 1\n self.alien_fleet = 1\n self.alien_fleet_drop_speed = 10\n", "step-4": "import pygame\nimport sys\n\n\nclass Settings:\n \"\"\"docstring for Setting\"\"\"\n\n def __init__(self):\n self.colour = 230, 230, 230\n self.screen_width = 1200\n self.screen_height = 800\n self.ship_speed = 1.5\n self.bullet_speed = 1\n self.bullet_width = 3\n self.bullet_height = 15\n self.bullet_color = 60, 60, 60\n self.alien_speed = 1\n self.alien_fleet = 1\n self.alien_fleet_drop_speed = 10\n", "step-5": "import pygame\nimport sys\n\n# класс для хранения настроек\nclass Settings():\n\t\"\"\"docstring for Setting\"\"\"\n\tdef __init__(self):\n\t\t# параметры экрана\n\t\tself.colour = (230, 230, 230)\n\t\tself.screen_width = 1200\n\t\tself.screen_height = 800\t\n\t\t# параметры коробля\n\t\tself.ship_speed = 1.5\n\n\t\t# параметры пули\n\t\tself.bullet_speed = 1\n\t\tself.bullet_width = 3\n\t\tself.bullet_height = 15\n\t\tself.bullet_color = (60,60,60)\n\n\t\t# скорость и перемещение флота\n\t\tself.alien_speed = 1\n\t\tself.alien_fleet = 1\n\t\tself.alien_fleet_drop_speed = 10", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> while message != 'quit': message = input(prompt) if message != 'quit': print(message) <|reserved_special_token_0|> while active: message = input(prompt) if message == 'quit': active = False else: print(message) <|reserved_special_token_1|> prompt = 'Enter a message and I will repeat it to you: ' message = ' ' while message != 'quit': message = input(prompt) if message != 'quit': print(message) prompt = 'Enter a message and I will repeat it to you: ' active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message) <|reserved_special_token_1|> prompt = "Enter a message and I will repeat it to you: " message = " " while message != 'quit': message = input(prompt) if message != 'quit': print(message) # using the 'flag' variable prompt = "Enter a message and I will repeat it to you: " # active is the variable used in this case as flag active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message)
flexible
{ "blob_id": "1a6f84835ec2f5fbbb064aef2cd872c24eb3839d", "index": 8717, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile message != 'quit':\n message = input(prompt)\n if message != 'quit':\n print(message)\n<mask token>\nwhile active:\n message = input(prompt)\n if message == 'quit':\n active = False\n else:\n print(message)\n", "step-3": "prompt = 'Enter a message and I will repeat it to you: '\nmessage = ' '\nwhile message != 'quit':\n message = input(prompt)\n if message != 'quit':\n print(message)\nprompt = 'Enter a message and I will repeat it to you: '\nactive = True\nwhile active:\n message = input(prompt)\n if message == 'quit':\n active = False\n else:\n print(message)\n", "step-4": "prompt = \"Enter a message and I will repeat it to you: \"\n\nmessage = \" \"\n\nwhile message != 'quit':\n message = input(prompt)\n if message != 'quit':\n print(message)\n\n# using the 'flag' variable\n\nprompt = \"Enter a message and I will repeat it to you: \"\n\n# active is the variable used in this case as flag\n\nactive = True\n\nwhile active:\n message = input(prompt)\n \n if message == 'quit':\n active = False\n else:\n print(message)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import matplotlib.pyplot as plt import numpy as np steps = 10 num_tests = 100 res = [] with open('txt.txt', 'r') as f: data = f.readlines() line = 0 for i in range(10, 110, 10): agg = 0 for j in range(num_tests): agg += int(data[line]) line += 1 res.append(agg/num_tests) x = list(range(10, 110, steps)) y = res z = np.polyfit(x, res, 2) # print(z) p = np.poly1d(z) plt.plot(x, y, 'o') plt.plot(x, p(x),label = "Best fit 2 degree polynomial") plt.title("#messages vs. #nodes in graph (GHS algo.) (Averaged over 100 runs)") plt.xlabel("Number of nodes in fully connected graph") plt.ylabel("Number of messages") plt.legend() # plt.show() plt.savefig("Messages.svg") plt.clf() steps = 10 num_tests = 10 res = [] with open('txt2.txt', 'r') as f: data = f.readlines() line = 0 for procs in range(1,13): times = [] for i in range(10, 110, 10): temp = 0 for num in range(num_tests): temp += float(data[line].split()[1]) line += 3 times.append(temp/num_tests) res.append(times) x = list(range(10, 110, steps)) y = res # z = np.polyfit(x, res, 2) # print(z) # p = np.poly1d(z) # plt.plot(x, y, 'o') # plt.plot(x, p(x),label = "Best fit 2 degree polynomial") plt.title("Time taken vs. number of cores used (Averaged over 10 runs)") plt.xlabel("Number of nodes in fully connected graph") plt.ylabel("Time taken (in seconds)") # for procs in range(1,13): for procs in [1,2,4,8,12]: plt.plot(x,res[procs-1],label = str((procs))+' Cores') plt.legend() # plt.show() plt.savefig("Time.svg")
normal
{ "blob_id": "176ffac7ad47f5c43a24acc664631f8353ec5100", "index": 967, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('txt.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for i in range(10, 110, 10):\n agg = 0\n for j in range(num_tests):\n agg += int(data[line])\n line += 1\n res.append(agg / num_tests)\n<mask token>\nplt.plot(x, y, 'o')\nplt.plot(x, p(x), label='Best fit 2 degree polynomial')\nplt.title('#messages vs. #nodes in graph (GHS algo.) (Averaged over 100 runs)')\nplt.xlabel('Number of nodes in fully connected graph')\nplt.ylabel('Number of messages')\nplt.legend()\nplt.savefig('Messages.svg')\nplt.clf()\n<mask token>\nwith open('txt2.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for procs in range(1, 13):\n times = []\n for i in range(10, 110, 10):\n temp = 0\n for num in range(num_tests):\n temp += float(data[line].split()[1])\n line += 3\n times.append(temp / num_tests)\n res.append(times)\n<mask token>\nplt.title('Time taken vs. number of cores used (Averaged over 10 runs)')\nplt.xlabel('Number of nodes in fully connected graph')\nplt.ylabel('Time taken (in seconds)')\nfor procs in [1, 2, 4, 8, 12]:\n plt.plot(x, res[procs - 1], label=str(procs) + ' Cores')\nplt.legend()\nplt.savefig('Time.svg')\n", "step-3": "<mask token>\nsteps = 10\nnum_tests = 100\nres = []\nwith open('txt.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for i in range(10, 110, 10):\n agg = 0\n for j in range(num_tests):\n agg += int(data[line])\n line += 1\n res.append(agg / num_tests)\nx = list(range(10, 110, steps))\ny = res\nz = np.polyfit(x, res, 2)\np = np.poly1d(z)\nplt.plot(x, y, 'o')\nplt.plot(x, p(x), label='Best fit 2 degree polynomial')\nplt.title('#messages vs. #nodes in graph (GHS algo.) (Averaged over 100 runs)')\nplt.xlabel('Number of nodes in fully connected graph')\nplt.ylabel('Number of messages')\nplt.legend()\nplt.savefig('Messages.svg')\nplt.clf()\nsteps = 10\nnum_tests = 10\nres = []\nwith open('txt2.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for procs in range(1, 13):\n times = []\n for i in range(10, 110, 10):\n temp = 0\n for num in range(num_tests):\n temp += float(data[line].split()[1])\n line += 3\n times.append(temp / num_tests)\n res.append(times)\nx = list(range(10, 110, steps))\ny = res\nplt.title('Time taken vs. number of cores used (Averaged over 10 runs)')\nplt.xlabel('Number of nodes in fully connected graph')\nplt.ylabel('Time taken (in seconds)')\nfor procs in [1, 2, 4, 8, 12]:\n plt.plot(x, res[procs - 1], label=str(procs) + ' Cores')\nplt.legend()\nplt.savefig('Time.svg')\n", "step-4": "import matplotlib.pyplot as plt\nimport numpy as np\nsteps = 10\nnum_tests = 100\nres = []\nwith open('txt.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for i in range(10, 110, 10):\n agg = 0\n for j in range(num_tests):\n agg += int(data[line])\n line += 1\n res.append(agg / num_tests)\nx = list(range(10, 110, steps))\ny = res\nz = np.polyfit(x, res, 2)\np = np.poly1d(z)\nplt.plot(x, y, 'o')\nplt.plot(x, p(x), label='Best fit 2 degree polynomial')\nplt.title('#messages vs. #nodes in graph (GHS algo.) (Averaged over 100 runs)')\nplt.xlabel('Number of nodes in fully connected graph')\nplt.ylabel('Number of messages')\nplt.legend()\nplt.savefig('Messages.svg')\nplt.clf()\nsteps = 10\nnum_tests = 10\nres = []\nwith open('txt2.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for procs in range(1, 13):\n times = []\n for i in range(10, 110, 10):\n temp = 0\n for num in range(num_tests):\n temp += float(data[line].split()[1])\n line += 3\n times.append(temp / num_tests)\n res.append(times)\nx = list(range(10, 110, steps))\ny = res\nplt.title('Time taken vs. number of cores used (Averaged over 10 runs)')\nplt.xlabel('Number of nodes in fully connected graph')\nplt.ylabel('Time taken (in seconds)')\nfor procs in [1, 2, 4, 8, 12]:\n plt.plot(x, res[procs - 1], label=str(procs) + ' Cores')\nplt.legend()\nplt.savefig('Time.svg')\n", "step-5": "import matplotlib.pyplot as plt\nimport numpy as np\n\nsteps = 10\nnum_tests = 100\n\nres = []\n\nwith open('txt.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for i in range(10, 110, 10):\n agg = 0\n for j in range(num_tests):\n agg += int(data[line])\n line += 1\n res.append(agg/num_tests)\n\nx = list(range(10, 110, steps))\ny = res\n\nz = np.polyfit(x, res, 2)\n# print(z)\np = np.poly1d(z)\nplt.plot(x, y, 'o')\nplt.plot(x, p(x),label = \"Best fit 2 degree polynomial\")\n\nplt.title(\"#messages vs. #nodes in graph (GHS algo.) (Averaged over 100 runs)\")\nplt.xlabel(\"Number of nodes in fully connected graph\")\nplt.ylabel(\"Number of messages\")\n\nplt.legend()\n# plt.show()\n\nplt.savefig(\"Messages.svg\")\n\nplt.clf()\nsteps = 10\nnum_tests = 10\n\nres = []\n\nwith open('txt2.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for procs in range(1,13):\n times = []\n for i in range(10, 110, 10):\n temp = 0\n for num in range(num_tests):\n temp += float(data[line].split()[1])\n line += 3\n times.append(temp/num_tests)\n res.append(times)\n\nx = list(range(10, 110, steps))\ny = res\n\n# z = np.polyfit(x, res, 2)\n# print(z)\n# p = np.poly1d(z)\n# plt.plot(x, y, 'o')\n# plt.plot(x, p(x),label = \"Best fit 2 degree polynomial\")\n\nplt.title(\"Time taken vs. number of cores used (Averaged over 10 runs)\")\nplt.xlabel(\"Number of nodes in fully connected graph\")\nplt.ylabel(\"Time taken (in seconds)\")\n\n# for procs in range(1,13):\nfor procs in [1,2,4,8,12]:\n plt.plot(x,res[procs-1],label = str((procs))+' Cores')\n\nplt.legend()\n# plt.show()\n\nplt.savefig(\"Time.svg\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class Bunker(Sprite): <|reserved_special_token_0|> <|reserved_special_token_0|> def blitme(self): """Draw the ship at its current location""" self.screen.blit(self.image, self.rect) <|reserved_special_token_1|> <|reserved_special_token_0|> class Bunker(Sprite): def __init__(self, ai_settings, bunker_x, bunker_y, screen, images): """Initialize the ship and set its starting position""" super(Bunker, self).__init__() self.screen = screen self.images = images self.image = self.images[18] self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.centerx = bunker_x self.rect.bottom = bunker_y self.bunker_health = 5 <|reserved_special_token_0|> def blitme(self): """Draw the ship at its current location""" self.screen.blit(self.image, self.rect) <|reserved_special_token_1|> <|reserved_special_token_0|> class Bunker(Sprite): def __init__(self, ai_settings, bunker_x, bunker_y, screen, images): """Initialize the ship and set its starting position""" super(Bunker, self).__init__() self.screen = screen self.images = images self.image = self.images[18] self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.centerx = bunker_x self.rect.bottom = bunker_y self.bunker_health = 5 def update(self): """Track the HP of the bunker""" if self.bunker_health == 0: self.kill() def blitme(self): """Draw the ship at its current location""" self.screen.blit(self.image, self.rect) <|reserved_special_token_1|> import pygame from pygame.sprite import Sprite import spritesheet class Bunker(Sprite): def __init__(self, ai_settings, bunker_x, bunker_y, screen, images): """Initialize the ship and set its starting position""" super(Bunker, self).__init__() self.screen = screen self.images = images self.image = self.images[18] self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.centerx = bunker_x self.rect.bottom = bunker_y self.bunker_health = 5 def update(self): """Track the HP of the bunker""" if self.bunker_health == 0: self.kill() def blitme(self): """Draw the ship at its current location""" self.screen.blit(self.image, self.rect) <|reserved_special_token_1|> import pygame from pygame.sprite import Sprite import spritesheet class Bunker(Sprite): def __init__(self, ai_settings, bunker_x, bunker_y, screen, images): """Initialize the ship and set its starting position""" super(Bunker, self).__init__() self.screen = screen self.images = images self.image = self.images[18] self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # Start each new bunker at the bottom of the screen self.rect.centerx = bunker_x self.rect.bottom = bunker_y # Store a decimal value for the ship's center. #self.center = float(self.rect.centerx) self.bunker_health = 5 def update(self): """Track the HP of the bunker""" if self.bunker_health == 0: self.kill() def blitme(self): """Draw the ship at its current location""" self.screen.blit(self.image, self.rect)
flexible
{ "blob_id": "d088aadc4d88267b908c4f6de2928c812ef36739", "index": 1603, "step-1": "<mask token>\n\n\nclass Bunker(Sprite):\n <mask token>\n <mask token>\n\n def blitme(self):\n \"\"\"Draw the ship at its current location\"\"\"\n self.screen.blit(self.image, self.rect)\n", "step-2": "<mask token>\n\n\nclass Bunker(Sprite):\n\n def __init__(self, ai_settings, bunker_x, bunker_y, screen, images):\n \"\"\"Initialize the ship and set its starting position\"\"\"\n super(Bunker, self).__init__()\n self.screen = screen\n self.images = images\n self.image = self.images[18]\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n self.rect.centerx = bunker_x\n self.rect.bottom = bunker_y\n self.bunker_health = 5\n <mask token>\n\n def blitme(self):\n \"\"\"Draw the ship at its current location\"\"\"\n self.screen.blit(self.image, self.rect)\n", "step-3": "<mask token>\n\n\nclass Bunker(Sprite):\n\n def __init__(self, ai_settings, bunker_x, bunker_y, screen, images):\n \"\"\"Initialize the ship and set its starting position\"\"\"\n super(Bunker, self).__init__()\n self.screen = screen\n self.images = images\n self.image = self.images[18]\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n self.rect.centerx = bunker_x\n self.rect.bottom = bunker_y\n self.bunker_health = 5\n\n def update(self):\n \"\"\"Track the HP of the bunker\"\"\"\n if self.bunker_health == 0:\n self.kill()\n\n def blitme(self):\n \"\"\"Draw the ship at its current location\"\"\"\n self.screen.blit(self.image, self.rect)\n", "step-4": "import pygame\nfrom pygame.sprite import Sprite\nimport spritesheet\n\n\nclass Bunker(Sprite):\n\n def __init__(self, ai_settings, bunker_x, bunker_y, screen, images):\n \"\"\"Initialize the ship and set its starting position\"\"\"\n super(Bunker, self).__init__()\n self.screen = screen\n self.images = images\n self.image = self.images[18]\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n self.rect.centerx = bunker_x\n self.rect.bottom = bunker_y\n self.bunker_health = 5\n\n def update(self):\n \"\"\"Track the HP of the bunker\"\"\"\n if self.bunker_health == 0:\n self.kill()\n\n def blitme(self):\n \"\"\"Draw the ship at its current location\"\"\"\n self.screen.blit(self.image, self.rect)\n", "step-5": "import pygame\nfrom pygame.sprite import Sprite\nimport spritesheet\n\nclass Bunker(Sprite):\n\n def __init__(self, ai_settings, bunker_x, bunker_y, screen, images):\n \"\"\"Initialize the ship and set its starting position\"\"\"\n super(Bunker, self).__init__()\n self.screen = screen\n self.images = images\n\n self.image = self.images[18]\n\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n # Start each new bunker at the bottom of the screen\n self.rect.centerx = bunker_x\n self.rect.bottom = bunker_y\n\n # Store a decimal value for the ship's center.\n #self.center = float(self.rect.centerx)\n\n self.bunker_health = 5\n\n def update(self):\n \"\"\"Track the HP of the bunker\"\"\"\n if self.bunker_health == 0:\n self.kill()\n\n def blitme(self):\n \"\"\"Draw the ship at its current location\"\"\"\n self.screen.blit(self.image, self.rect)\n\n\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
def formula(a,b): if(b == 0): print "You can not divide by zero" else: return (a+b)/b print formula(4,4) print formula(2,0)
normal
{ "blob_id": "dffd575b9d5b763abdbce6f88586c183b71086c4", "index": 7701, "step-1": "def formula(a,b):\n if(b == 0):\n print \"You can not divide by zero\"\n else:\n return (a+b)/b \n\n\nprint formula(4,4)\nprint formula(2,0)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import redis r = redis.StrictRedis() r.set("counter", 40) print(r.get("counter")) print(r.incr("counter")) print(r.incr("counter")) print(r.get("counter"))
normal
{ "blob_id": "b38c9357030b2eac8298743cfb4d6c4d58c99ed4", "index": 7463, "step-1": "<mask token>\n", "step-2": "<mask token>\nr.set('counter', 40)\nprint(r.get('counter'))\nprint(r.incr('counter'))\nprint(r.incr('counter'))\nprint(r.get('counter'))\n", "step-3": "<mask token>\nr = redis.StrictRedis()\nr.set('counter', 40)\nprint(r.get('counter'))\nprint(r.incr('counter'))\nprint(r.incr('counter'))\nprint(r.get('counter'))\n", "step-4": "import redis\nr = redis.StrictRedis()\nr.set('counter', 40)\nprint(r.get('counter'))\nprint(r.incr('counter'))\nprint(r.incr('counter'))\nprint(r.get('counter'))\n", "step-5": "import redis\nr = redis.StrictRedis()\n\nr.set(\"counter\", 40) \nprint(r.get(\"counter\"))\nprint(r.incr(\"counter\"))\nprint(r.incr(\"counter\"))\nprint(r.get(\"counter\"))\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
def readint(): return int(raw_input()) T = readint() for t in xrange(T): N = int(raw_input()) res = 0 sum = 0 min = 1000000 for i in raw_input().split(): r = int(i) res ^= r sum += r if min > r: min = r if res == 0: sum -= min print "Case #%d: %s" % (t + 1, sum) else: print "Case #%d: NO" % (t + 1)
normal
{ "blob_id": "81a1fbd13b06e4470bfbaa0d1716d5301e1a4b36", "index": 1035, "step-1": "def readint(): return int(raw_input())\r\n\r\nT = readint()\r\nfor t in xrange(T):\r\n\tN = int(raw_input())\r\n\tres = 0\r\n\tsum = 0\r\n\tmin = 1000000\r\n\tfor i in raw_input().split():\r\n\t\tr = int(i)\r\n\t\tres ^= r\r\n\t\tsum += r\r\n\t\tif min > r: min = r\r\n\tif res == 0:\r\n\t\tsum -= min\r\n\t\tprint \"Case #%d: %s\" % (t + 1, sum)\r\n\telse:\r\n\t\tprint \"Case #%d: NO\" % (t + 1)", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for d in tests: d['code'] = d['prompt'] == 'code' d['correct'] = d['accuracy'] * d['trials'] p = d['accuracy'] d['err'] = 0.842 * math.sqrt(p * (1 - p) / d['trials']) <|reserved_special_token_0|> plt.style.use('dark_background') <|reserved_special_token_0|> plt.errorbar('shots', 'accuracy', yerr=examples_df['err'], data=examples_df, marker='o', capsize=2, color='mediumorchid', markersize=4, linewidth=1, linestyle='-', label='Examples') <|reserved_special_token_0|> plt.errorbar('shots', 'accuracy', yerr=code_df['err'], data=code_df, marker ='o', capsize=4, color='darkcyan', markersize=4, linewidth=1, label= 'Coding') plt.legend() plt.xlabel('Shots') plt.ylabel('Accuracy') plt.title('List Sort Length 5') plt.show() <|reserved_special_token_1|> <|reserved_special_token_0|> tests = [{'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 0, 'accuracy': 0.28, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 1, 'accuracy': 0.4, 'trials': 50}, { 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 3, 'accuracy': 0.3, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 5, 'accuracy': 0.28, 'trials': 50}, { 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 7, 'accuracy': 0.32, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 10, 'accuracy': 0.5, 'trials': 50}, { 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 13, 'accuracy': 0.36, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 16, 'accuracy': 0.22, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 32, 'accuracy': 0.2, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 0, 'accuracy': 0.76, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 1, 'accuracy': 0.66, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 3, 'accuracy': 0.46, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 5, 'accuracy': 0.44, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 7, 'accuracy': 0.44, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 10, 'accuracy': 0.42, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 13, 'accuracy': 0.3, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 16, 'accuracy': 0.32, 'trials': 50}] for d in tests: d['code'] = d['prompt'] == 'code' d['correct'] = d['accuracy'] * d['trials'] p = d['accuracy'] d['err'] = 0.842 * math.sqrt(p * (1 - p) / d['trials']) df = pd.DataFrame(tests) plt.style.use('dark_background') examples_df = df[df['prompt'] == 'examples'] plt.errorbar('shots', 'accuracy', yerr=examples_df['err'], data=examples_df, marker='o', capsize=2, color='mediumorchid', markersize=4, linewidth=1, linestyle='-', label='Examples') code_df = df[df['prompt'] == 'code'] plt.errorbar('shots', 'accuracy', yerr=code_df['err'], data=code_df, marker ='o', capsize=4, color='darkcyan', markersize=4, linewidth=1, label= 'Coding') plt.legend() plt.xlabel('Shots') plt.ylabel('Accuracy') plt.title('List Sort Length 5') plt.show() <|reserved_special_token_1|> import math import pandas as pd from matplotlib import pyplot as plt tests = [{'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 0, 'accuracy': 0.28, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 1, 'accuracy': 0.4, 'trials': 50}, { 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 3, 'accuracy': 0.3, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 5, 'accuracy': 0.28, 'trials': 50}, { 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 7, 'accuracy': 0.32, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 10, 'accuracy': 0.5, 'trials': 50}, { 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 13, 'accuracy': 0.36, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 16, 'accuracy': 0.22, 'trials': 50}, {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 32, 'accuracy': 0.2, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 0, 'accuracy': 0.76, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 1, 'accuracy': 0.66, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 3, 'accuracy': 0.46, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 5, 'accuracy': 0.44, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 7, 'accuracy': 0.44, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 10, 'accuracy': 0.42, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 13, 'accuracy': 0.3, 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 16, 'accuracy': 0.32, 'trials': 50}] for d in tests: d['code'] = d['prompt'] == 'code' d['correct'] = d['accuracy'] * d['trials'] p = d['accuracy'] d['err'] = 0.842 * math.sqrt(p * (1 - p) / d['trials']) df = pd.DataFrame(tests) plt.style.use('dark_background') examples_df = df[df['prompt'] == 'examples'] plt.errorbar('shots', 'accuracy', yerr=examples_df['err'], data=examples_df, marker='o', capsize=2, color='mediumorchid', markersize=4, linewidth=1, linestyle='-', label='Examples') code_df = df[df['prompt'] == 'code'] plt.errorbar('shots', 'accuracy', yerr=code_df['err'], data=code_df, marker ='o', capsize=4, color='darkcyan', markersize=4, linewidth=1, label= 'Coding') plt.legend() plt.xlabel('Shots') plt.ylabel('Accuracy') plt.title('List Sort Length 5') plt.show() <|reserved_special_token_1|> import math import pandas as pd from matplotlib import pyplot as plt tests = [ { "task": "listsort", "prompt": "examples", "length": 5, "shots": 0, "accuracy": 0.28, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 1, "accuracy": 0.40, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 3, "accuracy": 0.30, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 5, "accuracy": 0.28, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 7, "accuracy": 0.32, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 10, "accuracy": 0.50, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 13, "accuracy": 0.36, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 16, "accuracy": 0.22, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 32, "accuracy": 0.20, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 0, "accuracy": 0.76, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 1, "accuracy": 0.66, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 3, "accuracy": 0.46, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 5, "accuracy": 0.44, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 7, "accuracy": 0.44, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 10, "accuracy": 0.42, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 13, "accuracy": 0.30, "trials": 50}, { "task": "listsort", "prompt": "code", "length": 5, "shots": 16, "accuracy": 0.32, "trials": 50}, # { "task": "listsort", "prompt": "examples", "length": 10, "shots": 0, "accuracy": 0.04, "trials": 50}, # { "task": "listsort", "prompt": "examples", "length": 10, "shots": 1, "accuracy": 0.04, "trials": 50}, # { "task": "listsort", "prompt": "examples", "length": 10, "shots": 10, "accuracy": 0.00, "trials": 50}, # { "task": "listsort", "prompt": "examples", "length": 10, "shots": 32, "accuracy": 0.00, "trials": 50}, # { "task": "listsort", "prompt": "code", "length": 10, "shots": 0, "accuracy": 0.04, "trials": 50}, # { "task": "listsort", "prompt": "code", "length": 10, "shots": 1, "accuracy": 0.14, "trials": 50}, # { "task": "listsort", "prompt": "code", "length": 10, "shots": 10, "accuracy": 0.00, "trials": 50}, ] for d in tests: d["code"] = d["prompt"] == "code" d["correct"] = d["accuracy"] * d["trials"] p = d["accuracy"] # 80% confidence: 0.842 # 95% confidence: d["err"] = 0.842 * math.sqrt(p * (1-p) / d["trials"]) df = pd.DataFrame(tests) plt.style.use('dark_background') examples_df = df[df["prompt"] == "examples"] plt.errorbar('shots', 'accuracy', yerr=examples_df["err"], data=examples_df, marker='o', capsize=2, color='mediumorchid', markersize=4, linewidth=1, linestyle='-', label="Examples") code_df = df[df["prompt"] == "code"] plt.errorbar('shots', 'accuracy', yerr=code_df["err"], data=code_df, marker='o', capsize=4, color='darkcyan', markersize=4, linewidth=1, label="Coding") plt.legend() plt.xlabel("Shots") plt.ylabel("Accuracy") plt.title("List Sort Length 5") # plt.savefig('Fig2.png', dpi=300, bbox_inches='tight') plt.show() # seaborn.lineplot(data=df, x="shots", y="correct", hue="prompt", ci="sd") # length 99 # { "task": "listsort", "prompt": "examples", "length": 5, "shots" 10, "accuracy": 0.46, "trials": 50}, # { "task": "listsort", "prompt": "code", "length": 5, "shots": 0, "accuracy": 0.50, "trials": 50}, # { "task": "listsort", "prompt": "code", "length": 10, "shots": 0, "accuracy": 0.02, "trials": 50},
flexible
{ "blob_id": "6b6397fd18848ffa2ae9c0ec1443d20f2cbeb8b0", "index": 3637, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor d in tests:\n d['code'] = d['prompt'] == 'code'\n d['correct'] = d['accuracy'] * d['trials']\n p = d['accuracy']\n d['err'] = 0.842 * math.sqrt(p * (1 - p) / d['trials'])\n<mask token>\nplt.style.use('dark_background')\n<mask token>\nplt.errorbar('shots', 'accuracy', yerr=examples_df['err'], data=examples_df,\n marker='o', capsize=2, color='mediumorchid', markersize=4, linewidth=1,\n linestyle='-', label='Examples')\n<mask token>\nplt.errorbar('shots', 'accuracy', yerr=code_df['err'], data=code_df, marker\n ='o', capsize=4, color='darkcyan', markersize=4, linewidth=1, label=\n 'Coding')\nplt.legend()\nplt.xlabel('Shots')\nplt.ylabel('Accuracy')\nplt.title('List Sort Length 5')\nplt.show()\n", "step-3": "<mask token>\ntests = [{'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 0,\n 'accuracy': 0.28, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 1, 'accuracy': 0.4, 'trials': 50}, {\n 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 3,\n 'accuracy': 0.3, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 5, 'accuracy': 0.28, 'trials': 50}, {\n 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 7,\n 'accuracy': 0.32, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 10, 'accuracy': 0.5, 'trials': 50}, {\n 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 13,\n 'accuracy': 0.36, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 16, 'accuracy': 0.22, 'trials': 50},\n {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 32,\n 'accuracy': 0.2, 'trials': 50}, {'task': 'listsort', 'prompt': 'code',\n 'length': 5, 'shots': 0, 'accuracy': 0.76, 'trials': 50}, {'task':\n 'listsort', 'prompt': 'code', 'length': 5, 'shots': 1, 'accuracy': 0.66,\n 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5,\n 'shots': 3, 'accuracy': 0.46, 'trials': 50}, {'task': 'listsort',\n 'prompt': 'code', 'length': 5, 'shots': 5, 'accuracy': 0.44, 'trials': \n 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 7,\n 'accuracy': 0.44, 'trials': 50}, {'task': 'listsort', 'prompt': 'code',\n 'length': 5, 'shots': 10, 'accuracy': 0.42, 'trials': 50}, {'task':\n 'listsort', 'prompt': 'code', 'length': 5, 'shots': 13, 'accuracy': 0.3,\n 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5,\n 'shots': 16, 'accuracy': 0.32, 'trials': 50}]\nfor d in tests:\n d['code'] = d['prompt'] == 'code'\n d['correct'] = d['accuracy'] * d['trials']\n p = d['accuracy']\n d['err'] = 0.842 * math.sqrt(p * (1 - p) / d['trials'])\ndf = pd.DataFrame(tests)\nplt.style.use('dark_background')\nexamples_df = df[df['prompt'] == 'examples']\nplt.errorbar('shots', 'accuracy', yerr=examples_df['err'], data=examples_df,\n marker='o', capsize=2, color='mediumorchid', markersize=4, linewidth=1,\n linestyle='-', label='Examples')\ncode_df = df[df['prompt'] == 'code']\nplt.errorbar('shots', 'accuracy', yerr=code_df['err'], data=code_df, marker\n ='o', capsize=4, color='darkcyan', markersize=4, linewidth=1, label=\n 'Coding')\nplt.legend()\nplt.xlabel('Shots')\nplt.ylabel('Accuracy')\nplt.title('List Sort Length 5')\nplt.show()\n", "step-4": "import math\nimport pandas as pd\nfrom matplotlib import pyplot as plt\ntests = [{'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 0,\n 'accuracy': 0.28, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 1, 'accuracy': 0.4, 'trials': 50}, {\n 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 3,\n 'accuracy': 0.3, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 5, 'accuracy': 0.28, 'trials': 50}, {\n 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 7,\n 'accuracy': 0.32, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 10, 'accuracy': 0.5, 'trials': 50}, {\n 'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 13,\n 'accuracy': 0.36, 'trials': 50}, {'task': 'listsort', 'prompt':\n 'examples', 'length': 5, 'shots': 16, 'accuracy': 0.22, 'trials': 50},\n {'task': 'listsort', 'prompt': 'examples', 'length': 5, 'shots': 32,\n 'accuracy': 0.2, 'trials': 50}, {'task': 'listsort', 'prompt': 'code',\n 'length': 5, 'shots': 0, 'accuracy': 0.76, 'trials': 50}, {'task':\n 'listsort', 'prompt': 'code', 'length': 5, 'shots': 1, 'accuracy': 0.66,\n 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5,\n 'shots': 3, 'accuracy': 0.46, 'trials': 50}, {'task': 'listsort',\n 'prompt': 'code', 'length': 5, 'shots': 5, 'accuracy': 0.44, 'trials': \n 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5, 'shots': 7,\n 'accuracy': 0.44, 'trials': 50}, {'task': 'listsort', 'prompt': 'code',\n 'length': 5, 'shots': 10, 'accuracy': 0.42, 'trials': 50}, {'task':\n 'listsort', 'prompt': 'code', 'length': 5, 'shots': 13, 'accuracy': 0.3,\n 'trials': 50}, {'task': 'listsort', 'prompt': 'code', 'length': 5,\n 'shots': 16, 'accuracy': 0.32, 'trials': 50}]\nfor d in tests:\n d['code'] = d['prompt'] == 'code'\n d['correct'] = d['accuracy'] * d['trials']\n p = d['accuracy']\n d['err'] = 0.842 * math.sqrt(p * (1 - p) / d['trials'])\ndf = pd.DataFrame(tests)\nplt.style.use('dark_background')\nexamples_df = df[df['prompt'] == 'examples']\nplt.errorbar('shots', 'accuracy', yerr=examples_df['err'], data=examples_df,\n marker='o', capsize=2, color='mediumorchid', markersize=4, linewidth=1,\n linestyle='-', label='Examples')\ncode_df = df[df['prompt'] == 'code']\nplt.errorbar('shots', 'accuracy', yerr=code_df['err'], data=code_df, marker\n ='o', capsize=4, color='darkcyan', markersize=4, linewidth=1, label=\n 'Coding')\nplt.legend()\nplt.xlabel('Shots')\nplt.ylabel('Accuracy')\nplt.title('List Sort Length 5')\nplt.show()\n", "step-5": "import math\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\ntests = [\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 0, \"accuracy\": 0.28, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 1, \"accuracy\": 0.40, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 3, \"accuracy\": 0.30, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 5, \"accuracy\": 0.28, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 7, \"accuracy\": 0.32, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 10, \"accuracy\": 0.50, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 13, \"accuracy\": 0.36, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 16, \"accuracy\": 0.22, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 32, \"accuracy\": 0.20, \"trials\": 50},\n\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 0, \"accuracy\": 0.76, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 1, \"accuracy\": 0.66, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 3, \"accuracy\": 0.46, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 5, \"accuracy\": 0.44, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 7, \"accuracy\": 0.44, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 10, \"accuracy\": 0.42, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 13, \"accuracy\": 0.30, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 16, \"accuracy\": 0.32, \"trials\": 50},\n\n\n # { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 10, \"shots\": 0, \"accuracy\": 0.04, \"trials\": 50},\n # { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 10, \"shots\": 1, \"accuracy\": 0.04, \"trials\": 50},\n # { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 10, \"shots\": 10, \"accuracy\": 0.00, \"trials\": 50},\n # { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 10, \"shots\": 32, \"accuracy\": 0.00, \"trials\": 50},\n # { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 10, \"shots\": 0, \"accuracy\": 0.04, \"trials\": 50},\n # { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 10, \"shots\": 1, \"accuracy\": 0.14, \"trials\": 50},\n # { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 10, \"shots\": 10, \"accuracy\": 0.00, \"trials\": 50},\n]\nfor d in tests:\n d[\"code\"] = d[\"prompt\"] == \"code\"\n d[\"correct\"] = d[\"accuracy\"] * d[\"trials\"]\n p = d[\"accuracy\"]\n # 80% confidence: 0.842\n # 95% confidence:\n d[\"err\"] = 0.842 * math.sqrt(p * (1-p) / d[\"trials\"])\n\ndf = pd.DataFrame(tests)\n\n\nplt.style.use('dark_background')\nexamples_df = df[df[\"prompt\"] == \"examples\"]\nplt.errorbar('shots', 'accuracy', yerr=examples_df[\"err\"], data=examples_df, marker='o', capsize=2,\n color='mediumorchid', markersize=4, linewidth=1, linestyle='-', label=\"Examples\")\n\ncode_df = df[df[\"prompt\"] == \"code\"]\nplt.errorbar('shots', 'accuracy', yerr=code_df[\"err\"], data=code_df, marker='o', capsize=4,\n color='darkcyan', markersize=4, linewidth=1, label=\"Coding\")\n\n\nplt.legend()\nplt.xlabel(\"Shots\")\nplt.ylabel(\"Accuracy\")\nplt.title(\"List Sort Length 5\")\n# plt.savefig('Fig2.png', dpi=300, bbox_inches='tight')\nplt.show()\n\n\n\n# seaborn.lineplot(data=df, x=\"shots\", y=\"correct\", hue=\"prompt\", ci=\"sd\")\n\n\n\n\n# length 99\n# { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\" 10, \"accuracy\": 0.46, \"trials\": 50},\n# { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 5, \"shots\": 0, \"accuracy\": 0.50, \"trials\": 50},\n# { \"task\": \"listsort\", \"prompt\": \"code\", \"length\": 10, \"shots\": 0, \"accuracy\": 0.02, \"trials\": 50},\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class PasswordGenerator: <|reserved_special_token_0|> def __init__(self, length, *, uppercase=True, lowercase=True, digits= True, special=True): self.length = length self.uppercase = uppercase self.lowercase = lowercase self.digits = digits self.special = special def generate(self, length=None, uppercase=None, lowercase=None, digits= None, special=None): """Generate a random password Keyword Args: length (int): The length of the password uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password Returns: str: The freshly generated password """ if length is None: length = self.length allowed_chars = '' if uppercase is not None: allowed_chars += ascii_uppercase if uppercase else '' elif self.uppercase: allowed_chars += ascii_uppercase if lowercase is not None: allowed_chars += ascii_lowercase if lowercase else '' elif self.lowercase: allowed_chars += ascii_lowercase if digits is not None: allowed_chars += all_digits if digits else '' elif self.digits: allowed_chars += all_digits if special is not None: allowed_chars += punctuation if special else '' elif self.special: allowed_chars += punctuation return ''.join(choice(allowed_chars) for _ in range(length)) def __len__(self): return self.length if self.length >= 0 else 0 <|reserved_special_token_1|> <|reserved_special_token_0|> class PasswordRequirements: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class PasswordGenerator: """A random password generator Args: length (int): The length of the password Keyword Args: uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password """ def __init__(self, length, *, uppercase=True, lowercase=True, digits= True, special=True): self.length = length self.uppercase = uppercase self.lowercase = lowercase self.digits = digits self.special = special def generate(self, length=None, uppercase=None, lowercase=None, digits= None, special=None): """Generate a random password Keyword Args: length (int): The length of the password uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password Returns: str: The freshly generated password """ if length is None: length = self.length allowed_chars = '' if uppercase is not None: allowed_chars += ascii_uppercase if uppercase else '' elif self.uppercase: allowed_chars += ascii_uppercase if lowercase is not None: allowed_chars += ascii_lowercase if lowercase else '' elif self.lowercase: allowed_chars += ascii_lowercase if digits is not None: allowed_chars += all_digits if digits else '' elif self.digits: allowed_chars += all_digits if special is not None: allowed_chars += punctuation if special else '' elif self.special: allowed_chars += punctuation return ''.join(choice(allowed_chars) for _ in range(length)) def __len__(self): return self.length if self.length >= 0 else 0 <|reserved_special_token_1|> <|reserved_special_token_0|> def check_password(password): """Check a given password against known data breaches Note: This method uses the `Have I Been Pwned <https://haveibeenpwned.com/>`_ Passwords API. The unhashed password nor its full `SHA-1 <https://en.wikipedia.org/wiki/SHA-1>`_ hash never leave the device. Args: password (str): The password to check Returns: int: The number of times the password has been found """ sha1 = hashlib.sha1(password.encode('utf-8')).hexdigest() response = requests.get(f'https://api.pwnedpasswords.com/range/{sha1[:5]}') hash_suffix_list = [x.split(':') for x in response.text.splitlines(False)] try: count = [count for suffix, count in hash_suffix_list if sha1. endswith(suffix.lower())][0] except IndexError: return 0 return int(count) class PasswordRequirements: """A set of requirements to check passwords against Keyword Args: min_length (int): The minimum length of the password min_digits (int): The minimum number of digits in the password min_special (int): The minimum number of special characters in the password min_alpha (int): The minimum number of alphabetical characters in the password min_upper (int): The minimum number of uppercase letters in the password min_lower (int): The minimum number of lowercase letters in the password check_breaches (bool): Whether to ensure that passwords aren't found in known data breaches (uses :meth:`~passwd.check_password`) func (function): A function that takes in a password (:class:`str`) and returns a :class:`bool` that must be ``True`` for the password to meet all requirements """ def __init__(self, *, min_length=0, min_digits=0, min_special=0, min_alpha=0, min_upper=0, min_lower=0, check_breaches=False, func=None ): self.min_length = min_length self.min_digits = min_digits self.min_special = min_special self.min_alpha = min_alpha self.min_upper = min_upper self.min_lower = min_lower self.check_breaches = check_breaches self.func = func def check(self, password): """Check a password against the requirements Args: password (str): The password to check Returns: bool: Whether the password meets all the given requirements """ if len(password) < self.min_length: return False digits = len(findall('\\d', password)) if digits < self.min_digits: return False special_chars = sum(v for k, v in Counter(password).items() if k in punctuation) if special_chars < self.min_special: return False alpha_chars = sum(v for k, v in Counter(password).items() if k in ascii_letters) if alpha_chars < self.min_alpha: return False upper_chars = sum(v for k, v in Counter(password).items() if k in ascii_uppercase) if upper_chars < self.min_upper: return False lower_chars = sum(v for k, v in Counter(password).items() if k in ascii_lowercase) if lower_chars < self.min_lower: return False if self.check_breaches and check_password(password): return False if self.func and not self.func(password): return False return True class PasswordGenerator: """A random password generator Args: length (int): The length of the password Keyword Args: uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password """ def __init__(self, length, *, uppercase=True, lowercase=True, digits= True, special=True): self.length = length self.uppercase = uppercase self.lowercase = lowercase self.digits = digits self.special = special def generate(self, length=None, uppercase=None, lowercase=None, digits= None, special=None): """Generate a random password Keyword Args: length (int): The length of the password uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password Returns: str: The freshly generated password """ if length is None: length = self.length allowed_chars = '' if uppercase is not None: allowed_chars += ascii_uppercase if uppercase else '' elif self.uppercase: allowed_chars += ascii_uppercase if lowercase is not None: allowed_chars += ascii_lowercase if lowercase else '' elif self.lowercase: allowed_chars += ascii_lowercase if digits is not None: allowed_chars += all_digits if digits else '' elif self.digits: allowed_chars += all_digits if special is not None: allowed_chars += punctuation if special else '' elif self.special: allowed_chars += punctuation return ''.join(choice(allowed_chars) for _ in range(length)) def __len__(self): return self.length if self.length >= 0 else 0 <|reserved_special_token_1|> __version__ = '1.2.0' import hashlib from collections import Counter from re import findall from secrets import choice from string import ascii_letters, ascii_lowercase, ascii_uppercase from string import digits as all_digits from string import punctuation import requests def check_password(password): """Check a given password against known data breaches Note: This method uses the `Have I Been Pwned <https://haveibeenpwned.com/>`_ Passwords API. The unhashed password nor its full `SHA-1 <https://en.wikipedia.org/wiki/SHA-1>`_ hash never leave the device. Args: password (str): The password to check Returns: int: The number of times the password has been found """ sha1 = hashlib.sha1(password.encode('utf-8')).hexdigest() response = requests.get(f'https://api.pwnedpasswords.com/range/{sha1[:5]}') hash_suffix_list = [x.split(':') for x in response.text.splitlines(False)] try: count = [count for suffix, count in hash_suffix_list if sha1. endswith(suffix.lower())][0] except IndexError: return 0 return int(count) class PasswordRequirements: """A set of requirements to check passwords against Keyword Args: min_length (int): The minimum length of the password min_digits (int): The minimum number of digits in the password min_special (int): The minimum number of special characters in the password min_alpha (int): The minimum number of alphabetical characters in the password min_upper (int): The minimum number of uppercase letters in the password min_lower (int): The minimum number of lowercase letters in the password check_breaches (bool): Whether to ensure that passwords aren't found in known data breaches (uses :meth:`~passwd.check_password`) func (function): A function that takes in a password (:class:`str`) and returns a :class:`bool` that must be ``True`` for the password to meet all requirements """ def __init__(self, *, min_length=0, min_digits=0, min_special=0, min_alpha=0, min_upper=0, min_lower=0, check_breaches=False, func=None ): self.min_length = min_length self.min_digits = min_digits self.min_special = min_special self.min_alpha = min_alpha self.min_upper = min_upper self.min_lower = min_lower self.check_breaches = check_breaches self.func = func def check(self, password): """Check a password against the requirements Args: password (str): The password to check Returns: bool: Whether the password meets all the given requirements """ if len(password) < self.min_length: return False digits = len(findall('\\d', password)) if digits < self.min_digits: return False special_chars = sum(v for k, v in Counter(password).items() if k in punctuation) if special_chars < self.min_special: return False alpha_chars = sum(v for k, v in Counter(password).items() if k in ascii_letters) if alpha_chars < self.min_alpha: return False upper_chars = sum(v for k, v in Counter(password).items() if k in ascii_uppercase) if upper_chars < self.min_upper: return False lower_chars = sum(v for k, v in Counter(password).items() if k in ascii_lowercase) if lower_chars < self.min_lower: return False if self.check_breaches and check_password(password): return False if self.func and not self.func(password): return False return True class PasswordGenerator: """A random password generator Args: length (int): The length of the password Keyword Args: uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password """ def __init__(self, length, *, uppercase=True, lowercase=True, digits= True, special=True): self.length = length self.uppercase = uppercase self.lowercase = lowercase self.digits = digits self.special = special def generate(self, length=None, uppercase=None, lowercase=None, digits= None, special=None): """Generate a random password Keyword Args: length (int): The length of the password uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password Returns: str: The freshly generated password """ if length is None: length = self.length allowed_chars = '' if uppercase is not None: allowed_chars += ascii_uppercase if uppercase else '' elif self.uppercase: allowed_chars += ascii_uppercase if lowercase is not None: allowed_chars += ascii_lowercase if lowercase else '' elif self.lowercase: allowed_chars += ascii_lowercase if digits is not None: allowed_chars += all_digits if digits else '' elif self.digits: allowed_chars += all_digits if special is not None: allowed_chars += punctuation if special else '' elif self.special: allowed_chars += punctuation return ''.join(choice(allowed_chars) for _ in range(length)) def __len__(self): return self.length if self.length >= 0 else 0 <|reserved_special_token_1|> __version__ = "1.2.0" import hashlib from collections import Counter from re import findall from secrets import choice from string import ascii_letters, ascii_lowercase, ascii_uppercase from string import digits as all_digits from string import punctuation import requests def check_password(password): """Check a given password against known data breaches Note: This method uses the `Have I Been Pwned <https://haveibeenpwned.com/>`_ Passwords API. The unhashed password nor its full `SHA-1 <https://en.wikipedia.org/wiki/SHA-1>`_ hash never leave the device. Args: password (str): The password to check Returns: int: The number of times the password has been found """ sha1 = hashlib.sha1(password.encode("utf-8")).hexdigest() response = requests.get(f"https://api.pwnedpasswords.com/range/{sha1[:5]}") hash_suffix_list = [x.split(":") for x in response.text.splitlines(False)] try: count = [ count for suffix, count in hash_suffix_list if sha1.endswith(suffix.lower()) ][0] except IndexError: return 0 return int(count) class PasswordRequirements: """A set of requirements to check passwords against Keyword Args: min_length (int): The minimum length of the password min_digits (int): The minimum number of digits in the password min_special (int): The minimum number of special characters in the password min_alpha (int): The minimum number of alphabetical characters in the password min_upper (int): The minimum number of uppercase letters in the password min_lower (int): The minimum number of lowercase letters in the password check_breaches (bool): Whether to ensure that passwords aren't found in known data breaches (uses :meth:`~passwd.check_password`) func (function): A function that takes in a password (:class:`str`) and returns a :class:`bool` that must be ``True`` for the password to meet all requirements """ def __init__( self, *, min_length=0, min_digits=0, min_special=0, min_alpha=0, min_upper=0, min_lower=0, check_breaches=False, func=None, ): self.min_length = min_length self.min_digits = min_digits self.min_special = min_special self.min_alpha = min_alpha self.min_upper = min_upper self.min_lower = min_lower self.check_breaches = check_breaches self.func = func def check(self, password): """Check a password against the requirements Args: password (str): The password to check Returns: bool: Whether the password meets all the given requirements """ if len(password) < self.min_length: return False digits = len(findall(r"\d", password)) if digits < self.min_digits: return False special_chars = sum(v for k, v in Counter(password).items() if k in punctuation) if special_chars < self.min_special: return False alpha_chars = sum(v for k, v in Counter(password).items() if k in ascii_letters) if alpha_chars < self.min_alpha: return False upper_chars = sum( v for k, v in Counter(password).items() if k in ascii_uppercase ) if upper_chars < self.min_upper: return False lower_chars = sum( v for k, v in Counter(password).items() if k in ascii_lowercase ) if lower_chars < self.min_lower: return False if self.check_breaches and check_password(password): return False if self.func and not self.func(password): return False return True class PasswordGenerator: """A random password generator Args: length (int): The length of the password Keyword Args: uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password """ def __init__( self, length, *, uppercase=True, lowercase=True, digits=True, special=True ): self.length = length self.uppercase = uppercase self.lowercase = lowercase self.digits = digits self.special = special def generate( self, length=None, uppercase=None, lowercase=None, digits=None, special=None ): """Generate a random password Keyword Args: length (int): The length of the password uppercase (bool): Whether to allow uppercase letters in the password lowercase (bool): Whether to allow lowercase letters in the password digits (bool): Whether to allow numerical digits in the password special (bool): Whether to allow special characters in the password Returns: str: The freshly generated password """ if length is None: length = self.length allowed_chars = "" if uppercase is not None: allowed_chars += ascii_uppercase if uppercase else "" elif self.uppercase: allowed_chars += ascii_uppercase if lowercase is not None: allowed_chars += ascii_lowercase if lowercase else "" elif self.lowercase: allowed_chars += ascii_lowercase if digits is not None: allowed_chars += all_digits if digits else "" elif self.digits: allowed_chars += all_digits if special is not None: allowed_chars += punctuation if special else "" elif self.special: allowed_chars += punctuation return "".join(choice(allowed_chars) for _ in range(length)) def __len__(self): return self.length if self.length >= 0 else 0
flexible
{ "blob_id": "eafe89de10c4187057b0cc1e0e9772f03a576b0d", "index": 9771, "step-1": "<mask token>\n\n\nclass PasswordGenerator:\n <mask token>\n\n def __init__(self, length, *, uppercase=True, lowercase=True, digits=\n True, special=True):\n self.length = length\n self.uppercase = uppercase\n self.lowercase = lowercase\n self.digits = digits\n self.special = special\n\n def generate(self, length=None, uppercase=None, lowercase=None, digits=\n None, special=None):\n \"\"\"Generate a random password\n\n Keyword Args:\n length (int): The length of the password\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n\n Returns:\n str: The freshly generated password\n \"\"\"\n if length is None:\n length = self.length\n allowed_chars = ''\n if uppercase is not None:\n allowed_chars += ascii_uppercase if uppercase else ''\n elif self.uppercase:\n allowed_chars += ascii_uppercase\n if lowercase is not None:\n allowed_chars += ascii_lowercase if lowercase else ''\n elif self.lowercase:\n allowed_chars += ascii_lowercase\n if digits is not None:\n allowed_chars += all_digits if digits else ''\n elif self.digits:\n allowed_chars += all_digits\n if special is not None:\n allowed_chars += punctuation if special else ''\n elif self.special:\n allowed_chars += punctuation\n return ''.join(choice(allowed_chars) for _ in range(length))\n\n def __len__(self):\n return self.length if self.length >= 0 else 0\n", "step-2": "<mask token>\n\n\nclass PasswordRequirements:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass PasswordGenerator:\n \"\"\"A random password generator\n\n Args:\n length (int): The length of the password\n\n Keyword Args:\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n \"\"\"\n\n def __init__(self, length, *, uppercase=True, lowercase=True, digits=\n True, special=True):\n self.length = length\n self.uppercase = uppercase\n self.lowercase = lowercase\n self.digits = digits\n self.special = special\n\n def generate(self, length=None, uppercase=None, lowercase=None, digits=\n None, special=None):\n \"\"\"Generate a random password\n\n Keyword Args:\n length (int): The length of the password\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n\n Returns:\n str: The freshly generated password\n \"\"\"\n if length is None:\n length = self.length\n allowed_chars = ''\n if uppercase is not None:\n allowed_chars += ascii_uppercase if uppercase else ''\n elif self.uppercase:\n allowed_chars += ascii_uppercase\n if lowercase is not None:\n allowed_chars += ascii_lowercase if lowercase else ''\n elif self.lowercase:\n allowed_chars += ascii_lowercase\n if digits is not None:\n allowed_chars += all_digits if digits else ''\n elif self.digits:\n allowed_chars += all_digits\n if special is not None:\n allowed_chars += punctuation if special else ''\n elif self.special:\n allowed_chars += punctuation\n return ''.join(choice(allowed_chars) for _ in range(length))\n\n def __len__(self):\n return self.length if self.length >= 0 else 0\n", "step-3": "<mask token>\n\n\ndef check_password(password):\n \"\"\"Check a given password against known data breaches\n\n Note:\n This method uses the `Have I Been Pwned <https://haveibeenpwned.com/>`_ Passwords API. The unhashed password nor its full `SHA-1 <https://en.wikipedia.org/wiki/SHA-1>`_ hash never leave the device.\n\n Args:\n password (str): The password to check\n\n Returns:\n int: The number of times the password has been found\n \"\"\"\n sha1 = hashlib.sha1(password.encode('utf-8')).hexdigest()\n response = requests.get(f'https://api.pwnedpasswords.com/range/{sha1[:5]}')\n hash_suffix_list = [x.split(':') for x in response.text.splitlines(False)]\n try:\n count = [count for suffix, count in hash_suffix_list if sha1.\n endswith(suffix.lower())][0]\n except IndexError:\n return 0\n return int(count)\n\n\nclass PasswordRequirements:\n \"\"\"A set of requirements to check passwords against\n\n Keyword Args:\n min_length (int): The minimum length of the password\n min_digits (int): The minimum number of digits in the password\n min_special (int): The minimum number of special characters in the password\n min_alpha (int): The minimum number of alphabetical characters in the password\n min_upper (int): The minimum number of uppercase letters in the password\n min_lower (int): The minimum number of lowercase letters in the password\n check_breaches (bool): Whether to ensure that passwords aren't found in known data breaches (uses :meth:`~passwd.check_password`)\n func (function): A function that takes in a password (:class:`str`) and returns a :class:`bool` that must be ``True`` for the password to meet all requirements\n \"\"\"\n\n def __init__(self, *, min_length=0, min_digits=0, min_special=0,\n min_alpha=0, min_upper=0, min_lower=0, check_breaches=False, func=None\n ):\n self.min_length = min_length\n self.min_digits = min_digits\n self.min_special = min_special\n self.min_alpha = min_alpha\n self.min_upper = min_upper\n self.min_lower = min_lower\n self.check_breaches = check_breaches\n self.func = func\n\n def check(self, password):\n \"\"\"Check a password against the requirements\n\n Args:\n password (str): The password to check\n\n Returns:\n bool: Whether the password meets all the given requirements\n \"\"\"\n if len(password) < self.min_length:\n return False\n digits = len(findall('\\\\d', password))\n if digits < self.min_digits:\n return False\n special_chars = sum(v for k, v in Counter(password).items() if k in\n punctuation)\n if special_chars < self.min_special:\n return False\n alpha_chars = sum(v for k, v in Counter(password).items() if k in\n ascii_letters)\n if alpha_chars < self.min_alpha:\n return False\n upper_chars = sum(v for k, v in Counter(password).items() if k in\n ascii_uppercase)\n if upper_chars < self.min_upper:\n return False\n lower_chars = sum(v for k, v in Counter(password).items() if k in\n ascii_lowercase)\n if lower_chars < self.min_lower:\n return False\n if self.check_breaches and check_password(password):\n return False\n if self.func and not self.func(password):\n return False\n return True\n\n\nclass PasswordGenerator:\n \"\"\"A random password generator\n\n Args:\n length (int): The length of the password\n\n Keyword Args:\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n \"\"\"\n\n def __init__(self, length, *, uppercase=True, lowercase=True, digits=\n True, special=True):\n self.length = length\n self.uppercase = uppercase\n self.lowercase = lowercase\n self.digits = digits\n self.special = special\n\n def generate(self, length=None, uppercase=None, lowercase=None, digits=\n None, special=None):\n \"\"\"Generate a random password\n\n Keyword Args:\n length (int): The length of the password\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n\n Returns:\n str: The freshly generated password\n \"\"\"\n if length is None:\n length = self.length\n allowed_chars = ''\n if uppercase is not None:\n allowed_chars += ascii_uppercase if uppercase else ''\n elif self.uppercase:\n allowed_chars += ascii_uppercase\n if lowercase is not None:\n allowed_chars += ascii_lowercase if lowercase else ''\n elif self.lowercase:\n allowed_chars += ascii_lowercase\n if digits is not None:\n allowed_chars += all_digits if digits else ''\n elif self.digits:\n allowed_chars += all_digits\n if special is not None:\n allowed_chars += punctuation if special else ''\n elif self.special:\n allowed_chars += punctuation\n return ''.join(choice(allowed_chars) for _ in range(length))\n\n def __len__(self):\n return self.length if self.length >= 0 else 0\n", "step-4": "__version__ = '1.2.0'\nimport hashlib\nfrom collections import Counter\nfrom re import findall\nfrom secrets import choice\nfrom string import ascii_letters, ascii_lowercase, ascii_uppercase\nfrom string import digits as all_digits\nfrom string import punctuation\nimport requests\n\n\ndef check_password(password):\n \"\"\"Check a given password against known data breaches\n\n Note:\n This method uses the `Have I Been Pwned <https://haveibeenpwned.com/>`_ Passwords API. The unhashed password nor its full `SHA-1 <https://en.wikipedia.org/wiki/SHA-1>`_ hash never leave the device.\n\n Args:\n password (str): The password to check\n\n Returns:\n int: The number of times the password has been found\n \"\"\"\n sha1 = hashlib.sha1(password.encode('utf-8')).hexdigest()\n response = requests.get(f'https://api.pwnedpasswords.com/range/{sha1[:5]}')\n hash_suffix_list = [x.split(':') for x in response.text.splitlines(False)]\n try:\n count = [count for suffix, count in hash_suffix_list if sha1.\n endswith(suffix.lower())][0]\n except IndexError:\n return 0\n return int(count)\n\n\nclass PasswordRequirements:\n \"\"\"A set of requirements to check passwords against\n\n Keyword Args:\n min_length (int): The minimum length of the password\n min_digits (int): The minimum number of digits in the password\n min_special (int): The minimum number of special characters in the password\n min_alpha (int): The minimum number of alphabetical characters in the password\n min_upper (int): The minimum number of uppercase letters in the password\n min_lower (int): The minimum number of lowercase letters in the password\n check_breaches (bool): Whether to ensure that passwords aren't found in known data breaches (uses :meth:`~passwd.check_password`)\n func (function): A function that takes in a password (:class:`str`) and returns a :class:`bool` that must be ``True`` for the password to meet all requirements\n \"\"\"\n\n def __init__(self, *, min_length=0, min_digits=0, min_special=0,\n min_alpha=0, min_upper=0, min_lower=0, check_breaches=False, func=None\n ):\n self.min_length = min_length\n self.min_digits = min_digits\n self.min_special = min_special\n self.min_alpha = min_alpha\n self.min_upper = min_upper\n self.min_lower = min_lower\n self.check_breaches = check_breaches\n self.func = func\n\n def check(self, password):\n \"\"\"Check a password against the requirements\n\n Args:\n password (str): The password to check\n\n Returns:\n bool: Whether the password meets all the given requirements\n \"\"\"\n if len(password) < self.min_length:\n return False\n digits = len(findall('\\\\d', password))\n if digits < self.min_digits:\n return False\n special_chars = sum(v for k, v in Counter(password).items() if k in\n punctuation)\n if special_chars < self.min_special:\n return False\n alpha_chars = sum(v for k, v in Counter(password).items() if k in\n ascii_letters)\n if alpha_chars < self.min_alpha:\n return False\n upper_chars = sum(v for k, v in Counter(password).items() if k in\n ascii_uppercase)\n if upper_chars < self.min_upper:\n return False\n lower_chars = sum(v for k, v in Counter(password).items() if k in\n ascii_lowercase)\n if lower_chars < self.min_lower:\n return False\n if self.check_breaches and check_password(password):\n return False\n if self.func and not self.func(password):\n return False\n return True\n\n\nclass PasswordGenerator:\n \"\"\"A random password generator\n\n Args:\n length (int): The length of the password\n\n Keyword Args:\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n \"\"\"\n\n def __init__(self, length, *, uppercase=True, lowercase=True, digits=\n True, special=True):\n self.length = length\n self.uppercase = uppercase\n self.lowercase = lowercase\n self.digits = digits\n self.special = special\n\n def generate(self, length=None, uppercase=None, lowercase=None, digits=\n None, special=None):\n \"\"\"Generate a random password\n\n Keyword Args:\n length (int): The length of the password\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n\n Returns:\n str: The freshly generated password\n \"\"\"\n if length is None:\n length = self.length\n allowed_chars = ''\n if uppercase is not None:\n allowed_chars += ascii_uppercase if uppercase else ''\n elif self.uppercase:\n allowed_chars += ascii_uppercase\n if lowercase is not None:\n allowed_chars += ascii_lowercase if lowercase else ''\n elif self.lowercase:\n allowed_chars += ascii_lowercase\n if digits is not None:\n allowed_chars += all_digits if digits else ''\n elif self.digits:\n allowed_chars += all_digits\n if special is not None:\n allowed_chars += punctuation if special else ''\n elif self.special:\n allowed_chars += punctuation\n return ''.join(choice(allowed_chars) for _ in range(length))\n\n def __len__(self):\n return self.length if self.length >= 0 else 0\n", "step-5": "__version__ = \"1.2.0\"\n\nimport hashlib\nfrom collections import Counter\nfrom re import findall\nfrom secrets import choice\nfrom string import ascii_letters, ascii_lowercase, ascii_uppercase\nfrom string import digits as all_digits\nfrom string import punctuation\n\nimport requests\n\n\ndef check_password(password):\n \"\"\"Check a given password against known data breaches\n\n Note:\n This method uses the `Have I Been Pwned <https://haveibeenpwned.com/>`_ Passwords API. The unhashed password nor its full `SHA-1 <https://en.wikipedia.org/wiki/SHA-1>`_ hash never leave the device.\n\n Args:\n password (str): The password to check\n\n Returns:\n int: The number of times the password has been found\n \"\"\"\n\n sha1 = hashlib.sha1(password.encode(\"utf-8\")).hexdigest()\n\n response = requests.get(f\"https://api.pwnedpasswords.com/range/{sha1[:5]}\")\n\n hash_suffix_list = [x.split(\":\") for x in response.text.splitlines(False)]\n\n try:\n count = [\n count for suffix, count in hash_suffix_list if sha1.endswith(suffix.lower())\n ][0]\n except IndexError:\n return 0\n\n return int(count)\n\n\nclass PasswordRequirements:\n \"\"\"A set of requirements to check passwords against\n\n Keyword Args:\n min_length (int): The minimum length of the password\n min_digits (int): The minimum number of digits in the password\n min_special (int): The minimum number of special characters in the password\n min_alpha (int): The minimum number of alphabetical characters in the password\n min_upper (int): The minimum number of uppercase letters in the password\n min_lower (int): The minimum number of lowercase letters in the password\n check_breaches (bool): Whether to ensure that passwords aren't found in known data breaches (uses :meth:`~passwd.check_password`)\n func (function): A function that takes in a password (:class:`str`) and returns a :class:`bool` that must be ``True`` for the password to meet all requirements\n \"\"\"\n\n def __init__(\n self,\n *,\n min_length=0,\n min_digits=0,\n min_special=0,\n min_alpha=0,\n min_upper=0,\n min_lower=0,\n check_breaches=False,\n func=None,\n ):\n self.min_length = min_length\n self.min_digits = min_digits\n self.min_special = min_special\n self.min_alpha = min_alpha\n self.min_upper = min_upper\n self.min_lower = min_lower\n self.check_breaches = check_breaches\n self.func = func\n\n def check(self, password):\n \"\"\"Check a password against the requirements\n\n Args:\n password (str): The password to check\n\n Returns:\n bool: Whether the password meets all the given requirements\n \"\"\"\n\n if len(password) < self.min_length:\n return False\n\n digits = len(findall(r\"\\d\", password))\n if digits < self.min_digits:\n return False\n\n special_chars = sum(v for k, v in Counter(password).items() if k in punctuation)\n if special_chars < self.min_special:\n return False\n\n alpha_chars = sum(v for k, v in Counter(password).items() if k in ascii_letters)\n if alpha_chars < self.min_alpha:\n return False\n\n upper_chars = sum(\n v for k, v in Counter(password).items() if k in ascii_uppercase\n )\n if upper_chars < self.min_upper:\n return False\n\n lower_chars = sum(\n v for k, v in Counter(password).items() if k in ascii_lowercase\n )\n if lower_chars < self.min_lower:\n return False\n\n if self.check_breaches and check_password(password):\n return False\n\n if self.func and not self.func(password):\n return False\n\n return True\n\n\nclass PasswordGenerator:\n \"\"\"A random password generator\n\n Args:\n length (int): The length of the password\n\n Keyword Args:\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n \"\"\"\n\n def __init__(\n self, length, *, uppercase=True, lowercase=True, digits=True, special=True\n ):\n self.length = length\n self.uppercase = uppercase\n self.lowercase = lowercase\n self.digits = digits\n self.special = special\n\n def generate(\n self, length=None, uppercase=None, lowercase=None, digits=None, special=None\n ):\n \"\"\"Generate a random password\n\n Keyword Args:\n length (int): The length of the password\n uppercase (bool): Whether to allow uppercase letters in the password\n lowercase (bool): Whether to allow lowercase letters in the password\n digits (bool): Whether to allow numerical digits in the password\n special (bool): Whether to allow special characters in the password\n\n Returns:\n str: The freshly generated password\n \"\"\"\n if length is None:\n length = self.length\n \n allowed_chars = \"\"\n\n if uppercase is not None:\n allowed_chars += ascii_uppercase if uppercase else \"\"\n elif self.uppercase:\n allowed_chars += ascii_uppercase\n\n if lowercase is not None:\n allowed_chars += ascii_lowercase if lowercase else \"\"\n elif self.lowercase:\n allowed_chars += ascii_lowercase\n\n if digits is not None:\n allowed_chars += all_digits if digits else \"\"\n elif self.digits:\n allowed_chars += all_digits\n\n if special is not None:\n allowed_chars += punctuation if special else \"\"\n elif self.special:\n allowed_chars += punctuation\n\n return \"\".join(choice(allowed_chars) for _ in range(length))\n\n def __len__(self):\n return self.length if self.length >= 0 else 0\n", "step-ids": [ 4, 6, 10, 12, 13 ] }
[ 4, 6, 10, 12, 13 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> DEFAULT_LL_URL = 'https://ll.thespacedevs.com' DEFAULT_VERSION = '2.0.0' DEFAULT_API_URL = '/'.join([DEFAULT_LL_URL, DEFAULT_VERSION]) <|reserved_special_token_1|> DEFAULT_LL_URL = "https://ll.thespacedevs.com" DEFAULT_VERSION = "2.0.0" DEFAULT_API_URL = "/".join([DEFAULT_LL_URL, DEFAULT_VERSION])
flexible
{ "blob_id": "1a72da7f436e6c5e73e396b771f8ce1a3affba1a", "index": 3010, "step-1": "<mask token>\n", "step-2": "DEFAULT_LL_URL = 'https://ll.thespacedevs.com'\nDEFAULT_VERSION = '2.0.0'\nDEFAULT_API_URL = '/'.join([DEFAULT_LL_URL, DEFAULT_VERSION])\n", "step-3": "DEFAULT_LL_URL = \"https://ll.thespacedevs.com\"\nDEFAULT_VERSION = \"2.0.0\"\nDEFAULT_API_URL = \"/\".join([DEFAULT_LL_URL, DEFAULT_VERSION])\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> class WSMessage: def __init__(self, command: str, data: any=None) ->None: self.command = command self.data = data <|reserved_special_token_0|> def dictData(self) ->dict: return self.data <|reserved_special_token_1|> <|reserved_special_token_0|> class WSMessage: def __init__(self, command: str, data: any=None) ->None: self.command = command self.data = data def strData(self) ->str: return self.data def dictData(self) ->dict: return self.data <|reserved_special_token_1|> class WSCommand: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class WSMessage: def __init__(self, command: str, data: any=None) ->None: self.command = command self.data = data def strData(self) ->str: return self.data def dictData(self) ->dict: return self.data <|reserved_special_token_1|> class WSCommand: handshake_hi = 'handshake_hi' ping = 'ping' pong = 'pong' http_call = 'http_call' http_return = 'http_return' class WSMessage: def __init__(self, command: str, data: any=None) ->None: self.command = command self.data = data def strData(self) ->str: return self.data def dictData(self) ->dict: return self.data
flexible
{ "blob_id": "d4621ef378b89490278c09e569f781aef1fcef3f", "index": 7013, "step-1": "<mask token>\n\n\nclass WSMessage:\n\n def __init__(self, command: str, data: any=None) ->None:\n self.command = command\n self.data = data\n <mask token>\n\n def dictData(self) ->dict:\n return self.data\n", "step-2": "<mask token>\n\n\nclass WSMessage:\n\n def __init__(self, command: str, data: any=None) ->None:\n self.command = command\n self.data = data\n\n def strData(self) ->str:\n return self.data\n\n def dictData(self) ->dict:\n return self.data\n", "step-3": "class WSCommand:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass WSMessage:\n\n def __init__(self, command: str, data: any=None) ->None:\n self.command = command\n self.data = data\n\n def strData(self) ->str:\n return self.data\n\n def dictData(self) ->dict:\n return self.data\n", "step-4": "class WSCommand:\n handshake_hi = 'handshake_hi'\n ping = 'ping'\n pong = 'pong'\n http_call = 'http_call'\n http_return = 'http_return'\n\n\nclass WSMessage:\n\n def __init__(self, command: str, data: any=None) ->None:\n self.command = command\n self.data = data\n\n def strData(self) ->str:\n return self.data\n\n def dictData(self) ->dict:\n return self.data\n", "step-5": null, "step-ids": [ 3, 4, 5, 6 ] }
[ 3, 4, 5, 6 ]
class cal4: def setdata(self, n1): self.n1 = n1 <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> class cal4: def setdata(self, n1): self.n1 = n1 def display(self): return n1 * n1 <|reserved_special_token_0|> <|reserved_special_token_1|> class cal4: def setdata(self, n1): self.n1 = n1 def display(self): return n1 * n1 <|reserved_special_token_0|> print(c.display()) <|reserved_special_token_1|> class cal4: def setdata(self, n1): self.n1 = n1 def display(self): return n1 * n1 n1 = int(input('Enter number: ')) c = cal4() print(c.display()) <|reserved_special_token_1|> class cal4: def setdata(self,n1): self.n1 = n1 def display(self): return n1*n1 n1 = int(input("Enter number: ")) c = cal4() print(c.display())
flexible
{ "blob_id": "65b90fccd0ee74b369475aa9fe33f159881c8b82", "index": 6645, "step-1": "class cal4:\n\n def setdata(self, n1):\n self.n1 = n1\n <mask token>\n\n\n<mask token>\n", "step-2": "class cal4:\n\n def setdata(self, n1):\n self.n1 = n1\n\n def display(self):\n return n1 * n1\n\n\n<mask token>\n", "step-3": "class cal4:\n\n def setdata(self, n1):\n self.n1 = n1\n\n def display(self):\n return n1 * n1\n\n\n<mask token>\nprint(c.display())\n", "step-4": "class cal4:\n\n def setdata(self, n1):\n self.n1 = n1\n\n def display(self):\n return n1 * n1\n\n\nn1 = int(input('Enter number: '))\nc = cal4()\nprint(c.display())\n", "step-5": "class cal4:\r\n def setdata(self,n1):\r\n self.n1 = n1\r\n def display(self):\r\n return n1*n1\r\nn1 = int(input(\"Enter number: \"))\r\nc = cal4()\r\n\r\nprint(c.display())", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
<|reserved_special_token_0|> @norecursion def configuration(localization, *varargs, **kwargs): global module_type_store str_32070 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 9, 33), 'str', '') None_32071 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 9, 45), 'None') defaults = [str_32070, None_32071] module_type_store = module_type_store.open_function_context('configuration' , 9, 0, False) configuration.stypy_localization = localization configuration.stypy_type_of_self = None configuration.stypy_type_store = module_type_store configuration.stypy_function_name = 'configuration' configuration.stypy_param_names_list = ['parent_package', 'top_path'] configuration.stypy_varargs_param_name = None configuration.stypy_kwargs_param_name = None configuration.stypy_call_defaults = defaults configuration.stypy_call_varargs = varargs configuration.stypy_call_kwargs = kwargs arguments = process_argument_values(localization, None, module_type_store, 'configuration', ['parent_package', 'top_path'], None, None, defaults, varargs, kwargs) if is_error_type(arguments): module_type_store = module_type_store.close_function_context() return arguments init_call_information(module_type_store, 'configuration', localization, ['parent_package', 'top_path'], arguments) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 0, 0), 'stypy_return_type', None) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 10, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32072 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util' ) if type(import_32072) is not StypyTypeError: if import_32072 != 'pyd_module': __import__(import_32072) sys_modules_32073 = sys.modules[import_32072] import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', sys_modules_32073.module_type_store, module_type_store, [ 'Configuration']) nest_module(stypy.reporting.localization.Localization(__file__, 10, 4), __file__, sys_modules_32073, sys_modules_32073. module_type_store, module_type_store) else: from numpy.distutils.misc_util import Configuration import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', None, module_type_store, ['Configuration'], [Configuration]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 10, 4), 'numpy.distutils.misc_util', import_32072) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 11, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32074 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info') if type(import_32074) is not StypyTypeError: if import_32074 != 'pyd_module': __import__(import_32074) sys_modules_32075 = sys.modules[import_32074] import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', sys_modules_32075.module_type_store, module_type_store, [ 'get_info']) nest_module(stypy.reporting.localization.Localization(__file__, 11, 4), __file__, sys_modules_32075, sys_modules_32075. module_type_store, module_type_store) else: from numpy.distutils.system_info import get_info import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', None, module_type_store, ['get_info'], [get_info]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 11, 4), 'numpy.distutils.system_info', import_32074) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') str_32077 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 12, 27), 'str', 'integrate') parent_package_32078 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 40), 'parent_package', False) top_path_32079 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 56), 'top_path', False) kwargs_32080 = {} Configuration_32076 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 13), 'Configuration', False) Configuration_call_result_32081 = invoke(stypy.reporting.localization. Localization(__file__, 12, 13), Configuration_32076, *[str_32077, parent_package_32078, top_path_32079], **kwargs_32080) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 12, 4), 'config', Configuration_call_result_32081) str_32084 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 31), 'str', 'lapack_opt') int_32085 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 60), 'int') keyword_32086 = int_32085 kwargs_32087 = {'notfound_action': keyword_32086} get_info_32083 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 15, 22), 'get_info', False) get_info_call_result_32088 = invoke(stypy.reporting.localization. Localization(__file__, 15, 22), get_info_32083, *[str_32084], ** kwargs_32087) kwargs_32089 = {} dict_32082 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 15, 17), 'dict', False) dict_call_result_32090 = invoke(stypy.reporting.localization. Localization(__file__, 15, 17), dict_32082, *[ get_info_call_result_32088], **kwargs_32089) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 15, 4), 'lapack_opt', dict_call_result_32090) str_32093 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 33), 'str', 'libraries') list_32094 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 46), 'list') kwargs_32095 = {} lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 18, 18), 'lapack_opt', False) pop_32092 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop') pop_call_result_32096 = invoke(stypy.reporting.localization. Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094], **kwargs_32095) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 18, 4), 'lapack_libs', pop_call_result_32096) list_32097 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 15), 'list') str_32099 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 21), 'str', 'mach') str_32100 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 28), 'str', '*.f') kwargs_32101 = {} join_32098 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 20, 16), 'join', False) join_call_result_32102 = invoke(stypy.reporting.localization. Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100], **kwargs_32101) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 20, 15), list_32097, join_call_result_32102) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 20, 4), 'mach_src', list_32097) list_32103 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 19), 'list') str_32105 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 25), 'str', 'quadpack') str_32106 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 37), 'str', '*.f') kwargs_32107 = {} join_32104 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 21, 20), 'join', False) join_call_result_32108 = invoke(stypy.reporting.localization. Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106], **kwargs_32107) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 21, 19), list_32103, join_call_result_32108) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 21, 4), 'quadpack_src', list_32103) list_32114 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 47), 'list') str_32115 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32115) str_32116 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 23), 'str', 'bnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32116) str_32117 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 34), 'str', 'cfode.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32117) str_32118 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 8), 'str', 'ewset.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32118) str_32119 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 19), 'str', 'fnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32119) str_32120 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 30), 'str', 'intdy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32120) str_32121 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 8), 'str', 'lsoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32121) str_32122 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 19), 'str', 'prja.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32122) str_32123 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 29), 'str', 'solsy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32123) str_32124 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 40), 'str', 'srcma.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32124) str_32125 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 8), 'str', 'stoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32125) str_32126 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32126) str_32127 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32127) str_32128 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 43), 'str', 'xsetf.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32128) str_32129 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 27, 8), 'str', 'xsetun.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32129) comprehension_32130 = get_contained_elements_type(stypy.reporting. localization.Localization(__file__, 22, 17), list_32114) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 17), 'fn', comprehension_32130) str_32110 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 22), 'str', 'odepack') fn_32111 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 22, 33), 'fn', False) kwargs_32112 = {} join_32109 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 22, 17), 'join', False) join_call_result_32113 = invoke(stypy.reporting.localization. Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111], **kwargs_32112) list_32131 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 17), 'list') set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 17), list_32131, join_call_result_32113) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 4), 'lsoda_src', list_32131) list_32132 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 15), 'list') str_32134 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 21), 'str', 'odepack') str_32135 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 32), 'str', 'vode.f') kwargs_32136 = {} join_32133 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 16), 'join', False) join_call_result_32137 = invoke(stypy.reporting.localization. Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135], **kwargs_32136) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32137) str_32139 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 48), 'str', 'odepack') str_32140 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 59), 'str', 'zvode.f') kwargs_32141 = {} join_32138 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 43), 'join', False) join_call_result_32142 = invoke(stypy.reporting.localization. Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140], **kwargs_32141) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32142) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 28, 4), 'vode_src', list_32132) list_32143 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 14), 'list') str_32145 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 20), 'str', 'dop') str_32146 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 26), 'str', '*.f') kwargs_32147 = {} join_32144 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 29, 15), 'join', False) join_call_result_32148 = invoke(stypy.reporting.localization. Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146], **kwargs_32147) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 29, 14), list_32143, join_call_result_32148) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 29, 4), 'dop_src', list_32143) list_32149 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 24), 'list') str_32151 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 30), 'str', 'tests') str_32152 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 38), 'str', '_test_multivariate.c') kwargs_32153 = {} join_32150 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 30, 25), 'join', False) join_call_result_32154 = invoke(stypy.reporting.localization. Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152], **kwargs_32153) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 30, 24), list_32149, join_call_result_32154) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 30, 4), 'quadpack_test_src', list_32149) list_32155 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 29), 'list') str_32157 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 35), 'str', 'tests') str_32158 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f') kwargs_32159 = {} join_32156 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 31, 30), 'join', False) join_call_result_32160 = invoke(stypy.reporting.localization. Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158], **kwargs_32159) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 31, 29), list_32155, join_call_result_32160) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 31, 4), 'odeint_banded_test_src', list_32155) str_32163 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 33, 23), 'str', 'mach') mach_src_32164 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 39), 'mach_src', False) keyword_32165 = mach_src_32164 dict_32166 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 33), 'dict') str_32167 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 34), 'str', 'noopt') tuple_32168 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 43), 'tuple') file___32169 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 34, 43), '__file__', False) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, file___32169) int_32170 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 52), 'int') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, int_32170) set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 33), dict_32166, (str_32167, tuple_32168)) keyword_32171 = dict_32166 kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171} config_32161 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 4), 'config', False) add_library_32162 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 33, 4), config_32161, 'add_library') add_library_call_result_32173 = invoke(stypy.reporting.localization. Localization(__file__, 33, 4), add_library_32162, *[str_32163], ** kwargs_32172) str_32176 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 35, 23), 'str', 'quadpack') quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 43), 'quadpack_src', False) keyword_32178 = quadpack_src_32177 kwargs_32179 = {'sources': keyword_32178} config_32174 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 4), 'config', False) add_library_32175 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 35, 4), config_32174, 'add_library') add_library_call_result_32180 = invoke(stypy.reporting.localization. Localization(__file__, 35, 4), add_library_32175, *[str_32176], ** kwargs_32179) str_32183 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 36, 23), 'str', 'lsoda') lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 40), 'lsoda_src', False) keyword_32185 = lsoda_src_32184 kwargs_32186 = {'sources': keyword_32185} config_32181 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 4), 'config', False) add_library_32182 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 36, 4), config_32181, 'add_library') add_library_call_result_32187 = invoke(stypy.reporting.localization. Localization(__file__, 36, 4), add_library_32182, *[str_32183], ** kwargs_32186) str_32190 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 37, 23), 'str', 'vode') vode_src_32191 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 39), 'vode_src', False) keyword_32192 = vode_src_32191 kwargs_32193 = {'sources': keyword_32192} config_32188 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 4), 'config', False) add_library_32189 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 37, 4), config_32188, 'add_library') add_library_call_result_32194 = invoke(stypy.reporting.localization. Localization(__file__, 37, 4), add_library_32189, *[str_32190], ** kwargs_32193) str_32197 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 38, 23), 'str', 'dop') dop_src_32198 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 38), 'dop_src', False) keyword_32199 = dop_src_32198 kwargs_32200 = {'sources': keyword_32199} config_32195 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 4), 'config', False) add_library_32196 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 38, 4), config_32195, 'add_library') add_library_call_result_32201 = invoke(stypy.reporting.localization. Localization(__file__, 38, 4), add_library_32196, *[str_32197], ** kwargs_32200) list_32202 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 19), 'list') file___32207 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 42, 41), '__file__', False) kwargs_32208 = {} os_32204 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 42, 25), 'os', False) path_32205 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), os_32204, 'path') dirname_32206 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), path_32205, 'dirname') dirname_call_result_32209 = invoke(stypy.reporting.localization. Localization(__file__, 42, 25), dirname_32206, *[file___32207], ** kwargs_32208) str_32210 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 52), 'str', '..') str_32211 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 58), 'str', '_lib') str_32212 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 66), 'str', 'src') kwargs_32213 = {} join_32203 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 42, 20), 'join', False) join_call_result_32214 = invoke(stypy.reporting.localization. Localization(__file__, 42, 20), join_32203, *[ dirname_call_result_32209, str_32210, str_32211, str_32212], ** kwargs_32213) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 42, 19), list_32202, join_call_result_32214) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 42, 4), 'include_dirs', list_32202) str_32215 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 43, 7), 'str', 'include_dirs') lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 43, 25), 'lapack_opt') result_contains_32217 = python_operator(stypy.reporting.localization. Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216) if_condition_32218 = is_suitable_condition(stypy.reporting.localization .Localization(__file__, 43, 4), result_contains_32217) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 43, 4), 'if_condition_32218', if_condition_32218) module_type_store = SSAContext.create_ssa_context(module_type_store, 'if') lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 44, 26), 'lapack_opt', False) kwargs_32221 = {} dict_32219 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 44, 21), 'dict', False) dict_call_result_32222 = invoke(stypy.reporting.localization. Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], ** kwargs_32221) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 44, 8), 'lapack_opt', dict_call_result_32222) str_32227 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 45, 43), 'str', 'include_dirs') kwargs_32228 = {} lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 28), 'lapack_opt', False) pop_32226 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop') pop_call_result_32229 = invoke(stypy.reporting.localization. Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228 ) kwargs_32230 = {} include_dirs_32223 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 8), 'include_dirs', False) extend_32224 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 8), include_dirs_32223, 'extend') extend_call_result_32231 = invoke(stypy.reporting.localization. Localization(__file__, 45, 8), extend_32224, *[ pop_call_result_32229], **kwargs_32230) module_type_store = module_type_store.join_ssa_context() str_32234 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 47, 25), 'str', '_quadpack') list_32235 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 33), 'list') str_32236 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c' ) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 48, 33), list_32235, str_32236) keyword_32237 = list_32235 list_32238 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 35), 'list') str_32239 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 36), 'str', 'quadpack') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32239) str_32240 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 48), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32240) lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 49, 58), 'lapack_libs', False) result_add_32242 = python_operator(stypy.reporting.localization. Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241) keyword_32243 = result_add_32242 list_32244 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 34), 'list') str_32245 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 35), 'str', '__quadpack.h') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 50, 34), list_32244, str_32245) quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 36), 'quadpack_src', False) result_add_32247 = python_operator(stypy.reporting.localization. Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246) mach_src_32248 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 51), 'mach_src', False) result_add_32249 = python_operator(stypy.reporting.localization. Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248) keyword_32250 = result_add_32249 include_dirs_32251 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 52, 38), 'include_dirs', False) keyword_32252 = include_dirs_32251 lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 53, 27), 'lapack_opt', False) kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237, 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253, 'include_dirs': keyword_32252} config_32232 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 47, 4), 'config', False) add_extension_32233 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 47, 4), config_32232, 'add_extension') add_extension_call_result_32255 = invoke(stypy.reporting.localization. Localization(__file__, 47, 4), add_extension_32233, *[str_32234], **kwargs_32254) kwargs_32258 = {} lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 56, 19), 'lapack_opt', False) copy_32257 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy') copy_call_result_32259 = invoke(stypy.reporting.localization. Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 56, 4), 'odepack_opts', copy_call_result_32259) numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False) kwargs_32263 = {} odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 4), 'odepack_opts', False) update_32261 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 57, 4), odepack_opts_32260, 'update') update_call_result_32264 = invoke(stypy.reporting.localization. Localization(__file__, 57, 4), update_32261, *[ numpy_nodepr_api_32262], **kwargs_32263) str_32267 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 58, 25), 'str', '_odepack') list_32268 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 33), 'list') str_32269 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 59, 33), list_32268, str_32269) keyword_32270 = list_32268 list_32271 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 35), 'list') str_32272 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32272) str_32273 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32273) lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 60, 55), 'lapack_libs', False) result_add_32275 = python_operator(stypy.reporting.localization. Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274) keyword_32276 = result_add_32275 lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 34), 'lsoda_src', False) mach_src_32278 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 46), 'mach_src', False) result_add_32279 = python_operator(stypy.reporting.localization. Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278) keyword_32280 = result_add_32279 odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 62, 27), 'odepack_opts', False) kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270, 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281} config_32265 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 58, 4), 'config', False) add_extension_32266 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 58, 4), config_32265, 'add_extension') add_extension_call_result_32283 = invoke(stypy.reporting.localization. Localization(__file__, 58, 4), add_extension_32266, *[str_32267], **kwargs_32282) str_32286 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 65, 25), 'str', 'vode') list_32287 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 33), 'list') str_32288 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 34), 'str', 'vode.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 66, 33), list_32287, str_32288) keyword_32289 = list_32287 list_32290 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 35), 'list') str_32291 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 36), 'str', 'vode') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 67, 35), list_32290, str_32291) lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 67, 46), 'lapack_libs', False) result_add_32293 = python_operator(stypy.reporting.localization. Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292) keyword_32294 = result_add_32293 vode_src_32295 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 68, 33), 'vode_src', False) keyword_32296 = vode_src_32295 lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 69, 27), 'lapack_opt', False) kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289, 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297} config_32284 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 65, 4), 'config', False) add_extension_32285 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 65, 4), config_32284, 'add_extension') add_extension_call_result_32299 = invoke(stypy.reporting.localization. Localization(__file__, 65, 4), add_extension_32285, *[str_32286], **kwargs_32298) str_32302 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 72, 25), 'str', 'lsoda') list_32303 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 33), 'list') str_32304 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 73, 33), list_32303, str_32304) keyword_32305 = list_32303 list_32306 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 35), 'list') str_32307 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32307) str_32308 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32308) lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 74, 55), 'lapack_libs', False) result_add_32310 = python_operator(stypy.reporting.localization. Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309) keyword_32311 = result_add_32310 lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 34), 'lsoda_src', False) mach_src_32313 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 46), 'mach_src', False) result_add_32314 = python_operator(stypy.reporting.localization. Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313) keyword_32315 = result_add_32314 lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 76, 27), 'lapack_opt', False) kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305, 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316} config_32300 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 72, 4), 'config', False) add_extension_32301 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 72, 4), config_32300, 'add_extension') add_extension_call_result_32318 = invoke(stypy.reporting.localization. Localization(__file__, 72, 4), add_extension_32301, *[str_32302], **kwargs_32317) str_32321 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 79, 25), 'str', '_dop') list_32322 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 33), 'list') str_32323 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 34), 'str', 'dop.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 80, 33), list_32322, str_32323) keyword_32324 = list_32322 list_32325 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 35), 'list') str_32326 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 36), 'str', 'dop') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 81, 35), list_32325, str_32326) keyword_32327 = list_32325 dop_src_32328 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 82, 33), 'dop_src', False) keyword_32329 = dop_src_32328 kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324, 'depends': keyword_32329} config_32319 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 79, 4), 'config', False) add_extension_32320 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 79, 4), config_32319, 'add_extension') add_extension_call_result_32331 = invoke(stypy.reporting.localization. Localization(__file__, 79, 4), add_extension_32320, *[str_32321], **kwargs_32330) str_32334 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 84, 25), 'str', '_test_multivariate') quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 85, 33), 'quadpack_test_src', False) keyword_32336 = quadpack_test_src_32335 kwargs_32337 = {'sources': keyword_32336} config_32332 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 84, 4), 'config', False) add_extension_32333 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 84, 4), config_32332, 'add_extension') add_extension_call_result_32338 = invoke(stypy.reporting.localization. Localization(__file__, 84, 4), add_extension_32333, *[str_32334], **kwargs_32337) str_32341 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 88, 25), 'str', '_test_odeint_banded') odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy. reporting.localization.Localization(__file__, 89, 33), 'odeint_banded_test_src', False) keyword_32343 = odeint_banded_test_src_32342 list_32344 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 35), 'list') str_32345 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32345) str_32346 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32346) lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 90, 55), 'lapack_libs', False) result_add_32348 = python_operator(stypy.reporting.localization. Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347) keyword_32349 = result_add_32348 lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 34), 'lsoda_src', False) mach_src_32351 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 46), 'mach_src', False) result_add_32352 = python_operator(stypy.reporting.localization. Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351) keyword_32353 = result_add_32352 lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 92, 27), 'lapack_opt', False) kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343, 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354} config_32339 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 88, 4), 'config', False) add_extension_32340 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 88, 4), config_32339, 'add_extension') add_extension_call_result_32356 = invoke(stypy.reporting.localization. Localization(__file__, 88, 4), add_extension_32340, *[str_32341], **kwargs_32355) str_32359 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 94, 26), 'str', '_ivp') kwargs_32360 = {} config_32357 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 94, 4), 'config', False) add_subpackage_32358 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 94, 4), config_32357, 'add_subpackage') add_subpackage_call_result_32361 = invoke(stypy.reporting.localization. Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359], **kwargs_32360) str_32364 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 96, 24), 'str', 'tests') kwargs_32365 = {} config_32362 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 96, 4), 'config', False) add_data_dir_32363 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 96, 4), config_32362, 'add_data_dir') add_data_dir_call_result_32366 = invoke(stypy.reporting.localization. Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], ** kwargs_32365) config_32367 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 97, 11), 'config') module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 97, 4), 'stypy_return_type', config_32367) teardown_call_information(localization, arguments) stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 9, 0), 'stypy_return_type') module_type_store.store_return_type_of_current_context( stypy_return_type_32368) module_type_store = module_type_store.close_function_context() return stypy_return_type_32368 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 3, 0)) <|reserved_special_token_0|> import_module(stypy.reporting.localization.Localization(__file__, 3, 0), 'os', os, module_type_store) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 4, 0)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') <|reserved_special_token_0|> if type(import_32066) is not StypyTypeError: if import_32066 != 'pyd_module': __import__(import_32066) sys_modules_32067 = sys.modules[import_32066] import_from_module(stypy.reporting.localization.Localization( __file__, 4, 0), 'os.path', sys_modules_32067.module_type_store, module_type_store, ['join']) nest_module(stypy.reporting.localization.Localization(__file__, 4, 0), __file__, sys_modules_32067, sys_modules_32067. module_type_store, module_type_store) else: from os.path import join import_from_module(stypy.reporting.localization.Localization( __file__, 4, 0), 'os.path', None, module_type_store, ['join'], [join]) else: module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 4, 0), 'os.path', import_32066) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 6, 0)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') <|reserved_special_token_0|> if type(import_32068) is not StypyTypeError: if import_32068 != 'pyd_module': __import__(import_32068) sys_modules_32069 = sys.modules[import_32068] import_from_module(stypy.reporting.localization.Localization( __file__, 6, 0), 'scipy._build_utils', sys_modules_32069. module_type_store, module_type_store, ['numpy_nodepr_api']) nest_module(stypy.reporting.localization.Localization(__file__, 6, 0), __file__, sys_modules_32069, sys_modules_32069. module_type_store, module_type_store) else: from scipy._build_utils import numpy_nodepr_api import_from_module(stypy.reporting.localization.Localization( __file__, 6, 0), 'scipy._build_utils', None, module_type_store, ['numpy_nodepr_api'], [numpy_nodepr_api]) else: module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 6, 0), 'scipy._build_utils', import_32068) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') @norecursion def configuration(localization, *varargs, **kwargs): global module_type_store str_32070 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 9, 33), 'str', '') None_32071 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 9, 45), 'None') defaults = [str_32070, None_32071] module_type_store = module_type_store.open_function_context('configuration' , 9, 0, False) configuration.stypy_localization = localization configuration.stypy_type_of_self = None configuration.stypy_type_store = module_type_store configuration.stypy_function_name = 'configuration' configuration.stypy_param_names_list = ['parent_package', 'top_path'] configuration.stypy_varargs_param_name = None configuration.stypy_kwargs_param_name = None configuration.stypy_call_defaults = defaults configuration.stypy_call_varargs = varargs configuration.stypy_call_kwargs = kwargs arguments = process_argument_values(localization, None, module_type_store, 'configuration', ['parent_package', 'top_path'], None, None, defaults, varargs, kwargs) if is_error_type(arguments): module_type_store = module_type_store.close_function_context() return arguments init_call_information(module_type_store, 'configuration', localization, ['parent_package', 'top_path'], arguments) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 0, 0), 'stypy_return_type', None) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 10, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32072 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util' ) if type(import_32072) is not StypyTypeError: if import_32072 != 'pyd_module': __import__(import_32072) sys_modules_32073 = sys.modules[import_32072] import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', sys_modules_32073.module_type_store, module_type_store, [ 'Configuration']) nest_module(stypy.reporting.localization.Localization(__file__, 10, 4), __file__, sys_modules_32073, sys_modules_32073. module_type_store, module_type_store) else: from numpy.distutils.misc_util import Configuration import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', None, module_type_store, ['Configuration'], [Configuration]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 10, 4), 'numpy.distutils.misc_util', import_32072) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 11, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32074 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info') if type(import_32074) is not StypyTypeError: if import_32074 != 'pyd_module': __import__(import_32074) sys_modules_32075 = sys.modules[import_32074] import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', sys_modules_32075.module_type_store, module_type_store, [ 'get_info']) nest_module(stypy.reporting.localization.Localization(__file__, 11, 4), __file__, sys_modules_32075, sys_modules_32075. module_type_store, module_type_store) else: from numpy.distutils.system_info import get_info import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', None, module_type_store, ['get_info'], [get_info]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 11, 4), 'numpy.distutils.system_info', import_32074) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') str_32077 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 12, 27), 'str', 'integrate') parent_package_32078 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 40), 'parent_package', False) top_path_32079 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 56), 'top_path', False) kwargs_32080 = {} Configuration_32076 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 13), 'Configuration', False) Configuration_call_result_32081 = invoke(stypy.reporting.localization. Localization(__file__, 12, 13), Configuration_32076, *[str_32077, parent_package_32078, top_path_32079], **kwargs_32080) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 12, 4), 'config', Configuration_call_result_32081) str_32084 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 31), 'str', 'lapack_opt') int_32085 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 60), 'int') keyword_32086 = int_32085 kwargs_32087 = {'notfound_action': keyword_32086} get_info_32083 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 15, 22), 'get_info', False) get_info_call_result_32088 = invoke(stypy.reporting.localization. Localization(__file__, 15, 22), get_info_32083, *[str_32084], ** kwargs_32087) kwargs_32089 = {} dict_32082 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 15, 17), 'dict', False) dict_call_result_32090 = invoke(stypy.reporting.localization. Localization(__file__, 15, 17), dict_32082, *[ get_info_call_result_32088], **kwargs_32089) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 15, 4), 'lapack_opt', dict_call_result_32090) str_32093 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 33), 'str', 'libraries') list_32094 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 46), 'list') kwargs_32095 = {} lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 18, 18), 'lapack_opt', False) pop_32092 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop') pop_call_result_32096 = invoke(stypy.reporting.localization. Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094], **kwargs_32095) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 18, 4), 'lapack_libs', pop_call_result_32096) list_32097 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 15), 'list') str_32099 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 21), 'str', 'mach') str_32100 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 28), 'str', '*.f') kwargs_32101 = {} join_32098 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 20, 16), 'join', False) join_call_result_32102 = invoke(stypy.reporting.localization. Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100], **kwargs_32101) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 20, 15), list_32097, join_call_result_32102) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 20, 4), 'mach_src', list_32097) list_32103 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 19), 'list') str_32105 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 25), 'str', 'quadpack') str_32106 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 37), 'str', '*.f') kwargs_32107 = {} join_32104 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 21, 20), 'join', False) join_call_result_32108 = invoke(stypy.reporting.localization. Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106], **kwargs_32107) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 21, 19), list_32103, join_call_result_32108) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 21, 4), 'quadpack_src', list_32103) list_32114 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 47), 'list') str_32115 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32115) str_32116 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 23), 'str', 'bnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32116) str_32117 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 34), 'str', 'cfode.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32117) str_32118 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 8), 'str', 'ewset.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32118) str_32119 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 19), 'str', 'fnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32119) str_32120 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 30), 'str', 'intdy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32120) str_32121 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 8), 'str', 'lsoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32121) str_32122 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 19), 'str', 'prja.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32122) str_32123 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 29), 'str', 'solsy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32123) str_32124 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 40), 'str', 'srcma.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32124) str_32125 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 8), 'str', 'stoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32125) str_32126 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32126) str_32127 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32127) str_32128 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 43), 'str', 'xsetf.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32128) str_32129 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 27, 8), 'str', 'xsetun.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32129) comprehension_32130 = get_contained_elements_type(stypy.reporting. localization.Localization(__file__, 22, 17), list_32114) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 17), 'fn', comprehension_32130) str_32110 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 22), 'str', 'odepack') fn_32111 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 22, 33), 'fn', False) kwargs_32112 = {} join_32109 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 22, 17), 'join', False) join_call_result_32113 = invoke(stypy.reporting.localization. Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111], **kwargs_32112) list_32131 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 17), 'list') set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 17), list_32131, join_call_result_32113) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 4), 'lsoda_src', list_32131) list_32132 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 15), 'list') str_32134 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 21), 'str', 'odepack') str_32135 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 32), 'str', 'vode.f') kwargs_32136 = {} join_32133 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 16), 'join', False) join_call_result_32137 = invoke(stypy.reporting.localization. Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135], **kwargs_32136) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32137) str_32139 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 48), 'str', 'odepack') str_32140 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 59), 'str', 'zvode.f') kwargs_32141 = {} join_32138 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 43), 'join', False) join_call_result_32142 = invoke(stypy.reporting.localization. Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140], **kwargs_32141) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32142) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 28, 4), 'vode_src', list_32132) list_32143 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 14), 'list') str_32145 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 20), 'str', 'dop') str_32146 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 26), 'str', '*.f') kwargs_32147 = {} join_32144 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 29, 15), 'join', False) join_call_result_32148 = invoke(stypy.reporting.localization. Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146], **kwargs_32147) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 29, 14), list_32143, join_call_result_32148) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 29, 4), 'dop_src', list_32143) list_32149 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 24), 'list') str_32151 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 30), 'str', 'tests') str_32152 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 38), 'str', '_test_multivariate.c') kwargs_32153 = {} join_32150 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 30, 25), 'join', False) join_call_result_32154 = invoke(stypy.reporting.localization. Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152], **kwargs_32153) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 30, 24), list_32149, join_call_result_32154) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 30, 4), 'quadpack_test_src', list_32149) list_32155 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 29), 'list') str_32157 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 35), 'str', 'tests') str_32158 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f') kwargs_32159 = {} join_32156 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 31, 30), 'join', False) join_call_result_32160 = invoke(stypy.reporting.localization. Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158], **kwargs_32159) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 31, 29), list_32155, join_call_result_32160) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 31, 4), 'odeint_banded_test_src', list_32155) str_32163 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 33, 23), 'str', 'mach') mach_src_32164 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 39), 'mach_src', False) keyword_32165 = mach_src_32164 dict_32166 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 33), 'dict') str_32167 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 34), 'str', 'noopt') tuple_32168 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 43), 'tuple') file___32169 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 34, 43), '__file__', False) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, file___32169) int_32170 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 52), 'int') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, int_32170) set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 33), dict_32166, (str_32167, tuple_32168)) keyword_32171 = dict_32166 kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171} config_32161 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 4), 'config', False) add_library_32162 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 33, 4), config_32161, 'add_library') add_library_call_result_32173 = invoke(stypy.reporting.localization. Localization(__file__, 33, 4), add_library_32162, *[str_32163], ** kwargs_32172) str_32176 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 35, 23), 'str', 'quadpack') quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 43), 'quadpack_src', False) keyword_32178 = quadpack_src_32177 kwargs_32179 = {'sources': keyword_32178} config_32174 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 4), 'config', False) add_library_32175 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 35, 4), config_32174, 'add_library') add_library_call_result_32180 = invoke(stypy.reporting.localization. Localization(__file__, 35, 4), add_library_32175, *[str_32176], ** kwargs_32179) str_32183 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 36, 23), 'str', 'lsoda') lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 40), 'lsoda_src', False) keyword_32185 = lsoda_src_32184 kwargs_32186 = {'sources': keyword_32185} config_32181 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 4), 'config', False) add_library_32182 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 36, 4), config_32181, 'add_library') add_library_call_result_32187 = invoke(stypy.reporting.localization. Localization(__file__, 36, 4), add_library_32182, *[str_32183], ** kwargs_32186) str_32190 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 37, 23), 'str', 'vode') vode_src_32191 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 39), 'vode_src', False) keyword_32192 = vode_src_32191 kwargs_32193 = {'sources': keyword_32192} config_32188 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 4), 'config', False) add_library_32189 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 37, 4), config_32188, 'add_library') add_library_call_result_32194 = invoke(stypy.reporting.localization. Localization(__file__, 37, 4), add_library_32189, *[str_32190], ** kwargs_32193) str_32197 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 38, 23), 'str', 'dop') dop_src_32198 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 38), 'dop_src', False) keyword_32199 = dop_src_32198 kwargs_32200 = {'sources': keyword_32199} config_32195 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 4), 'config', False) add_library_32196 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 38, 4), config_32195, 'add_library') add_library_call_result_32201 = invoke(stypy.reporting.localization. Localization(__file__, 38, 4), add_library_32196, *[str_32197], ** kwargs_32200) list_32202 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 19), 'list') file___32207 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 42, 41), '__file__', False) kwargs_32208 = {} os_32204 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 42, 25), 'os', False) path_32205 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), os_32204, 'path') dirname_32206 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), path_32205, 'dirname') dirname_call_result_32209 = invoke(stypy.reporting.localization. Localization(__file__, 42, 25), dirname_32206, *[file___32207], ** kwargs_32208) str_32210 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 52), 'str', '..') str_32211 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 58), 'str', '_lib') str_32212 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 66), 'str', 'src') kwargs_32213 = {} join_32203 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 42, 20), 'join', False) join_call_result_32214 = invoke(stypy.reporting.localization. Localization(__file__, 42, 20), join_32203, *[ dirname_call_result_32209, str_32210, str_32211, str_32212], ** kwargs_32213) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 42, 19), list_32202, join_call_result_32214) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 42, 4), 'include_dirs', list_32202) str_32215 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 43, 7), 'str', 'include_dirs') lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 43, 25), 'lapack_opt') result_contains_32217 = python_operator(stypy.reporting.localization. Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216) if_condition_32218 = is_suitable_condition(stypy.reporting.localization .Localization(__file__, 43, 4), result_contains_32217) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 43, 4), 'if_condition_32218', if_condition_32218) module_type_store = SSAContext.create_ssa_context(module_type_store, 'if') lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 44, 26), 'lapack_opt', False) kwargs_32221 = {} dict_32219 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 44, 21), 'dict', False) dict_call_result_32222 = invoke(stypy.reporting.localization. Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], ** kwargs_32221) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 44, 8), 'lapack_opt', dict_call_result_32222) str_32227 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 45, 43), 'str', 'include_dirs') kwargs_32228 = {} lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 28), 'lapack_opt', False) pop_32226 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop') pop_call_result_32229 = invoke(stypy.reporting.localization. Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228 ) kwargs_32230 = {} include_dirs_32223 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 8), 'include_dirs', False) extend_32224 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 8), include_dirs_32223, 'extend') extend_call_result_32231 = invoke(stypy.reporting.localization. Localization(__file__, 45, 8), extend_32224, *[ pop_call_result_32229], **kwargs_32230) module_type_store = module_type_store.join_ssa_context() str_32234 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 47, 25), 'str', '_quadpack') list_32235 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 33), 'list') str_32236 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c' ) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 48, 33), list_32235, str_32236) keyword_32237 = list_32235 list_32238 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 35), 'list') str_32239 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 36), 'str', 'quadpack') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32239) str_32240 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 48), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32240) lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 49, 58), 'lapack_libs', False) result_add_32242 = python_operator(stypy.reporting.localization. Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241) keyword_32243 = result_add_32242 list_32244 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 34), 'list') str_32245 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 35), 'str', '__quadpack.h') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 50, 34), list_32244, str_32245) quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 36), 'quadpack_src', False) result_add_32247 = python_operator(stypy.reporting.localization. Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246) mach_src_32248 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 51), 'mach_src', False) result_add_32249 = python_operator(stypy.reporting.localization. Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248) keyword_32250 = result_add_32249 include_dirs_32251 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 52, 38), 'include_dirs', False) keyword_32252 = include_dirs_32251 lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 53, 27), 'lapack_opt', False) kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237, 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253, 'include_dirs': keyword_32252} config_32232 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 47, 4), 'config', False) add_extension_32233 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 47, 4), config_32232, 'add_extension') add_extension_call_result_32255 = invoke(stypy.reporting.localization. Localization(__file__, 47, 4), add_extension_32233, *[str_32234], **kwargs_32254) kwargs_32258 = {} lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 56, 19), 'lapack_opt', False) copy_32257 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy') copy_call_result_32259 = invoke(stypy.reporting.localization. Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 56, 4), 'odepack_opts', copy_call_result_32259) numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False) kwargs_32263 = {} odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 4), 'odepack_opts', False) update_32261 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 57, 4), odepack_opts_32260, 'update') update_call_result_32264 = invoke(stypy.reporting.localization. Localization(__file__, 57, 4), update_32261, *[ numpy_nodepr_api_32262], **kwargs_32263) str_32267 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 58, 25), 'str', '_odepack') list_32268 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 33), 'list') str_32269 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 59, 33), list_32268, str_32269) keyword_32270 = list_32268 list_32271 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 35), 'list') str_32272 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32272) str_32273 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32273) lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 60, 55), 'lapack_libs', False) result_add_32275 = python_operator(stypy.reporting.localization. Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274) keyword_32276 = result_add_32275 lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 34), 'lsoda_src', False) mach_src_32278 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 46), 'mach_src', False) result_add_32279 = python_operator(stypy.reporting.localization. Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278) keyword_32280 = result_add_32279 odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 62, 27), 'odepack_opts', False) kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270, 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281} config_32265 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 58, 4), 'config', False) add_extension_32266 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 58, 4), config_32265, 'add_extension') add_extension_call_result_32283 = invoke(stypy.reporting.localization. Localization(__file__, 58, 4), add_extension_32266, *[str_32267], **kwargs_32282) str_32286 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 65, 25), 'str', 'vode') list_32287 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 33), 'list') str_32288 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 34), 'str', 'vode.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 66, 33), list_32287, str_32288) keyword_32289 = list_32287 list_32290 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 35), 'list') str_32291 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 36), 'str', 'vode') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 67, 35), list_32290, str_32291) lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 67, 46), 'lapack_libs', False) result_add_32293 = python_operator(stypy.reporting.localization. Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292) keyword_32294 = result_add_32293 vode_src_32295 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 68, 33), 'vode_src', False) keyword_32296 = vode_src_32295 lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 69, 27), 'lapack_opt', False) kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289, 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297} config_32284 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 65, 4), 'config', False) add_extension_32285 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 65, 4), config_32284, 'add_extension') add_extension_call_result_32299 = invoke(stypy.reporting.localization. Localization(__file__, 65, 4), add_extension_32285, *[str_32286], **kwargs_32298) str_32302 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 72, 25), 'str', 'lsoda') list_32303 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 33), 'list') str_32304 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 73, 33), list_32303, str_32304) keyword_32305 = list_32303 list_32306 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 35), 'list') str_32307 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32307) str_32308 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32308) lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 74, 55), 'lapack_libs', False) result_add_32310 = python_operator(stypy.reporting.localization. Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309) keyword_32311 = result_add_32310 lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 34), 'lsoda_src', False) mach_src_32313 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 46), 'mach_src', False) result_add_32314 = python_operator(stypy.reporting.localization. Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313) keyword_32315 = result_add_32314 lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 76, 27), 'lapack_opt', False) kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305, 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316} config_32300 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 72, 4), 'config', False) add_extension_32301 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 72, 4), config_32300, 'add_extension') add_extension_call_result_32318 = invoke(stypy.reporting.localization. Localization(__file__, 72, 4), add_extension_32301, *[str_32302], **kwargs_32317) str_32321 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 79, 25), 'str', '_dop') list_32322 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 33), 'list') str_32323 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 34), 'str', 'dop.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 80, 33), list_32322, str_32323) keyword_32324 = list_32322 list_32325 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 35), 'list') str_32326 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 36), 'str', 'dop') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 81, 35), list_32325, str_32326) keyword_32327 = list_32325 dop_src_32328 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 82, 33), 'dop_src', False) keyword_32329 = dop_src_32328 kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324, 'depends': keyword_32329} config_32319 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 79, 4), 'config', False) add_extension_32320 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 79, 4), config_32319, 'add_extension') add_extension_call_result_32331 = invoke(stypy.reporting.localization. Localization(__file__, 79, 4), add_extension_32320, *[str_32321], **kwargs_32330) str_32334 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 84, 25), 'str', '_test_multivariate') quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 85, 33), 'quadpack_test_src', False) keyword_32336 = quadpack_test_src_32335 kwargs_32337 = {'sources': keyword_32336} config_32332 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 84, 4), 'config', False) add_extension_32333 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 84, 4), config_32332, 'add_extension') add_extension_call_result_32338 = invoke(stypy.reporting.localization. Localization(__file__, 84, 4), add_extension_32333, *[str_32334], **kwargs_32337) str_32341 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 88, 25), 'str', '_test_odeint_banded') odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy. reporting.localization.Localization(__file__, 89, 33), 'odeint_banded_test_src', False) keyword_32343 = odeint_banded_test_src_32342 list_32344 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 35), 'list') str_32345 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32345) str_32346 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32346) lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 90, 55), 'lapack_libs', False) result_add_32348 = python_operator(stypy.reporting.localization. Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347) keyword_32349 = result_add_32348 lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 34), 'lsoda_src', False) mach_src_32351 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 46), 'mach_src', False) result_add_32352 = python_operator(stypy.reporting.localization. Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351) keyword_32353 = result_add_32352 lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 92, 27), 'lapack_opt', False) kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343, 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354} config_32339 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 88, 4), 'config', False) add_extension_32340 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 88, 4), config_32339, 'add_extension') add_extension_call_result_32356 = invoke(stypy.reporting.localization. Localization(__file__, 88, 4), add_extension_32340, *[str_32341], **kwargs_32355) str_32359 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 94, 26), 'str', '_ivp') kwargs_32360 = {} config_32357 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 94, 4), 'config', False) add_subpackage_32358 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 94, 4), config_32357, 'add_subpackage') add_subpackage_call_result_32361 = invoke(stypy.reporting.localization. Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359], **kwargs_32360) str_32364 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 96, 24), 'str', 'tests') kwargs_32365 = {} config_32362 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 96, 4), 'config', False) add_data_dir_32363 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 96, 4), config_32362, 'add_data_dir') add_data_dir_call_result_32366 = invoke(stypy.reporting.localization. Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], ** kwargs_32365) config_32367 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 97, 11), 'config') module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 97, 4), 'stypy_return_type', config_32367) teardown_call_information(localization, arguments) stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 9, 0), 'stypy_return_type') module_type_store.store_return_type_of_current_context( stypy_return_type_32368) module_type_store = module_type_store.close_function_context() return stypy_return_type_32368 module_type_store.set_type_of(stypy.reporting.localization.Localization( __file__, 9, 0), 'configuration', configuration) if __name__ == '__main__': stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 101, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32369 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 101, 4), 'numpy.distutils.core') if type(import_32369) is not StypyTypeError: if import_32369 != 'pyd_module': __import__(import_32369) sys_modules_32370 = sys.modules[import_32369] import_from_module(stypy.reporting.localization.Localization( __file__, 101, 4), 'numpy.distutils.core', sys_modules_32370.module_type_store, module_type_store, [ 'setup']) nest_module(stypy.reporting.localization.Localization(__file__, 101, 4), __file__, sys_modules_32370, sys_modules_32370. module_type_store, module_type_store) else: from numpy.distutils.core import setup import_from_module(stypy.reporting.localization.Localization( __file__, 101, 4), 'numpy.distutils.core', None, module_type_store, ['setup'], [setup]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 101, 4), 'numpy.distutils.core', import_32369) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') kwargs_32378 = {} str_32373 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 102, 35), 'str', '') keyword_32374 = str_32373 kwargs_32375 = {'top_path': keyword_32374} configuration_32372 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 102, 12), 'configuration', False) configuration_call_result_32376 = invoke(stypy.reporting.localization. Localization(__file__, 102, 12), configuration_32372, *[], ** kwargs_32375) todict_32377 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 102, 12), configuration_call_result_32376, 'todict') todict_call_result_32379 = invoke(stypy.reporting.localization. Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378) kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379} setup_32371 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 102, 4), 'setup', False) setup_call_result_32381 = invoke(stypy.reporting.localization. Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> module_type_store = Context(None, __file__) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 3, 0)) <|reserved_special_token_0|> import_module(stypy.reporting.localization.Localization(__file__, 3, 0), 'os', os, module_type_store) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 4, 0)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32066 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 4, 0), 'os.path') if type(import_32066) is not StypyTypeError: if import_32066 != 'pyd_module': __import__(import_32066) sys_modules_32067 = sys.modules[import_32066] import_from_module(stypy.reporting.localization.Localization( __file__, 4, 0), 'os.path', sys_modules_32067.module_type_store, module_type_store, ['join']) nest_module(stypy.reporting.localization.Localization(__file__, 4, 0), __file__, sys_modules_32067, sys_modules_32067. module_type_store, module_type_store) else: from os.path import join import_from_module(stypy.reporting.localization.Localization( __file__, 4, 0), 'os.path', None, module_type_store, ['join'], [join]) else: module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 4, 0), 'os.path', import_32066) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 6, 0)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32068 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 6, 0), 'scipy._build_utils') if type(import_32068) is not StypyTypeError: if import_32068 != 'pyd_module': __import__(import_32068) sys_modules_32069 = sys.modules[import_32068] import_from_module(stypy.reporting.localization.Localization( __file__, 6, 0), 'scipy._build_utils', sys_modules_32069. module_type_store, module_type_store, ['numpy_nodepr_api']) nest_module(stypy.reporting.localization.Localization(__file__, 6, 0), __file__, sys_modules_32069, sys_modules_32069. module_type_store, module_type_store) else: from scipy._build_utils import numpy_nodepr_api import_from_module(stypy.reporting.localization.Localization( __file__, 6, 0), 'scipy._build_utils', None, module_type_store, ['numpy_nodepr_api'], [numpy_nodepr_api]) else: module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 6, 0), 'scipy._build_utils', import_32068) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') @norecursion def configuration(localization, *varargs, **kwargs): global module_type_store str_32070 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 9, 33), 'str', '') None_32071 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 9, 45), 'None') defaults = [str_32070, None_32071] module_type_store = module_type_store.open_function_context('configuration' , 9, 0, False) configuration.stypy_localization = localization configuration.stypy_type_of_self = None configuration.stypy_type_store = module_type_store configuration.stypy_function_name = 'configuration' configuration.stypy_param_names_list = ['parent_package', 'top_path'] configuration.stypy_varargs_param_name = None configuration.stypy_kwargs_param_name = None configuration.stypy_call_defaults = defaults configuration.stypy_call_varargs = varargs configuration.stypy_call_kwargs = kwargs arguments = process_argument_values(localization, None, module_type_store, 'configuration', ['parent_package', 'top_path'], None, None, defaults, varargs, kwargs) if is_error_type(arguments): module_type_store = module_type_store.close_function_context() return arguments init_call_information(module_type_store, 'configuration', localization, ['parent_package', 'top_path'], arguments) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 0, 0), 'stypy_return_type', None) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 10, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32072 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util' ) if type(import_32072) is not StypyTypeError: if import_32072 != 'pyd_module': __import__(import_32072) sys_modules_32073 = sys.modules[import_32072] import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', sys_modules_32073.module_type_store, module_type_store, [ 'Configuration']) nest_module(stypy.reporting.localization.Localization(__file__, 10, 4), __file__, sys_modules_32073, sys_modules_32073. module_type_store, module_type_store) else: from numpy.distutils.misc_util import Configuration import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', None, module_type_store, ['Configuration'], [Configuration]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 10, 4), 'numpy.distutils.misc_util', import_32072) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 11, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32074 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info') if type(import_32074) is not StypyTypeError: if import_32074 != 'pyd_module': __import__(import_32074) sys_modules_32075 = sys.modules[import_32074] import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', sys_modules_32075.module_type_store, module_type_store, [ 'get_info']) nest_module(stypy.reporting.localization.Localization(__file__, 11, 4), __file__, sys_modules_32075, sys_modules_32075. module_type_store, module_type_store) else: from numpy.distutils.system_info import get_info import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', None, module_type_store, ['get_info'], [get_info]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 11, 4), 'numpy.distutils.system_info', import_32074) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') str_32077 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 12, 27), 'str', 'integrate') parent_package_32078 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 40), 'parent_package', False) top_path_32079 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 56), 'top_path', False) kwargs_32080 = {} Configuration_32076 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 13), 'Configuration', False) Configuration_call_result_32081 = invoke(stypy.reporting.localization. Localization(__file__, 12, 13), Configuration_32076, *[str_32077, parent_package_32078, top_path_32079], **kwargs_32080) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 12, 4), 'config', Configuration_call_result_32081) str_32084 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 31), 'str', 'lapack_opt') int_32085 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 60), 'int') keyword_32086 = int_32085 kwargs_32087 = {'notfound_action': keyword_32086} get_info_32083 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 15, 22), 'get_info', False) get_info_call_result_32088 = invoke(stypy.reporting.localization. Localization(__file__, 15, 22), get_info_32083, *[str_32084], ** kwargs_32087) kwargs_32089 = {} dict_32082 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 15, 17), 'dict', False) dict_call_result_32090 = invoke(stypy.reporting.localization. Localization(__file__, 15, 17), dict_32082, *[ get_info_call_result_32088], **kwargs_32089) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 15, 4), 'lapack_opt', dict_call_result_32090) str_32093 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 33), 'str', 'libraries') list_32094 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 46), 'list') kwargs_32095 = {} lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 18, 18), 'lapack_opt', False) pop_32092 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop') pop_call_result_32096 = invoke(stypy.reporting.localization. Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094], **kwargs_32095) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 18, 4), 'lapack_libs', pop_call_result_32096) list_32097 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 15), 'list') str_32099 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 21), 'str', 'mach') str_32100 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 28), 'str', '*.f') kwargs_32101 = {} join_32098 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 20, 16), 'join', False) join_call_result_32102 = invoke(stypy.reporting.localization. Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100], **kwargs_32101) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 20, 15), list_32097, join_call_result_32102) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 20, 4), 'mach_src', list_32097) list_32103 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 19), 'list') str_32105 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 25), 'str', 'quadpack') str_32106 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 37), 'str', '*.f') kwargs_32107 = {} join_32104 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 21, 20), 'join', False) join_call_result_32108 = invoke(stypy.reporting.localization. Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106], **kwargs_32107) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 21, 19), list_32103, join_call_result_32108) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 21, 4), 'quadpack_src', list_32103) list_32114 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 47), 'list') str_32115 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32115) str_32116 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 23), 'str', 'bnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32116) str_32117 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 34), 'str', 'cfode.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32117) str_32118 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 8), 'str', 'ewset.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32118) str_32119 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 19), 'str', 'fnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32119) str_32120 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 30), 'str', 'intdy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32120) str_32121 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 8), 'str', 'lsoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32121) str_32122 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 19), 'str', 'prja.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32122) str_32123 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 29), 'str', 'solsy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32123) str_32124 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 40), 'str', 'srcma.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32124) str_32125 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 8), 'str', 'stoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32125) str_32126 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32126) str_32127 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32127) str_32128 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 43), 'str', 'xsetf.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32128) str_32129 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 27, 8), 'str', 'xsetun.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32129) comprehension_32130 = get_contained_elements_type(stypy.reporting. localization.Localization(__file__, 22, 17), list_32114) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 17), 'fn', comprehension_32130) str_32110 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 22), 'str', 'odepack') fn_32111 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 22, 33), 'fn', False) kwargs_32112 = {} join_32109 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 22, 17), 'join', False) join_call_result_32113 = invoke(stypy.reporting.localization. Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111], **kwargs_32112) list_32131 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 17), 'list') set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 17), list_32131, join_call_result_32113) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 4), 'lsoda_src', list_32131) list_32132 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 15), 'list') str_32134 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 21), 'str', 'odepack') str_32135 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 32), 'str', 'vode.f') kwargs_32136 = {} join_32133 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 16), 'join', False) join_call_result_32137 = invoke(stypy.reporting.localization. Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135], **kwargs_32136) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32137) str_32139 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 48), 'str', 'odepack') str_32140 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 59), 'str', 'zvode.f') kwargs_32141 = {} join_32138 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 43), 'join', False) join_call_result_32142 = invoke(stypy.reporting.localization. Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140], **kwargs_32141) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32142) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 28, 4), 'vode_src', list_32132) list_32143 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 14), 'list') str_32145 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 20), 'str', 'dop') str_32146 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 26), 'str', '*.f') kwargs_32147 = {} join_32144 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 29, 15), 'join', False) join_call_result_32148 = invoke(stypy.reporting.localization. Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146], **kwargs_32147) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 29, 14), list_32143, join_call_result_32148) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 29, 4), 'dop_src', list_32143) list_32149 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 24), 'list') str_32151 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 30), 'str', 'tests') str_32152 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 38), 'str', '_test_multivariate.c') kwargs_32153 = {} join_32150 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 30, 25), 'join', False) join_call_result_32154 = invoke(stypy.reporting.localization. Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152], **kwargs_32153) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 30, 24), list_32149, join_call_result_32154) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 30, 4), 'quadpack_test_src', list_32149) list_32155 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 29), 'list') str_32157 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 35), 'str', 'tests') str_32158 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f') kwargs_32159 = {} join_32156 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 31, 30), 'join', False) join_call_result_32160 = invoke(stypy.reporting.localization. Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158], **kwargs_32159) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 31, 29), list_32155, join_call_result_32160) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 31, 4), 'odeint_banded_test_src', list_32155) str_32163 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 33, 23), 'str', 'mach') mach_src_32164 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 39), 'mach_src', False) keyword_32165 = mach_src_32164 dict_32166 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 33), 'dict') str_32167 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 34), 'str', 'noopt') tuple_32168 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 43), 'tuple') file___32169 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 34, 43), '__file__', False) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, file___32169) int_32170 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 52), 'int') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, int_32170) set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 33), dict_32166, (str_32167, tuple_32168)) keyword_32171 = dict_32166 kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171} config_32161 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 4), 'config', False) add_library_32162 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 33, 4), config_32161, 'add_library') add_library_call_result_32173 = invoke(stypy.reporting.localization. Localization(__file__, 33, 4), add_library_32162, *[str_32163], ** kwargs_32172) str_32176 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 35, 23), 'str', 'quadpack') quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 43), 'quadpack_src', False) keyword_32178 = quadpack_src_32177 kwargs_32179 = {'sources': keyword_32178} config_32174 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 4), 'config', False) add_library_32175 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 35, 4), config_32174, 'add_library') add_library_call_result_32180 = invoke(stypy.reporting.localization. Localization(__file__, 35, 4), add_library_32175, *[str_32176], ** kwargs_32179) str_32183 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 36, 23), 'str', 'lsoda') lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 40), 'lsoda_src', False) keyword_32185 = lsoda_src_32184 kwargs_32186 = {'sources': keyword_32185} config_32181 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 4), 'config', False) add_library_32182 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 36, 4), config_32181, 'add_library') add_library_call_result_32187 = invoke(stypy.reporting.localization. Localization(__file__, 36, 4), add_library_32182, *[str_32183], ** kwargs_32186) str_32190 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 37, 23), 'str', 'vode') vode_src_32191 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 39), 'vode_src', False) keyword_32192 = vode_src_32191 kwargs_32193 = {'sources': keyword_32192} config_32188 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 4), 'config', False) add_library_32189 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 37, 4), config_32188, 'add_library') add_library_call_result_32194 = invoke(stypy.reporting.localization. Localization(__file__, 37, 4), add_library_32189, *[str_32190], ** kwargs_32193) str_32197 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 38, 23), 'str', 'dop') dop_src_32198 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 38), 'dop_src', False) keyword_32199 = dop_src_32198 kwargs_32200 = {'sources': keyword_32199} config_32195 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 4), 'config', False) add_library_32196 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 38, 4), config_32195, 'add_library') add_library_call_result_32201 = invoke(stypy.reporting.localization. Localization(__file__, 38, 4), add_library_32196, *[str_32197], ** kwargs_32200) list_32202 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 19), 'list') file___32207 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 42, 41), '__file__', False) kwargs_32208 = {} os_32204 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 42, 25), 'os', False) path_32205 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), os_32204, 'path') dirname_32206 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), path_32205, 'dirname') dirname_call_result_32209 = invoke(stypy.reporting.localization. Localization(__file__, 42, 25), dirname_32206, *[file___32207], ** kwargs_32208) str_32210 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 52), 'str', '..') str_32211 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 58), 'str', '_lib') str_32212 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 66), 'str', 'src') kwargs_32213 = {} join_32203 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 42, 20), 'join', False) join_call_result_32214 = invoke(stypy.reporting.localization. Localization(__file__, 42, 20), join_32203, *[ dirname_call_result_32209, str_32210, str_32211, str_32212], ** kwargs_32213) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 42, 19), list_32202, join_call_result_32214) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 42, 4), 'include_dirs', list_32202) str_32215 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 43, 7), 'str', 'include_dirs') lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 43, 25), 'lapack_opt') result_contains_32217 = python_operator(stypy.reporting.localization. Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216) if_condition_32218 = is_suitable_condition(stypy.reporting.localization .Localization(__file__, 43, 4), result_contains_32217) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 43, 4), 'if_condition_32218', if_condition_32218) module_type_store = SSAContext.create_ssa_context(module_type_store, 'if') lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 44, 26), 'lapack_opt', False) kwargs_32221 = {} dict_32219 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 44, 21), 'dict', False) dict_call_result_32222 = invoke(stypy.reporting.localization. Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], ** kwargs_32221) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 44, 8), 'lapack_opt', dict_call_result_32222) str_32227 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 45, 43), 'str', 'include_dirs') kwargs_32228 = {} lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 28), 'lapack_opt', False) pop_32226 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop') pop_call_result_32229 = invoke(stypy.reporting.localization. Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228 ) kwargs_32230 = {} include_dirs_32223 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 8), 'include_dirs', False) extend_32224 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 8), include_dirs_32223, 'extend') extend_call_result_32231 = invoke(stypy.reporting.localization. Localization(__file__, 45, 8), extend_32224, *[ pop_call_result_32229], **kwargs_32230) module_type_store = module_type_store.join_ssa_context() str_32234 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 47, 25), 'str', '_quadpack') list_32235 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 33), 'list') str_32236 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c' ) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 48, 33), list_32235, str_32236) keyword_32237 = list_32235 list_32238 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 35), 'list') str_32239 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 36), 'str', 'quadpack') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32239) str_32240 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 48), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32240) lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 49, 58), 'lapack_libs', False) result_add_32242 = python_operator(stypy.reporting.localization. Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241) keyword_32243 = result_add_32242 list_32244 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 34), 'list') str_32245 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 35), 'str', '__quadpack.h') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 50, 34), list_32244, str_32245) quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 36), 'quadpack_src', False) result_add_32247 = python_operator(stypy.reporting.localization. Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246) mach_src_32248 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 51), 'mach_src', False) result_add_32249 = python_operator(stypy.reporting.localization. Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248) keyword_32250 = result_add_32249 include_dirs_32251 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 52, 38), 'include_dirs', False) keyword_32252 = include_dirs_32251 lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 53, 27), 'lapack_opt', False) kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237, 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253, 'include_dirs': keyword_32252} config_32232 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 47, 4), 'config', False) add_extension_32233 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 47, 4), config_32232, 'add_extension') add_extension_call_result_32255 = invoke(stypy.reporting.localization. Localization(__file__, 47, 4), add_extension_32233, *[str_32234], **kwargs_32254) kwargs_32258 = {} lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 56, 19), 'lapack_opt', False) copy_32257 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy') copy_call_result_32259 = invoke(stypy.reporting.localization. Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 56, 4), 'odepack_opts', copy_call_result_32259) numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False) kwargs_32263 = {} odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 4), 'odepack_opts', False) update_32261 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 57, 4), odepack_opts_32260, 'update') update_call_result_32264 = invoke(stypy.reporting.localization. Localization(__file__, 57, 4), update_32261, *[ numpy_nodepr_api_32262], **kwargs_32263) str_32267 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 58, 25), 'str', '_odepack') list_32268 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 33), 'list') str_32269 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 59, 33), list_32268, str_32269) keyword_32270 = list_32268 list_32271 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 35), 'list') str_32272 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32272) str_32273 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32273) lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 60, 55), 'lapack_libs', False) result_add_32275 = python_operator(stypy.reporting.localization. Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274) keyword_32276 = result_add_32275 lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 34), 'lsoda_src', False) mach_src_32278 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 46), 'mach_src', False) result_add_32279 = python_operator(stypy.reporting.localization. Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278) keyword_32280 = result_add_32279 odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 62, 27), 'odepack_opts', False) kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270, 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281} config_32265 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 58, 4), 'config', False) add_extension_32266 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 58, 4), config_32265, 'add_extension') add_extension_call_result_32283 = invoke(stypy.reporting.localization. Localization(__file__, 58, 4), add_extension_32266, *[str_32267], **kwargs_32282) str_32286 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 65, 25), 'str', 'vode') list_32287 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 33), 'list') str_32288 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 34), 'str', 'vode.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 66, 33), list_32287, str_32288) keyword_32289 = list_32287 list_32290 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 35), 'list') str_32291 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 36), 'str', 'vode') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 67, 35), list_32290, str_32291) lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 67, 46), 'lapack_libs', False) result_add_32293 = python_operator(stypy.reporting.localization. Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292) keyword_32294 = result_add_32293 vode_src_32295 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 68, 33), 'vode_src', False) keyword_32296 = vode_src_32295 lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 69, 27), 'lapack_opt', False) kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289, 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297} config_32284 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 65, 4), 'config', False) add_extension_32285 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 65, 4), config_32284, 'add_extension') add_extension_call_result_32299 = invoke(stypy.reporting.localization. Localization(__file__, 65, 4), add_extension_32285, *[str_32286], **kwargs_32298) str_32302 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 72, 25), 'str', 'lsoda') list_32303 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 33), 'list') str_32304 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 73, 33), list_32303, str_32304) keyword_32305 = list_32303 list_32306 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 35), 'list') str_32307 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32307) str_32308 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32308) lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 74, 55), 'lapack_libs', False) result_add_32310 = python_operator(stypy.reporting.localization. Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309) keyword_32311 = result_add_32310 lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 34), 'lsoda_src', False) mach_src_32313 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 46), 'mach_src', False) result_add_32314 = python_operator(stypy.reporting.localization. Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313) keyword_32315 = result_add_32314 lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 76, 27), 'lapack_opt', False) kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305, 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316} config_32300 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 72, 4), 'config', False) add_extension_32301 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 72, 4), config_32300, 'add_extension') add_extension_call_result_32318 = invoke(stypy.reporting.localization. Localization(__file__, 72, 4), add_extension_32301, *[str_32302], **kwargs_32317) str_32321 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 79, 25), 'str', '_dop') list_32322 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 33), 'list') str_32323 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 34), 'str', 'dop.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 80, 33), list_32322, str_32323) keyword_32324 = list_32322 list_32325 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 35), 'list') str_32326 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 36), 'str', 'dop') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 81, 35), list_32325, str_32326) keyword_32327 = list_32325 dop_src_32328 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 82, 33), 'dop_src', False) keyword_32329 = dop_src_32328 kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324, 'depends': keyword_32329} config_32319 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 79, 4), 'config', False) add_extension_32320 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 79, 4), config_32319, 'add_extension') add_extension_call_result_32331 = invoke(stypy.reporting.localization. Localization(__file__, 79, 4), add_extension_32320, *[str_32321], **kwargs_32330) str_32334 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 84, 25), 'str', '_test_multivariate') quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 85, 33), 'quadpack_test_src', False) keyword_32336 = quadpack_test_src_32335 kwargs_32337 = {'sources': keyword_32336} config_32332 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 84, 4), 'config', False) add_extension_32333 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 84, 4), config_32332, 'add_extension') add_extension_call_result_32338 = invoke(stypy.reporting.localization. Localization(__file__, 84, 4), add_extension_32333, *[str_32334], **kwargs_32337) str_32341 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 88, 25), 'str', '_test_odeint_banded') odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy. reporting.localization.Localization(__file__, 89, 33), 'odeint_banded_test_src', False) keyword_32343 = odeint_banded_test_src_32342 list_32344 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 35), 'list') str_32345 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32345) str_32346 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32346) lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 90, 55), 'lapack_libs', False) result_add_32348 = python_operator(stypy.reporting.localization. Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347) keyword_32349 = result_add_32348 lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 34), 'lsoda_src', False) mach_src_32351 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 46), 'mach_src', False) result_add_32352 = python_operator(stypy.reporting.localization. Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351) keyword_32353 = result_add_32352 lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 92, 27), 'lapack_opt', False) kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343, 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354} config_32339 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 88, 4), 'config', False) add_extension_32340 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 88, 4), config_32339, 'add_extension') add_extension_call_result_32356 = invoke(stypy.reporting.localization. Localization(__file__, 88, 4), add_extension_32340, *[str_32341], **kwargs_32355) str_32359 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 94, 26), 'str', '_ivp') kwargs_32360 = {} config_32357 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 94, 4), 'config', False) add_subpackage_32358 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 94, 4), config_32357, 'add_subpackage') add_subpackage_call_result_32361 = invoke(stypy.reporting.localization. Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359], **kwargs_32360) str_32364 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 96, 24), 'str', 'tests') kwargs_32365 = {} config_32362 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 96, 4), 'config', False) add_data_dir_32363 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 96, 4), config_32362, 'add_data_dir') add_data_dir_call_result_32366 = invoke(stypy.reporting.localization. Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], ** kwargs_32365) config_32367 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 97, 11), 'config') module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 97, 4), 'stypy_return_type', config_32367) teardown_call_information(localization, arguments) stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 9, 0), 'stypy_return_type') module_type_store.store_return_type_of_current_context( stypy_return_type_32368) module_type_store = module_type_store.close_function_context() return stypy_return_type_32368 module_type_store.set_type_of(stypy.reporting.localization.Localization( __file__, 9, 0), 'configuration', configuration) if __name__ == '__main__': stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 101, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32369 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 101, 4), 'numpy.distutils.core') if type(import_32369) is not StypyTypeError: if import_32369 != 'pyd_module': __import__(import_32369) sys_modules_32370 = sys.modules[import_32369] import_from_module(stypy.reporting.localization.Localization( __file__, 101, 4), 'numpy.distutils.core', sys_modules_32370.module_type_store, module_type_store, [ 'setup']) nest_module(stypy.reporting.localization.Localization(__file__, 101, 4), __file__, sys_modules_32370, sys_modules_32370. module_type_store, module_type_store) else: from numpy.distutils.core import setup import_from_module(stypy.reporting.localization.Localization( __file__, 101, 4), 'numpy.distutils.core', None, module_type_store, ['setup'], [setup]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 101, 4), 'numpy.distutils.core', import_32369) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') kwargs_32378 = {} str_32373 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 102, 35), 'str', '') keyword_32374 = str_32373 kwargs_32375 = {'top_path': keyword_32374} configuration_32372 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 102, 12), 'configuration', False) configuration_call_result_32376 = invoke(stypy.reporting.localization. Localization(__file__, 102, 12), configuration_32372, *[], ** kwargs_32375) todict_32377 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 102, 12), configuration_call_result_32376, 'todict') todict_call_result_32379 = invoke(stypy.reporting.localization. Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378) kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379} setup_32371 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 102, 4), 'setup', False) setup_call_result_32381 = invoke(stypy.reporting.localization. Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380) module_errors = stypy.errors.type_error.StypyTypeError.get_error_msgs() module_warnings = stypy.errors.type_warning.TypeWarning.get_warning_msgs() <|reserved_special_token_1|> <|reserved_special_token_0|> from stypy.type_inference_programs.type_inference_programs_imports import * module_type_store = Context(None, __file__) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 3, 0)) import os import_module(stypy.reporting.localization.Localization(__file__, 3, 0), 'os', os, module_type_store) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 4, 0)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32066 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 4, 0), 'os.path') if type(import_32066) is not StypyTypeError: if import_32066 != 'pyd_module': __import__(import_32066) sys_modules_32067 = sys.modules[import_32066] import_from_module(stypy.reporting.localization.Localization( __file__, 4, 0), 'os.path', sys_modules_32067.module_type_store, module_type_store, ['join']) nest_module(stypy.reporting.localization.Localization(__file__, 4, 0), __file__, sys_modules_32067, sys_modules_32067. module_type_store, module_type_store) else: from os.path import join import_from_module(stypy.reporting.localization.Localization( __file__, 4, 0), 'os.path', None, module_type_store, ['join'], [join]) else: module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 4, 0), 'os.path', import_32066) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 6, 0)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32068 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 6, 0), 'scipy._build_utils') if type(import_32068) is not StypyTypeError: if import_32068 != 'pyd_module': __import__(import_32068) sys_modules_32069 = sys.modules[import_32068] import_from_module(stypy.reporting.localization.Localization( __file__, 6, 0), 'scipy._build_utils', sys_modules_32069. module_type_store, module_type_store, ['numpy_nodepr_api']) nest_module(stypy.reporting.localization.Localization(__file__, 6, 0), __file__, sys_modules_32069, sys_modules_32069. module_type_store, module_type_store) else: from scipy._build_utils import numpy_nodepr_api import_from_module(stypy.reporting.localization.Localization( __file__, 6, 0), 'scipy._build_utils', None, module_type_store, ['numpy_nodepr_api'], [numpy_nodepr_api]) else: module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 6, 0), 'scipy._build_utils', import_32068) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') @norecursion def configuration(localization, *varargs, **kwargs): global module_type_store str_32070 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 9, 33), 'str', '') None_32071 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 9, 45), 'None') defaults = [str_32070, None_32071] module_type_store = module_type_store.open_function_context('configuration' , 9, 0, False) configuration.stypy_localization = localization configuration.stypy_type_of_self = None configuration.stypy_type_store = module_type_store configuration.stypy_function_name = 'configuration' configuration.stypy_param_names_list = ['parent_package', 'top_path'] configuration.stypy_varargs_param_name = None configuration.stypy_kwargs_param_name = None configuration.stypy_call_defaults = defaults configuration.stypy_call_varargs = varargs configuration.stypy_call_kwargs = kwargs arguments = process_argument_values(localization, None, module_type_store, 'configuration', ['parent_package', 'top_path'], None, None, defaults, varargs, kwargs) if is_error_type(arguments): module_type_store = module_type_store.close_function_context() return arguments init_call_information(module_type_store, 'configuration', localization, ['parent_package', 'top_path'], arguments) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 0, 0), 'stypy_return_type', None) stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 10, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32072 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util' ) if type(import_32072) is not StypyTypeError: if import_32072 != 'pyd_module': __import__(import_32072) sys_modules_32073 = sys.modules[import_32072] import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', sys_modules_32073.module_type_store, module_type_store, [ 'Configuration']) nest_module(stypy.reporting.localization.Localization(__file__, 10, 4), __file__, sys_modules_32073, sys_modules_32073. module_type_store, module_type_store) else: from numpy.distutils.misc_util import Configuration import_from_module(stypy.reporting.localization.Localization( __file__, 10, 4), 'numpy.distutils.misc_util', None, module_type_store, ['Configuration'], [Configuration]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 10, 4), 'numpy.distutils.misc_util', import_32072) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 11, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32074 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info') if type(import_32074) is not StypyTypeError: if import_32074 != 'pyd_module': __import__(import_32074) sys_modules_32075 = sys.modules[import_32074] import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', sys_modules_32075.module_type_store, module_type_store, [ 'get_info']) nest_module(stypy.reporting.localization.Localization(__file__, 11, 4), __file__, sys_modules_32075, sys_modules_32075. module_type_store, module_type_store) else: from numpy.distutils.system_info import get_info import_from_module(stypy.reporting.localization.Localization( __file__, 11, 4), 'numpy.distutils.system_info', None, module_type_store, ['get_info'], [get_info]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 11, 4), 'numpy.distutils.system_info', import_32074) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') str_32077 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 12, 27), 'str', 'integrate') parent_package_32078 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 40), 'parent_package', False) top_path_32079 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 56), 'top_path', False) kwargs_32080 = {} Configuration_32076 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 12, 13), 'Configuration', False) Configuration_call_result_32081 = invoke(stypy.reporting.localization. Localization(__file__, 12, 13), Configuration_32076, *[str_32077, parent_package_32078, top_path_32079], **kwargs_32080) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 12, 4), 'config', Configuration_call_result_32081) str_32084 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 31), 'str', 'lapack_opt') int_32085 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 15, 60), 'int') keyword_32086 = int_32085 kwargs_32087 = {'notfound_action': keyword_32086} get_info_32083 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 15, 22), 'get_info', False) get_info_call_result_32088 = invoke(stypy.reporting.localization. Localization(__file__, 15, 22), get_info_32083, *[str_32084], ** kwargs_32087) kwargs_32089 = {} dict_32082 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 15, 17), 'dict', False) dict_call_result_32090 = invoke(stypy.reporting.localization. Localization(__file__, 15, 17), dict_32082, *[ get_info_call_result_32088], **kwargs_32089) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 15, 4), 'lapack_opt', dict_call_result_32090) str_32093 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 33), 'str', 'libraries') list_32094 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 18, 46), 'list') kwargs_32095 = {} lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 18, 18), 'lapack_opt', False) pop_32092 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop') pop_call_result_32096 = invoke(stypy.reporting.localization. Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094], **kwargs_32095) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 18, 4), 'lapack_libs', pop_call_result_32096) list_32097 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 15), 'list') str_32099 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 21), 'str', 'mach') str_32100 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 20, 28), 'str', '*.f') kwargs_32101 = {} join_32098 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 20, 16), 'join', False) join_call_result_32102 = invoke(stypy.reporting.localization. Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100], **kwargs_32101) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 20, 15), list_32097, join_call_result_32102) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 20, 4), 'mach_src', list_32097) list_32103 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 19), 'list') str_32105 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 25), 'str', 'quadpack') str_32106 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 21, 37), 'str', '*.f') kwargs_32107 = {} join_32104 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 21, 20), 'join', False) join_call_result_32108 = invoke(stypy.reporting.localization. Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106], **kwargs_32107) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 21, 19), list_32103, join_call_result_32108) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 21, 4), 'quadpack_src', list_32103) list_32114 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 47), 'list') str_32115 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32115) str_32116 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 23), 'str', 'bnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32116) str_32117 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 23, 34), 'str', 'cfode.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32117) str_32118 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 8), 'str', 'ewset.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32118) str_32119 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 19), 'str', 'fnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32119) str_32120 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 24, 30), 'str', 'intdy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32120) str_32121 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 8), 'str', 'lsoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32121) str_32122 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 19), 'str', 'prja.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32122) str_32123 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 29), 'str', 'solsy.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32123) str_32124 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 25, 40), 'str', 'srcma.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32124) str_32125 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 8), 'str', 'stoda.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32125) str_32126 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32126) str_32127 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32127) str_32128 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 26, 43), 'str', 'xsetf.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32128) str_32129 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 27, 8), 'str', 'xsetun.f') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 47), list_32114, str_32129) comprehension_32130 = get_contained_elements_type(stypy.reporting. localization.Localization(__file__, 22, 17), list_32114) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 17), 'fn', comprehension_32130) str_32110 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 22), 'str', 'odepack') fn_32111 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 22, 33), 'fn', False) kwargs_32112 = {} join_32109 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 22, 17), 'join', False) join_call_result_32113 = invoke(stypy.reporting.localization. Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111], **kwargs_32112) list_32131 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 22, 17), 'list') set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 22, 17), list_32131, join_call_result_32113) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 22, 4), 'lsoda_src', list_32131) list_32132 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 15), 'list') str_32134 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 21), 'str', 'odepack') str_32135 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 32), 'str', 'vode.f') kwargs_32136 = {} join_32133 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 16), 'join', False) join_call_result_32137 = invoke(stypy.reporting.localization. Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135], **kwargs_32136) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32137) str_32139 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 48), 'str', 'odepack') str_32140 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 28, 59), 'str', 'zvode.f') kwargs_32141 = {} join_32138 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 28, 43), 'join', False) join_call_result_32142 = invoke(stypy.reporting.localization. Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140], **kwargs_32141) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 28, 15), list_32132, join_call_result_32142) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 28, 4), 'vode_src', list_32132) list_32143 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 14), 'list') str_32145 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 20), 'str', 'dop') str_32146 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 29, 26), 'str', '*.f') kwargs_32147 = {} join_32144 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 29, 15), 'join', False) join_call_result_32148 = invoke(stypy.reporting.localization. Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146], **kwargs_32147) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 29, 14), list_32143, join_call_result_32148) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 29, 4), 'dop_src', list_32143) list_32149 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 24), 'list') str_32151 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 30), 'str', 'tests') str_32152 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 30, 38), 'str', '_test_multivariate.c') kwargs_32153 = {} join_32150 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 30, 25), 'join', False) join_call_result_32154 = invoke(stypy.reporting.localization. Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152], **kwargs_32153) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 30, 24), list_32149, join_call_result_32154) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 30, 4), 'quadpack_test_src', list_32149) list_32155 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 29), 'list') str_32157 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 35), 'str', 'tests') str_32158 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f') kwargs_32159 = {} join_32156 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 31, 30), 'join', False) join_call_result_32160 = invoke(stypy.reporting.localization. Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158], **kwargs_32159) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 31, 29), list_32155, join_call_result_32160) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 31, 4), 'odeint_banded_test_src', list_32155) str_32163 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 33, 23), 'str', 'mach') mach_src_32164 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 39), 'mach_src', False) keyword_32165 = mach_src_32164 dict_32166 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 33), 'dict') str_32167 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 34), 'str', 'noopt') tuple_32168 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 43), 'tuple') file___32169 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 34, 43), '__file__', False) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, file___32169) int_32170 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 34, 52), 'int') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 43), tuple_32168, int_32170) set_contained_elements_type(stypy.reporting.localization.Localization( __file__, 34, 33), dict_32166, (str_32167, tuple_32168)) keyword_32171 = dict_32166 kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171} config_32161 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 33, 4), 'config', False) add_library_32162 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 33, 4), config_32161, 'add_library') add_library_call_result_32173 = invoke(stypy.reporting.localization. Localization(__file__, 33, 4), add_library_32162, *[str_32163], ** kwargs_32172) str_32176 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 35, 23), 'str', 'quadpack') quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 43), 'quadpack_src', False) keyword_32178 = quadpack_src_32177 kwargs_32179 = {'sources': keyword_32178} config_32174 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 35, 4), 'config', False) add_library_32175 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 35, 4), config_32174, 'add_library') add_library_call_result_32180 = invoke(stypy.reporting.localization. Localization(__file__, 35, 4), add_library_32175, *[str_32176], ** kwargs_32179) str_32183 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 36, 23), 'str', 'lsoda') lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 40), 'lsoda_src', False) keyword_32185 = lsoda_src_32184 kwargs_32186 = {'sources': keyword_32185} config_32181 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 36, 4), 'config', False) add_library_32182 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 36, 4), config_32181, 'add_library') add_library_call_result_32187 = invoke(stypy.reporting.localization. Localization(__file__, 36, 4), add_library_32182, *[str_32183], ** kwargs_32186) str_32190 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 37, 23), 'str', 'vode') vode_src_32191 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 39), 'vode_src', False) keyword_32192 = vode_src_32191 kwargs_32193 = {'sources': keyword_32192} config_32188 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 37, 4), 'config', False) add_library_32189 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 37, 4), config_32188, 'add_library') add_library_call_result_32194 = invoke(stypy.reporting.localization. Localization(__file__, 37, 4), add_library_32189, *[str_32190], ** kwargs_32193) str_32197 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 38, 23), 'str', 'dop') dop_src_32198 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 38), 'dop_src', False) keyword_32199 = dop_src_32198 kwargs_32200 = {'sources': keyword_32199} config_32195 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 38, 4), 'config', False) add_library_32196 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 38, 4), config_32195, 'add_library') add_library_call_result_32201 = invoke(stypy.reporting.localization. Localization(__file__, 38, 4), add_library_32196, *[str_32197], ** kwargs_32200) list_32202 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 19), 'list') file___32207 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 42, 41), '__file__', False) kwargs_32208 = {} os_32204 = module_type_store.get_type_of(stypy.reporting.localization. Localization(__file__, 42, 25), 'os', False) path_32205 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), os_32204, 'path') dirname_32206 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 42, 25), path_32205, 'dirname') dirname_call_result_32209 = invoke(stypy.reporting.localization. Localization(__file__, 42, 25), dirname_32206, *[file___32207], ** kwargs_32208) str_32210 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 52), 'str', '..') str_32211 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 58), 'str', '_lib') str_32212 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 42, 66), 'str', 'src') kwargs_32213 = {} join_32203 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 42, 20), 'join', False) join_call_result_32214 = invoke(stypy.reporting.localization. Localization(__file__, 42, 20), join_32203, *[ dirname_call_result_32209, str_32210, str_32211, str_32212], ** kwargs_32213) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 42, 19), list_32202, join_call_result_32214) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 42, 4), 'include_dirs', list_32202) str_32215 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 43, 7), 'str', 'include_dirs') lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 43, 25), 'lapack_opt') result_contains_32217 = python_operator(stypy.reporting.localization. Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216) if_condition_32218 = is_suitable_condition(stypy.reporting.localization .Localization(__file__, 43, 4), result_contains_32217) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 43, 4), 'if_condition_32218', if_condition_32218) module_type_store = SSAContext.create_ssa_context(module_type_store, 'if') lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 44, 26), 'lapack_opt', False) kwargs_32221 = {} dict_32219 = module_type_store.get_type_of(stypy.reporting.localization .Localization(__file__, 44, 21), 'dict', False) dict_call_result_32222 = invoke(stypy.reporting.localization. Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], ** kwargs_32221) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 44, 8), 'lapack_opt', dict_call_result_32222) str_32227 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 45, 43), 'str', 'include_dirs') kwargs_32228 = {} lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 28), 'lapack_opt', False) pop_32226 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop') pop_call_result_32229 = invoke(stypy.reporting.localization. Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228 ) kwargs_32230 = {} include_dirs_32223 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 45, 8), 'include_dirs', False) extend_32224 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 45, 8), include_dirs_32223, 'extend') extend_call_result_32231 = invoke(stypy.reporting.localization. Localization(__file__, 45, 8), extend_32224, *[ pop_call_result_32229], **kwargs_32230) module_type_store = module_type_store.join_ssa_context() str_32234 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 47, 25), 'str', '_quadpack') list_32235 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 33), 'list') str_32236 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c' ) add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 48, 33), list_32235, str_32236) keyword_32237 = list_32235 list_32238 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 35), 'list') str_32239 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 36), 'str', 'quadpack') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32239) str_32240 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 49, 48), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 49, 35), list_32238, str_32240) lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 49, 58), 'lapack_libs', False) result_add_32242 = python_operator(stypy.reporting.localization. Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241) keyword_32243 = result_add_32242 list_32244 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 34), 'list') str_32245 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 50, 35), 'str', '__quadpack.h') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 50, 34), list_32244, str_32245) quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 36), 'quadpack_src', False) result_add_32247 = python_operator(stypy.reporting.localization. Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246) mach_src_32248 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 51, 51), 'mach_src', False) result_add_32249 = python_operator(stypy.reporting.localization. Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248) keyword_32250 = result_add_32249 include_dirs_32251 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 52, 38), 'include_dirs', False) keyword_32252 = include_dirs_32251 lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 53, 27), 'lapack_opt', False) kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237, 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253, 'include_dirs': keyword_32252} config_32232 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 47, 4), 'config', False) add_extension_32233 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 47, 4), config_32232, 'add_extension') add_extension_call_result_32255 = invoke(stypy.reporting.localization. Localization(__file__, 47, 4), add_extension_32233, *[str_32234], **kwargs_32254) kwargs_32258 = {} lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 56, 19), 'lapack_opt', False) copy_32257 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy') copy_call_result_32259 = invoke(stypy.reporting.localization. Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258) module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 56, 4), 'odepack_opts', copy_call_result_32259) numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False) kwargs_32263 = {} odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 57, 4), 'odepack_opts', False) update_32261 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 57, 4), odepack_opts_32260, 'update') update_call_result_32264 = invoke(stypy.reporting.localization. Localization(__file__, 57, 4), update_32261, *[ numpy_nodepr_api_32262], **kwargs_32263) str_32267 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 58, 25), 'str', '_odepack') list_32268 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 33), 'list') str_32269 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 59, 33), list_32268, str_32269) keyword_32270 = list_32268 list_32271 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 35), 'list') str_32272 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32272) str_32273 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 60, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 60, 35), list_32271, str_32273) lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 60, 55), 'lapack_libs', False) result_add_32275 = python_operator(stypy.reporting.localization. Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274) keyword_32276 = result_add_32275 lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 34), 'lsoda_src', False) mach_src_32278 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 61, 46), 'mach_src', False) result_add_32279 = python_operator(stypy.reporting.localization. Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278) keyword_32280 = result_add_32279 odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 62, 27), 'odepack_opts', False) kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270, 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281} config_32265 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 58, 4), 'config', False) add_extension_32266 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 58, 4), config_32265, 'add_extension') add_extension_call_result_32283 = invoke(stypy.reporting.localization. Localization(__file__, 58, 4), add_extension_32266, *[str_32267], **kwargs_32282) str_32286 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 65, 25), 'str', 'vode') list_32287 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 33), 'list') str_32288 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 66, 34), 'str', 'vode.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 66, 33), list_32287, str_32288) keyword_32289 = list_32287 list_32290 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 35), 'list') str_32291 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 67, 36), 'str', 'vode') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 67, 35), list_32290, str_32291) lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 67, 46), 'lapack_libs', False) result_add_32293 = python_operator(stypy.reporting.localization. Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292) keyword_32294 = result_add_32293 vode_src_32295 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 68, 33), 'vode_src', False) keyword_32296 = vode_src_32295 lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 69, 27), 'lapack_opt', False) kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289, 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297} config_32284 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 65, 4), 'config', False) add_extension_32285 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 65, 4), config_32284, 'add_extension') add_extension_call_result_32299 = invoke(stypy.reporting.localization. Localization(__file__, 65, 4), add_extension_32285, *[str_32286], **kwargs_32298) str_32302 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 72, 25), 'str', 'lsoda') list_32303 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 33), 'list') str_32304 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 73, 33), list_32303, str_32304) keyword_32305 = list_32303 list_32306 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 35), 'list') str_32307 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32307) str_32308 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 74, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 74, 35), list_32306, str_32308) lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 74, 55), 'lapack_libs', False) result_add_32310 = python_operator(stypy.reporting.localization. Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309) keyword_32311 = result_add_32310 lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 34), 'lsoda_src', False) mach_src_32313 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 75, 46), 'mach_src', False) result_add_32314 = python_operator(stypy.reporting.localization. Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313) keyword_32315 = result_add_32314 lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 76, 27), 'lapack_opt', False) kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305, 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316} config_32300 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 72, 4), 'config', False) add_extension_32301 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 72, 4), config_32300, 'add_extension') add_extension_call_result_32318 = invoke(stypy.reporting.localization. Localization(__file__, 72, 4), add_extension_32301, *[str_32302], **kwargs_32317) str_32321 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 79, 25), 'str', '_dop') list_32322 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 33), 'list') str_32323 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 80, 34), 'str', 'dop.pyf') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 80, 33), list_32322, str_32323) keyword_32324 = list_32322 list_32325 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 35), 'list') str_32326 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 81, 36), 'str', 'dop') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 81, 35), list_32325, str_32326) keyword_32327 = list_32325 dop_src_32328 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 82, 33), 'dop_src', False) keyword_32329 = dop_src_32328 kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324, 'depends': keyword_32329} config_32319 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 79, 4), 'config', False) add_extension_32320 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 79, 4), config_32319, 'add_extension') add_extension_call_result_32331 = invoke(stypy.reporting.localization. Localization(__file__, 79, 4), add_extension_32320, *[str_32321], **kwargs_32330) str_32334 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 84, 25), 'str', '_test_multivariate') quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 85, 33), 'quadpack_test_src', False) keyword_32336 = quadpack_test_src_32335 kwargs_32337 = {'sources': keyword_32336} config_32332 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 84, 4), 'config', False) add_extension_32333 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 84, 4), config_32332, 'add_extension') add_extension_call_result_32338 = invoke(stypy.reporting.localization. Localization(__file__, 84, 4), add_extension_32333, *[str_32334], **kwargs_32337) str_32341 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 88, 25), 'str', '_test_odeint_banded') odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy. reporting.localization.Localization(__file__, 89, 33), 'odeint_banded_test_src', False) keyword_32343 = odeint_banded_test_src_32342 list_32344 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 35), 'list') str_32345 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32345) str_32346 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 90, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization( __file__, 90, 35), list_32344, str_32346) lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 90, 55), 'lapack_libs', False) result_add_32348 = python_operator(stypy.reporting.localization. Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347) keyword_32349 = result_add_32348 lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 34), 'lsoda_src', False) mach_src_32351 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 91, 46), 'mach_src', False) result_add_32352 = python_operator(stypy.reporting.localization. Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351) keyword_32353 = result_add_32352 lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 92, 27), 'lapack_opt', False) kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343, 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354} config_32339 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 88, 4), 'config', False) add_extension_32340 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 88, 4), config_32339, 'add_extension') add_extension_call_result_32356 = invoke(stypy.reporting.localization. Localization(__file__, 88, 4), add_extension_32340, *[str_32341], **kwargs_32355) str_32359 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 94, 26), 'str', '_ivp') kwargs_32360 = {} config_32357 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 94, 4), 'config', False) add_subpackage_32358 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 94, 4), config_32357, 'add_subpackage') add_subpackage_call_result_32361 = invoke(stypy.reporting.localization. Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359], **kwargs_32360) str_32364 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 96, 24), 'str', 'tests') kwargs_32365 = {} config_32362 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 96, 4), 'config', False) add_data_dir_32363 = module_type_store.get_type_of_member(stypy. reporting.localization.Localization(__file__, 96, 4), config_32362, 'add_data_dir') add_data_dir_call_result_32366 = invoke(stypy.reporting.localization. Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], ** kwargs_32365) config_32367 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 97, 11), 'config') module_type_store.set_type_of(stypy.reporting.localization.Localization (__file__, 97, 4), 'stypy_return_type', config_32367) teardown_call_information(localization, arguments) stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting .localization.Localization(__file__, 9, 0), 'stypy_return_type') module_type_store.store_return_type_of_current_context( stypy_return_type_32368) module_type_store = module_type_store.close_function_context() return stypy_return_type_32368 module_type_store.set_type_of(stypy.reporting.localization.Localization( __file__, 9, 0), 'configuration', configuration) if __name__ == '__main__': stypy.reporting.localization.Localization.set_current(stypy.reporting. localization.Localization(__file__, 101, 4)) update_path_to_current_file_folder( 'C:/Python27/lib/site-packages/scipy/integrate/') import_32369 = generate_type_inference_code_for_module(stypy.reporting. localization.Localization(__file__, 101, 4), 'numpy.distutils.core') if type(import_32369) is not StypyTypeError: if import_32369 != 'pyd_module': __import__(import_32369) sys_modules_32370 = sys.modules[import_32369] import_from_module(stypy.reporting.localization.Localization( __file__, 101, 4), 'numpy.distutils.core', sys_modules_32370.module_type_store, module_type_store, [ 'setup']) nest_module(stypy.reporting.localization.Localization(__file__, 101, 4), __file__, sys_modules_32370, sys_modules_32370. module_type_store, module_type_store) else: from numpy.distutils.core import setup import_from_module(stypy.reporting.localization.Localization( __file__, 101, 4), 'numpy.distutils.core', None, module_type_store, ['setup'], [setup]) else: module_type_store.set_type_of(stypy.reporting.localization. Localization(__file__, 101, 4), 'numpy.distutils.core', import_32369) remove_current_file_folder_from_path( 'C:/Python27/lib/site-packages/scipy/integrate/') kwargs_32378 = {} str_32373 = get_builtin_python_type_instance(stypy.reporting. localization.Localization(__file__, 102, 35), 'str', '') keyword_32374 = str_32373 kwargs_32375 = {'top_path': keyword_32374} configuration_32372 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 102, 12), 'configuration', False) configuration_call_result_32376 = invoke(stypy.reporting.localization. Localization(__file__, 102, 12), configuration_32372, *[], ** kwargs_32375) todict_32377 = module_type_store.get_type_of_member(stypy.reporting. localization.Localization(__file__, 102, 12), configuration_call_result_32376, 'todict') todict_call_result_32379 = invoke(stypy.reporting.localization. Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378) kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379} setup_32371 = module_type_store.get_type_of(stypy.reporting. localization.Localization(__file__, 102, 4), 'setup', False) setup_call_result_32381 = invoke(stypy.reporting.localization. Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380) module_errors = stypy.errors.type_error.StypyTypeError.get_error_msgs() module_warnings = stypy.errors.type_warning.TypeWarning.get_warning_msgs() <|reserved_special_token_1|> # -*- coding: utf-8 -*- """ ORIGINAL PROGRAM SOURCE CODE: 1: from __future__ import division, print_function, absolute_import 2: 3: import os 4: from os.path import join 5: 6: from scipy._build_utils import numpy_nodepr_api 7: 8: 9: def configuration(parent_package='',top_path=None): 10: from numpy.distutils.misc_util import Configuration 11: from numpy.distutils.system_info import get_info 12: config = Configuration('integrate', parent_package, top_path) 13: 14: # Get a local copy of lapack_opt_info 15: lapack_opt = dict(get_info('lapack_opt',notfound_action=2)) 16: # Pop off the libraries list so it can be combined with 17: # additional required libraries 18: lapack_libs = lapack_opt.pop('libraries', []) 19: 20: mach_src = [join('mach','*.f')] 21: quadpack_src = [join('quadpack', '*.f')] 22: lsoda_src = [join('odepack', fn) for fn in [ 23: 'blkdta000.f', 'bnorm.f', 'cfode.f', 24: 'ewset.f', 'fnorm.f', 'intdy.f', 25: 'lsoda.f', 'prja.f', 'solsy.f', 'srcma.f', 26: 'stoda.f', 'vmnorm.f', 'xerrwv.f', 'xsetf.f', 27: 'xsetun.f']] 28: vode_src = [join('odepack', 'vode.f'), join('odepack', 'zvode.f')] 29: dop_src = [join('dop','*.f')] 30: quadpack_test_src = [join('tests','_test_multivariate.c')] 31: odeint_banded_test_src = [join('tests', 'banded5x5.f')] 32: 33: config.add_library('mach', sources=mach_src, 34: config_fc={'noopt':(__file__,1)}) 35: config.add_library('quadpack', sources=quadpack_src) 36: config.add_library('lsoda', sources=lsoda_src) 37: config.add_library('vode', sources=vode_src) 38: config.add_library('dop', sources=dop_src) 39: 40: # Extensions 41: # quadpack: 42: include_dirs = [join(os.path.dirname(__file__), '..', '_lib', 'src')] 43: if 'include_dirs' in lapack_opt: 44: lapack_opt = dict(lapack_opt) 45: include_dirs.extend(lapack_opt.pop('include_dirs')) 46: 47: config.add_extension('_quadpack', 48: sources=['_quadpackmodule.c'], 49: libraries=['quadpack', 'mach'] + lapack_libs, 50: depends=(['__quadpack.h'] 51: + quadpack_src + mach_src), 52: include_dirs=include_dirs, 53: **lapack_opt) 54: 55: # odepack/lsoda-odeint 56: odepack_opts = lapack_opt.copy() 57: odepack_opts.update(numpy_nodepr_api) 58: config.add_extension('_odepack', 59: sources=['_odepackmodule.c'], 60: libraries=['lsoda', 'mach'] + lapack_libs, 61: depends=(lsoda_src + mach_src), 62: **odepack_opts) 63: 64: # vode 65: config.add_extension('vode', 66: sources=['vode.pyf'], 67: libraries=['vode'] + lapack_libs, 68: depends=vode_src, 69: **lapack_opt) 70: 71: # lsoda 72: config.add_extension('lsoda', 73: sources=['lsoda.pyf'], 74: libraries=['lsoda', 'mach'] + lapack_libs, 75: depends=(lsoda_src + mach_src), 76: **lapack_opt) 77: 78: # dop 79: config.add_extension('_dop', 80: sources=['dop.pyf'], 81: libraries=['dop'], 82: depends=dop_src) 83: 84: config.add_extension('_test_multivariate', 85: sources=quadpack_test_src) 86: 87: # Fortran+f2py extension module for testing odeint. 88: config.add_extension('_test_odeint_banded', 89: sources=odeint_banded_test_src, 90: libraries=['lsoda', 'mach'] + lapack_libs, 91: depends=(lsoda_src + mach_src), 92: **lapack_opt) 93: 94: config.add_subpackage('_ivp') 95: 96: config.add_data_dir('tests') 97: return config 98: 99: 100: if __name__ == '__main__': 101: from numpy.distutils.core import setup 102: setup(**configuration(top_path='').todict()) 103: """ # Import the stypy library necessary elements from stypy.type_inference_programs.type_inference_programs_imports import * # Create the module type store module_type_store = Context(None, __file__) # ################# Begin of the type inference program ################## stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 3, 0)) # 'import os' statement (line 3) import os import_module(stypy.reporting.localization.Localization(__file__, 3, 0), 'os', os, module_type_store) stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 4, 0)) # 'from os.path import join' statement (line 4) update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/') import_32066 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path') if (type(import_32066) is not StypyTypeError): if (import_32066 != 'pyd_module'): __import__(import_32066) sys_modules_32067 = sys.modules[import_32066] import_from_module(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path', sys_modules_32067.module_type_store, module_type_store, ['join']) nest_module(stypy.reporting.localization.Localization(__file__, 4, 0), __file__, sys_modules_32067, sys_modules_32067.module_type_store, module_type_store) else: from os.path import join import_from_module(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path', None, module_type_store, ['join'], [join]) else: # Assigning a type to the variable 'os.path' (line 4) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path', import_32066) remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 6, 0)) # 'from scipy._build_utils import numpy_nodepr_api' statement (line 6) update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/') import_32068 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils') if (type(import_32068) is not StypyTypeError): if (import_32068 != 'pyd_module'): __import__(import_32068) sys_modules_32069 = sys.modules[import_32068] import_from_module(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils', sys_modules_32069.module_type_store, module_type_store, ['numpy_nodepr_api']) nest_module(stypy.reporting.localization.Localization(__file__, 6, 0), __file__, sys_modules_32069, sys_modules_32069.module_type_store, module_type_store) else: from scipy._build_utils import numpy_nodepr_api import_from_module(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils', None, module_type_store, ['numpy_nodepr_api'], [numpy_nodepr_api]) else: # Assigning a type to the variable 'scipy._build_utils' (line 6) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils', import_32068) remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/') @norecursion def configuration(localization, *varargs, **kwargs): global module_type_store # Assign values to the parameters with defaults str_32070 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 9, 33), 'str', '') # Getting the type of 'None' (line 9) None_32071 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 9, 45), 'None') defaults = [str_32070, None_32071] # Create a new context for function 'configuration' module_type_store = module_type_store.open_function_context('configuration', 9, 0, False) # Passed parameters checking function configuration.stypy_localization = localization configuration.stypy_type_of_self = None configuration.stypy_type_store = module_type_store configuration.stypy_function_name = 'configuration' configuration.stypy_param_names_list = ['parent_package', 'top_path'] configuration.stypy_varargs_param_name = None configuration.stypy_kwargs_param_name = None configuration.stypy_call_defaults = defaults configuration.stypy_call_varargs = varargs configuration.stypy_call_kwargs = kwargs arguments = process_argument_values(localization, None, module_type_store, 'configuration', ['parent_package', 'top_path'], None, None, defaults, varargs, kwargs) if is_error_type(arguments): # Destroy the current context module_type_store = module_type_store.close_function_context() return arguments # Initialize method data init_call_information(module_type_store, 'configuration', localization, ['parent_package', 'top_path'], arguments) # Default return type storage variable (SSA) # Assigning a type to the variable 'stypy_return_type' module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 0, 0), 'stypy_return_type', None) # ################# Begin of 'configuration(...)' code ################## stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 10, 4)) # 'from numpy.distutils.misc_util import Configuration' statement (line 10) update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/') import_32072 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util') if (type(import_32072) is not StypyTypeError): if (import_32072 != 'pyd_module'): __import__(import_32072) sys_modules_32073 = sys.modules[import_32072] import_from_module(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util', sys_modules_32073.module_type_store, module_type_store, ['Configuration']) nest_module(stypy.reporting.localization.Localization(__file__, 10, 4), __file__, sys_modules_32073, sys_modules_32073.module_type_store, module_type_store) else: from numpy.distutils.misc_util import Configuration import_from_module(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util', None, module_type_store, ['Configuration'], [Configuration]) else: # Assigning a type to the variable 'numpy.distutils.misc_util' (line 10) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util', import_32072) remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/') stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 11, 4)) # 'from numpy.distutils.system_info import get_info' statement (line 11) update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/') import_32074 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info') if (type(import_32074) is not StypyTypeError): if (import_32074 != 'pyd_module'): __import__(import_32074) sys_modules_32075 = sys.modules[import_32074] import_from_module(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info', sys_modules_32075.module_type_store, module_type_store, ['get_info']) nest_module(stypy.reporting.localization.Localization(__file__, 11, 4), __file__, sys_modules_32075, sys_modules_32075.module_type_store, module_type_store) else: from numpy.distutils.system_info import get_info import_from_module(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info', None, module_type_store, ['get_info'], [get_info]) else: # Assigning a type to the variable 'numpy.distutils.system_info' (line 11) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info', import_32074) remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/') # Assigning a Call to a Name (line 12): # Call to Configuration(...): (line 12) # Processing the call arguments (line 12) str_32077 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 12, 27), 'str', 'integrate') # Getting the type of 'parent_package' (line 12) parent_package_32078 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 12, 40), 'parent_package', False) # Getting the type of 'top_path' (line 12) top_path_32079 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 12, 56), 'top_path', False) # Processing the call keyword arguments (line 12) kwargs_32080 = {} # Getting the type of 'Configuration' (line 12) Configuration_32076 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 12, 13), 'Configuration', False) # Calling Configuration(args, kwargs) (line 12) Configuration_call_result_32081 = invoke(stypy.reporting.localization.Localization(__file__, 12, 13), Configuration_32076, *[str_32077, parent_package_32078, top_path_32079], **kwargs_32080) # Assigning a type to the variable 'config' (line 12) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 12, 4), 'config', Configuration_call_result_32081) # Assigning a Call to a Name (line 15): # Call to dict(...): (line 15) # Processing the call arguments (line 15) # Call to get_info(...): (line 15) # Processing the call arguments (line 15) str_32084 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 15, 31), 'str', 'lapack_opt') # Processing the call keyword arguments (line 15) int_32085 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 15, 60), 'int') keyword_32086 = int_32085 kwargs_32087 = {'notfound_action': keyword_32086} # Getting the type of 'get_info' (line 15) get_info_32083 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 15, 22), 'get_info', False) # Calling get_info(args, kwargs) (line 15) get_info_call_result_32088 = invoke(stypy.reporting.localization.Localization(__file__, 15, 22), get_info_32083, *[str_32084], **kwargs_32087) # Processing the call keyword arguments (line 15) kwargs_32089 = {} # Getting the type of 'dict' (line 15) dict_32082 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 15, 17), 'dict', False) # Calling dict(args, kwargs) (line 15) dict_call_result_32090 = invoke(stypy.reporting.localization.Localization(__file__, 15, 17), dict_32082, *[get_info_call_result_32088], **kwargs_32089) # Assigning a type to the variable 'lapack_opt' (line 15) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 15, 4), 'lapack_opt', dict_call_result_32090) # Assigning a Call to a Name (line 18): # Call to pop(...): (line 18) # Processing the call arguments (line 18) str_32093 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 18, 33), 'str', 'libraries') # Obtaining an instance of the builtin type 'list' (line 18) list_32094 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 18, 46), 'list') # Adding type elements to the builtin type 'list' instance (line 18) # Processing the call keyword arguments (line 18) kwargs_32095 = {} # Getting the type of 'lapack_opt' (line 18) lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 18, 18), 'lapack_opt', False) # Obtaining the member 'pop' of a type (line 18) pop_32092 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop') # Calling pop(args, kwargs) (line 18) pop_call_result_32096 = invoke(stypy.reporting.localization.Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094], **kwargs_32095) # Assigning a type to the variable 'lapack_libs' (line 18) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 18, 4), 'lapack_libs', pop_call_result_32096) # Assigning a List to a Name (line 20): # Obtaining an instance of the builtin type 'list' (line 20) list_32097 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 20, 15), 'list') # Adding type elements to the builtin type 'list' instance (line 20) # Adding element type (line 20) # Call to join(...): (line 20) # Processing the call arguments (line 20) str_32099 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 20, 21), 'str', 'mach') str_32100 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 20, 28), 'str', '*.f') # Processing the call keyword arguments (line 20) kwargs_32101 = {} # Getting the type of 'join' (line 20) join_32098 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 20, 16), 'join', False) # Calling join(args, kwargs) (line 20) join_call_result_32102 = invoke(stypy.reporting.localization.Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100], **kwargs_32101) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 20, 15), list_32097, join_call_result_32102) # Assigning a type to the variable 'mach_src' (line 20) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 20, 4), 'mach_src', list_32097) # Assigning a List to a Name (line 21): # Obtaining an instance of the builtin type 'list' (line 21) list_32103 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 21, 19), 'list') # Adding type elements to the builtin type 'list' instance (line 21) # Adding element type (line 21) # Call to join(...): (line 21) # Processing the call arguments (line 21) str_32105 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 21, 25), 'str', 'quadpack') str_32106 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 21, 37), 'str', '*.f') # Processing the call keyword arguments (line 21) kwargs_32107 = {} # Getting the type of 'join' (line 21) join_32104 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 21, 20), 'join', False) # Calling join(args, kwargs) (line 21) join_call_result_32108 = invoke(stypy.reporting.localization.Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106], **kwargs_32107) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 21, 19), list_32103, join_call_result_32108) # Assigning a type to the variable 'quadpack_src' (line 21) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 21, 4), 'quadpack_src', list_32103) # Assigning a ListComp to a Name (line 22): # Calculating list comprehension # Calculating comprehension expression # Obtaining an instance of the builtin type 'list' (line 22) list_32114 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 22, 47), 'list') # Adding type elements to the builtin type 'list' instance (line 22) # Adding element type (line 22) str_32115 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32115) # Adding element type (line 22) str_32116 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 23, 23), 'str', 'bnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32116) # Adding element type (line 22) str_32117 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 23, 34), 'str', 'cfode.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32117) # Adding element type (line 22) str_32118 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 24, 8), 'str', 'ewset.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32118) # Adding element type (line 22) str_32119 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 24, 19), 'str', 'fnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32119) # Adding element type (line 22) str_32120 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 24, 30), 'str', 'intdy.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32120) # Adding element type (line 22) str_32121 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 8), 'str', 'lsoda.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32121) # Adding element type (line 22) str_32122 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 19), 'str', 'prja.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32122) # Adding element type (line 22) str_32123 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 29), 'str', 'solsy.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32123) # Adding element type (line 22) str_32124 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 40), 'str', 'srcma.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32124) # Adding element type (line 22) str_32125 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 8), 'str', 'stoda.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32125) # Adding element type (line 22) str_32126 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32126) # Adding element type (line 22) str_32127 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32127) # Adding element type (line 22) str_32128 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 43), 'str', 'xsetf.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32128) # Adding element type (line 22) str_32129 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 27, 8), 'str', 'xsetun.f') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32129) comprehension_32130 = get_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 17), list_32114) # Assigning a type to the variable 'fn' (line 22) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 22, 17), 'fn', comprehension_32130) # Call to join(...): (line 22) # Processing the call arguments (line 22) str_32110 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 22, 22), 'str', 'odepack') # Getting the type of 'fn' (line 22) fn_32111 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 22, 33), 'fn', False) # Processing the call keyword arguments (line 22) kwargs_32112 = {} # Getting the type of 'join' (line 22) join_32109 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 22, 17), 'join', False) # Calling join(args, kwargs) (line 22) join_call_result_32113 = invoke(stypy.reporting.localization.Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111], **kwargs_32112) list_32131 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 22, 17), 'list') set_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 17), list_32131, join_call_result_32113) # Assigning a type to the variable 'lsoda_src' (line 22) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 22, 4), 'lsoda_src', list_32131) # Assigning a List to a Name (line 28): # Obtaining an instance of the builtin type 'list' (line 28) list_32132 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 15), 'list') # Adding type elements to the builtin type 'list' instance (line 28) # Adding element type (line 28) # Call to join(...): (line 28) # Processing the call arguments (line 28) str_32134 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 21), 'str', 'odepack') str_32135 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 32), 'str', 'vode.f') # Processing the call keyword arguments (line 28) kwargs_32136 = {} # Getting the type of 'join' (line 28) join_32133 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 28, 16), 'join', False) # Calling join(args, kwargs) (line 28) join_call_result_32137 = invoke(stypy.reporting.localization.Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135], **kwargs_32136) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 28, 15), list_32132, join_call_result_32137) # Adding element type (line 28) # Call to join(...): (line 28) # Processing the call arguments (line 28) str_32139 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 48), 'str', 'odepack') str_32140 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 59), 'str', 'zvode.f') # Processing the call keyword arguments (line 28) kwargs_32141 = {} # Getting the type of 'join' (line 28) join_32138 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 28, 43), 'join', False) # Calling join(args, kwargs) (line 28) join_call_result_32142 = invoke(stypy.reporting.localization.Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140], **kwargs_32141) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 28, 15), list_32132, join_call_result_32142) # Assigning a type to the variable 'vode_src' (line 28) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 28, 4), 'vode_src', list_32132) # Assigning a List to a Name (line 29): # Obtaining an instance of the builtin type 'list' (line 29) list_32143 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 29, 14), 'list') # Adding type elements to the builtin type 'list' instance (line 29) # Adding element type (line 29) # Call to join(...): (line 29) # Processing the call arguments (line 29) str_32145 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 29, 20), 'str', 'dop') str_32146 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 29, 26), 'str', '*.f') # Processing the call keyword arguments (line 29) kwargs_32147 = {} # Getting the type of 'join' (line 29) join_32144 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 29, 15), 'join', False) # Calling join(args, kwargs) (line 29) join_call_result_32148 = invoke(stypy.reporting.localization.Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146], **kwargs_32147) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 29, 14), list_32143, join_call_result_32148) # Assigning a type to the variable 'dop_src' (line 29) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 29, 4), 'dop_src', list_32143) # Assigning a List to a Name (line 30): # Obtaining an instance of the builtin type 'list' (line 30) list_32149 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 30, 24), 'list') # Adding type elements to the builtin type 'list' instance (line 30) # Adding element type (line 30) # Call to join(...): (line 30) # Processing the call arguments (line 30) str_32151 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 30, 30), 'str', 'tests') str_32152 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 30, 38), 'str', '_test_multivariate.c') # Processing the call keyword arguments (line 30) kwargs_32153 = {} # Getting the type of 'join' (line 30) join_32150 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 30, 25), 'join', False) # Calling join(args, kwargs) (line 30) join_call_result_32154 = invoke(stypy.reporting.localization.Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152], **kwargs_32153) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 30, 24), list_32149, join_call_result_32154) # Assigning a type to the variable 'quadpack_test_src' (line 30) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 30, 4), 'quadpack_test_src', list_32149) # Assigning a List to a Name (line 31): # Obtaining an instance of the builtin type 'list' (line 31) list_32155 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 31, 29), 'list') # Adding type elements to the builtin type 'list' instance (line 31) # Adding element type (line 31) # Call to join(...): (line 31) # Processing the call arguments (line 31) str_32157 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 31, 35), 'str', 'tests') str_32158 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f') # Processing the call keyword arguments (line 31) kwargs_32159 = {} # Getting the type of 'join' (line 31) join_32156 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 31, 30), 'join', False) # Calling join(args, kwargs) (line 31) join_call_result_32160 = invoke(stypy.reporting.localization.Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158], **kwargs_32159) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 31, 29), list_32155, join_call_result_32160) # Assigning a type to the variable 'odeint_banded_test_src' (line 31) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 31, 4), 'odeint_banded_test_src', list_32155) # Call to add_library(...): (line 33) # Processing the call arguments (line 33) str_32163 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 33, 23), 'str', 'mach') # Processing the call keyword arguments (line 33) # Getting the type of 'mach_src' (line 33) mach_src_32164 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 33, 39), 'mach_src', False) keyword_32165 = mach_src_32164 # Obtaining an instance of the builtin type 'dict' (line 34) dict_32166 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 33), 'dict') # Adding type elements to the builtin type 'dict' instance (line 34) # Adding element type (key, value) (line 34) str_32167 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 34), 'str', 'noopt') # Obtaining an instance of the builtin type 'tuple' (line 34) tuple_32168 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 43), 'tuple') # Adding type elements to the builtin type 'tuple' instance (line 34) # Adding element type (line 34) # Getting the type of '__file__' (line 34) file___32169 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 34, 43), '__file__', False) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 34, 43), tuple_32168, file___32169) # Adding element type (line 34) int_32170 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 52), 'int') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 34, 43), tuple_32168, int_32170) set_contained_elements_type(stypy.reporting.localization.Localization(__file__, 34, 33), dict_32166, (str_32167, tuple_32168)) keyword_32171 = dict_32166 kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171} # Getting the type of 'config' (line 33) config_32161 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 33, 4), 'config', False) # Obtaining the member 'add_library' of a type (line 33) add_library_32162 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 33, 4), config_32161, 'add_library') # Calling add_library(args, kwargs) (line 33) add_library_call_result_32173 = invoke(stypy.reporting.localization.Localization(__file__, 33, 4), add_library_32162, *[str_32163], **kwargs_32172) # Call to add_library(...): (line 35) # Processing the call arguments (line 35) str_32176 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 35, 23), 'str', 'quadpack') # Processing the call keyword arguments (line 35) # Getting the type of 'quadpack_src' (line 35) quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 35, 43), 'quadpack_src', False) keyword_32178 = quadpack_src_32177 kwargs_32179 = {'sources': keyword_32178} # Getting the type of 'config' (line 35) config_32174 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 35, 4), 'config', False) # Obtaining the member 'add_library' of a type (line 35) add_library_32175 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 35, 4), config_32174, 'add_library') # Calling add_library(args, kwargs) (line 35) add_library_call_result_32180 = invoke(stypy.reporting.localization.Localization(__file__, 35, 4), add_library_32175, *[str_32176], **kwargs_32179) # Call to add_library(...): (line 36) # Processing the call arguments (line 36) str_32183 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 36, 23), 'str', 'lsoda') # Processing the call keyword arguments (line 36) # Getting the type of 'lsoda_src' (line 36) lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 36, 40), 'lsoda_src', False) keyword_32185 = lsoda_src_32184 kwargs_32186 = {'sources': keyword_32185} # Getting the type of 'config' (line 36) config_32181 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 36, 4), 'config', False) # Obtaining the member 'add_library' of a type (line 36) add_library_32182 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 36, 4), config_32181, 'add_library') # Calling add_library(args, kwargs) (line 36) add_library_call_result_32187 = invoke(stypy.reporting.localization.Localization(__file__, 36, 4), add_library_32182, *[str_32183], **kwargs_32186) # Call to add_library(...): (line 37) # Processing the call arguments (line 37) str_32190 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 37, 23), 'str', 'vode') # Processing the call keyword arguments (line 37) # Getting the type of 'vode_src' (line 37) vode_src_32191 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 37, 39), 'vode_src', False) keyword_32192 = vode_src_32191 kwargs_32193 = {'sources': keyword_32192} # Getting the type of 'config' (line 37) config_32188 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 37, 4), 'config', False) # Obtaining the member 'add_library' of a type (line 37) add_library_32189 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 37, 4), config_32188, 'add_library') # Calling add_library(args, kwargs) (line 37) add_library_call_result_32194 = invoke(stypy.reporting.localization.Localization(__file__, 37, 4), add_library_32189, *[str_32190], **kwargs_32193) # Call to add_library(...): (line 38) # Processing the call arguments (line 38) str_32197 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 38, 23), 'str', 'dop') # Processing the call keyword arguments (line 38) # Getting the type of 'dop_src' (line 38) dop_src_32198 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 38, 38), 'dop_src', False) keyword_32199 = dop_src_32198 kwargs_32200 = {'sources': keyword_32199} # Getting the type of 'config' (line 38) config_32195 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 38, 4), 'config', False) # Obtaining the member 'add_library' of a type (line 38) add_library_32196 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 38, 4), config_32195, 'add_library') # Calling add_library(args, kwargs) (line 38) add_library_call_result_32201 = invoke(stypy.reporting.localization.Localization(__file__, 38, 4), add_library_32196, *[str_32197], **kwargs_32200) # Assigning a List to a Name (line 42): # Obtaining an instance of the builtin type 'list' (line 42) list_32202 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 19), 'list') # Adding type elements to the builtin type 'list' instance (line 42) # Adding element type (line 42) # Call to join(...): (line 42) # Processing the call arguments (line 42) # Call to dirname(...): (line 42) # Processing the call arguments (line 42) # Getting the type of '__file__' (line 42) file___32207 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 42, 41), '__file__', False) # Processing the call keyword arguments (line 42) kwargs_32208 = {} # Getting the type of 'os' (line 42) os_32204 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 42, 25), 'os', False) # Obtaining the member 'path' of a type (line 42) path_32205 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 42, 25), os_32204, 'path') # Obtaining the member 'dirname' of a type (line 42) dirname_32206 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 42, 25), path_32205, 'dirname') # Calling dirname(args, kwargs) (line 42) dirname_call_result_32209 = invoke(stypy.reporting.localization.Localization(__file__, 42, 25), dirname_32206, *[file___32207], **kwargs_32208) str_32210 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 52), 'str', '..') str_32211 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 58), 'str', '_lib') str_32212 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 66), 'str', 'src') # Processing the call keyword arguments (line 42) kwargs_32213 = {} # Getting the type of 'join' (line 42) join_32203 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 42, 20), 'join', False) # Calling join(args, kwargs) (line 42) join_call_result_32214 = invoke(stypy.reporting.localization.Localization(__file__, 42, 20), join_32203, *[dirname_call_result_32209, str_32210, str_32211, str_32212], **kwargs_32213) add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 42, 19), list_32202, join_call_result_32214) # Assigning a type to the variable 'include_dirs' (line 42) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 42, 4), 'include_dirs', list_32202) str_32215 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 43, 7), 'str', 'include_dirs') # Getting the type of 'lapack_opt' (line 43) lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 43, 25), 'lapack_opt') # Applying the binary operator 'in' (line 43) result_contains_32217 = python_operator(stypy.reporting.localization.Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216) # Testing the type of an if condition (line 43) if_condition_32218 = is_suitable_condition(stypy.reporting.localization.Localization(__file__, 43, 4), result_contains_32217) # Assigning a type to the variable 'if_condition_32218' (line 43) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 43, 4), 'if_condition_32218', if_condition_32218) # SSA begins for if statement (line 43) module_type_store = SSAContext.create_ssa_context(module_type_store, 'if') # Assigning a Call to a Name (line 44): # Call to dict(...): (line 44) # Processing the call arguments (line 44) # Getting the type of 'lapack_opt' (line 44) lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 44, 26), 'lapack_opt', False) # Processing the call keyword arguments (line 44) kwargs_32221 = {} # Getting the type of 'dict' (line 44) dict_32219 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 44, 21), 'dict', False) # Calling dict(args, kwargs) (line 44) dict_call_result_32222 = invoke(stypy.reporting.localization.Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], **kwargs_32221) # Assigning a type to the variable 'lapack_opt' (line 44) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 44, 8), 'lapack_opt', dict_call_result_32222) # Call to extend(...): (line 45) # Processing the call arguments (line 45) # Call to pop(...): (line 45) # Processing the call arguments (line 45) str_32227 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 45, 43), 'str', 'include_dirs') # Processing the call keyword arguments (line 45) kwargs_32228 = {} # Getting the type of 'lapack_opt' (line 45) lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 45, 28), 'lapack_opt', False) # Obtaining the member 'pop' of a type (line 45) pop_32226 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop') # Calling pop(args, kwargs) (line 45) pop_call_result_32229 = invoke(stypy.reporting.localization.Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228) # Processing the call keyword arguments (line 45) kwargs_32230 = {} # Getting the type of 'include_dirs' (line 45) include_dirs_32223 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 45, 8), 'include_dirs', False) # Obtaining the member 'extend' of a type (line 45) extend_32224 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 45, 8), include_dirs_32223, 'extend') # Calling extend(args, kwargs) (line 45) extend_call_result_32231 = invoke(stypy.reporting.localization.Localization(__file__, 45, 8), extend_32224, *[pop_call_result_32229], **kwargs_32230) # SSA join for if statement (line 43) module_type_store = module_type_store.join_ssa_context() # Call to add_extension(...): (line 47) # Processing the call arguments (line 47) str_32234 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 47, 25), 'str', '_quadpack') # Processing the call keyword arguments (line 47) # Obtaining an instance of the builtin type 'list' (line 48) list_32235 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 48, 33), 'list') # Adding type elements to the builtin type 'list' instance (line 48) # Adding element type (line 48) str_32236 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 48, 33), list_32235, str_32236) keyword_32237 = list_32235 # Obtaining an instance of the builtin type 'list' (line 49) list_32238 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 49, 35), 'list') # Adding type elements to the builtin type 'list' instance (line 49) # Adding element type (line 49) str_32239 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 49, 36), 'str', 'quadpack') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 49, 35), list_32238, str_32239) # Adding element type (line 49) str_32240 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 49, 48), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 49, 35), list_32238, str_32240) # Getting the type of 'lapack_libs' (line 49) lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 49, 58), 'lapack_libs', False) # Applying the binary operator '+' (line 49) result_add_32242 = python_operator(stypy.reporting.localization.Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241) keyword_32243 = result_add_32242 # Obtaining an instance of the builtin type 'list' (line 50) list_32244 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 50, 34), 'list') # Adding type elements to the builtin type 'list' instance (line 50) # Adding element type (line 50) str_32245 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 50, 35), 'str', '__quadpack.h') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 50, 34), list_32244, str_32245) # Getting the type of 'quadpack_src' (line 51) quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 51, 36), 'quadpack_src', False) # Applying the binary operator '+' (line 50) result_add_32247 = python_operator(stypy.reporting.localization.Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246) # Getting the type of 'mach_src' (line 51) mach_src_32248 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 51, 51), 'mach_src', False) # Applying the binary operator '+' (line 51) result_add_32249 = python_operator(stypy.reporting.localization.Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248) keyword_32250 = result_add_32249 # Getting the type of 'include_dirs' (line 52) include_dirs_32251 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 52, 38), 'include_dirs', False) keyword_32252 = include_dirs_32251 # Getting the type of 'lapack_opt' (line 53) lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 53, 27), 'lapack_opt', False) kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237, 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253, 'include_dirs': keyword_32252} # Getting the type of 'config' (line 47) config_32232 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 47, 4), 'config', False) # Obtaining the member 'add_extension' of a type (line 47) add_extension_32233 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 47, 4), config_32232, 'add_extension') # Calling add_extension(args, kwargs) (line 47) add_extension_call_result_32255 = invoke(stypy.reporting.localization.Localization(__file__, 47, 4), add_extension_32233, *[str_32234], **kwargs_32254) # Assigning a Call to a Name (line 56): # Call to copy(...): (line 56) # Processing the call keyword arguments (line 56) kwargs_32258 = {} # Getting the type of 'lapack_opt' (line 56) lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 56, 19), 'lapack_opt', False) # Obtaining the member 'copy' of a type (line 56) copy_32257 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy') # Calling copy(args, kwargs) (line 56) copy_call_result_32259 = invoke(stypy.reporting.localization.Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258) # Assigning a type to the variable 'odepack_opts' (line 56) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 56, 4), 'odepack_opts', copy_call_result_32259) # Call to update(...): (line 57) # Processing the call arguments (line 57) # Getting the type of 'numpy_nodepr_api' (line 57) numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False) # Processing the call keyword arguments (line 57) kwargs_32263 = {} # Getting the type of 'odepack_opts' (line 57) odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 57, 4), 'odepack_opts', False) # Obtaining the member 'update' of a type (line 57) update_32261 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 57, 4), odepack_opts_32260, 'update') # Calling update(args, kwargs) (line 57) update_call_result_32264 = invoke(stypy.reporting.localization.Localization(__file__, 57, 4), update_32261, *[numpy_nodepr_api_32262], **kwargs_32263) # Call to add_extension(...): (line 58) # Processing the call arguments (line 58) str_32267 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 58, 25), 'str', '_odepack') # Processing the call keyword arguments (line 58) # Obtaining an instance of the builtin type 'list' (line 59) list_32268 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 59, 33), 'list') # Adding type elements to the builtin type 'list' instance (line 59) # Adding element type (line 59) str_32269 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 59, 33), list_32268, str_32269) keyword_32270 = list_32268 # Obtaining an instance of the builtin type 'list' (line 60) list_32271 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 60, 35), 'list') # Adding type elements to the builtin type 'list' instance (line 60) # Adding element type (line 60) str_32272 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 60, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 60, 35), list_32271, str_32272) # Adding element type (line 60) str_32273 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 60, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 60, 35), list_32271, str_32273) # Getting the type of 'lapack_libs' (line 60) lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 60, 55), 'lapack_libs', False) # Applying the binary operator '+' (line 60) result_add_32275 = python_operator(stypy.reporting.localization.Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274) keyword_32276 = result_add_32275 # Getting the type of 'lsoda_src' (line 61) lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 61, 34), 'lsoda_src', False) # Getting the type of 'mach_src' (line 61) mach_src_32278 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 61, 46), 'mach_src', False) # Applying the binary operator '+' (line 61) result_add_32279 = python_operator(stypy.reporting.localization.Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278) keyword_32280 = result_add_32279 # Getting the type of 'odepack_opts' (line 62) odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 62, 27), 'odepack_opts', False) kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270, 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281} # Getting the type of 'config' (line 58) config_32265 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 58, 4), 'config', False) # Obtaining the member 'add_extension' of a type (line 58) add_extension_32266 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 58, 4), config_32265, 'add_extension') # Calling add_extension(args, kwargs) (line 58) add_extension_call_result_32283 = invoke(stypy.reporting.localization.Localization(__file__, 58, 4), add_extension_32266, *[str_32267], **kwargs_32282) # Call to add_extension(...): (line 65) # Processing the call arguments (line 65) str_32286 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 65, 25), 'str', 'vode') # Processing the call keyword arguments (line 65) # Obtaining an instance of the builtin type 'list' (line 66) list_32287 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 66, 33), 'list') # Adding type elements to the builtin type 'list' instance (line 66) # Adding element type (line 66) str_32288 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 66, 34), 'str', 'vode.pyf') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 66, 33), list_32287, str_32288) keyword_32289 = list_32287 # Obtaining an instance of the builtin type 'list' (line 67) list_32290 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 67, 35), 'list') # Adding type elements to the builtin type 'list' instance (line 67) # Adding element type (line 67) str_32291 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 67, 36), 'str', 'vode') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 67, 35), list_32290, str_32291) # Getting the type of 'lapack_libs' (line 67) lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 67, 46), 'lapack_libs', False) # Applying the binary operator '+' (line 67) result_add_32293 = python_operator(stypy.reporting.localization.Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292) keyword_32294 = result_add_32293 # Getting the type of 'vode_src' (line 68) vode_src_32295 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 68, 33), 'vode_src', False) keyword_32296 = vode_src_32295 # Getting the type of 'lapack_opt' (line 69) lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 69, 27), 'lapack_opt', False) kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289, 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297} # Getting the type of 'config' (line 65) config_32284 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 65, 4), 'config', False) # Obtaining the member 'add_extension' of a type (line 65) add_extension_32285 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 65, 4), config_32284, 'add_extension') # Calling add_extension(args, kwargs) (line 65) add_extension_call_result_32299 = invoke(stypy.reporting.localization.Localization(__file__, 65, 4), add_extension_32285, *[str_32286], **kwargs_32298) # Call to add_extension(...): (line 72) # Processing the call arguments (line 72) str_32302 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 72, 25), 'str', 'lsoda') # Processing the call keyword arguments (line 72) # Obtaining an instance of the builtin type 'list' (line 73) list_32303 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 73, 33), 'list') # Adding type elements to the builtin type 'list' instance (line 73) # Adding element type (line 73) str_32304 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 73, 33), list_32303, str_32304) keyword_32305 = list_32303 # Obtaining an instance of the builtin type 'list' (line 74) list_32306 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 74, 35), 'list') # Adding type elements to the builtin type 'list' instance (line 74) # Adding element type (line 74) str_32307 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 74, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 74, 35), list_32306, str_32307) # Adding element type (line 74) str_32308 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 74, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 74, 35), list_32306, str_32308) # Getting the type of 'lapack_libs' (line 74) lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 74, 55), 'lapack_libs', False) # Applying the binary operator '+' (line 74) result_add_32310 = python_operator(stypy.reporting.localization.Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309) keyword_32311 = result_add_32310 # Getting the type of 'lsoda_src' (line 75) lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 75, 34), 'lsoda_src', False) # Getting the type of 'mach_src' (line 75) mach_src_32313 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 75, 46), 'mach_src', False) # Applying the binary operator '+' (line 75) result_add_32314 = python_operator(stypy.reporting.localization.Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313) keyword_32315 = result_add_32314 # Getting the type of 'lapack_opt' (line 76) lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 76, 27), 'lapack_opt', False) kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305, 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316} # Getting the type of 'config' (line 72) config_32300 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 72, 4), 'config', False) # Obtaining the member 'add_extension' of a type (line 72) add_extension_32301 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 72, 4), config_32300, 'add_extension') # Calling add_extension(args, kwargs) (line 72) add_extension_call_result_32318 = invoke(stypy.reporting.localization.Localization(__file__, 72, 4), add_extension_32301, *[str_32302], **kwargs_32317) # Call to add_extension(...): (line 79) # Processing the call arguments (line 79) str_32321 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 79, 25), 'str', '_dop') # Processing the call keyword arguments (line 79) # Obtaining an instance of the builtin type 'list' (line 80) list_32322 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 80, 33), 'list') # Adding type elements to the builtin type 'list' instance (line 80) # Adding element type (line 80) str_32323 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 80, 34), 'str', 'dop.pyf') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 80, 33), list_32322, str_32323) keyword_32324 = list_32322 # Obtaining an instance of the builtin type 'list' (line 81) list_32325 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 81, 35), 'list') # Adding type elements to the builtin type 'list' instance (line 81) # Adding element type (line 81) str_32326 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 81, 36), 'str', 'dop') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 81, 35), list_32325, str_32326) keyword_32327 = list_32325 # Getting the type of 'dop_src' (line 82) dop_src_32328 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 82, 33), 'dop_src', False) keyword_32329 = dop_src_32328 kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324, 'depends': keyword_32329} # Getting the type of 'config' (line 79) config_32319 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 79, 4), 'config', False) # Obtaining the member 'add_extension' of a type (line 79) add_extension_32320 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 79, 4), config_32319, 'add_extension') # Calling add_extension(args, kwargs) (line 79) add_extension_call_result_32331 = invoke(stypy.reporting.localization.Localization(__file__, 79, 4), add_extension_32320, *[str_32321], **kwargs_32330) # Call to add_extension(...): (line 84) # Processing the call arguments (line 84) str_32334 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 84, 25), 'str', '_test_multivariate') # Processing the call keyword arguments (line 84) # Getting the type of 'quadpack_test_src' (line 85) quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 85, 33), 'quadpack_test_src', False) keyword_32336 = quadpack_test_src_32335 kwargs_32337 = {'sources': keyword_32336} # Getting the type of 'config' (line 84) config_32332 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 84, 4), 'config', False) # Obtaining the member 'add_extension' of a type (line 84) add_extension_32333 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 84, 4), config_32332, 'add_extension') # Calling add_extension(args, kwargs) (line 84) add_extension_call_result_32338 = invoke(stypy.reporting.localization.Localization(__file__, 84, 4), add_extension_32333, *[str_32334], **kwargs_32337) # Call to add_extension(...): (line 88) # Processing the call arguments (line 88) str_32341 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 88, 25), 'str', '_test_odeint_banded') # Processing the call keyword arguments (line 88) # Getting the type of 'odeint_banded_test_src' (line 89) odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 89, 33), 'odeint_banded_test_src', False) keyword_32343 = odeint_banded_test_src_32342 # Obtaining an instance of the builtin type 'list' (line 90) list_32344 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 90, 35), 'list') # Adding type elements to the builtin type 'list' instance (line 90) # Adding element type (line 90) str_32345 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 90, 36), 'str', 'lsoda') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 90, 35), list_32344, str_32345) # Adding element type (line 90) str_32346 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 90, 45), 'str', 'mach') add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 90, 35), list_32344, str_32346) # Getting the type of 'lapack_libs' (line 90) lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 90, 55), 'lapack_libs', False) # Applying the binary operator '+' (line 90) result_add_32348 = python_operator(stypy.reporting.localization.Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347) keyword_32349 = result_add_32348 # Getting the type of 'lsoda_src' (line 91) lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 91, 34), 'lsoda_src', False) # Getting the type of 'mach_src' (line 91) mach_src_32351 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 91, 46), 'mach_src', False) # Applying the binary operator '+' (line 91) result_add_32352 = python_operator(stypy.reporting.localization.Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351) keyword_32353 = result_add_32352 # Getting the type of 'lapack_opt' (line 92) lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 92, 27), 'lapack_opt', False) kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343, 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354} # Getting the type of 'config' (line 88) config_32339 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 88, 4), 'config', False) # Obtaining the member 'add_extension' of a type (line 88) add_extension_32340 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 88, 4), config_32339, 'add_extension') # Calling add_extension(args, kwargs) (line 88) add_extension_call_result_32356 = invoke(stypy.reporting.localization.Localization(__file__, 88, 4), add_extension_32340, *[str_32341], **kwargs_32355) # Call to add_subpackage(...): (line 94) # Processing the call arguments (line 94) str_32359 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 94, 26), 'str', '_ivp') # Processing the call keyword arguments (line 94) kwargs_32360 = {} # Getting the type of 'config' (line 94) config_32357 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 94, 4), 'config', False) # Obtaining the member 'add_subpackage' of a type (line 94) add_subpackage_32358 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 94, 4), config_32357, 'add_subpackage') # Calling add_subpackage(args, kwargs) (line 94) add_subpackage_call_result_32361 = invoke(stypy.reporting.localization.Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359], **kwargs_32360) # Call to add_data_dir(...): (line 96) # Processing the call arguments (line 96) str_32364 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 96, 24), 'str', 'tests') # Processing the call keyword arguments (line 96) kwargs_32365 = {} # Getting the type of 'config' (line 96) config_32362 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 96, 4), 'config', False) # Obtaining the member 'add_data_dir' of a type (line 96) add_data_dir_32363 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 96, 4), config_32362, 'add_data_dir') # Calling add_data_dir(args, kwargs) (line 96) add_data_dir_call_result_32366 = invoke(stypy.reporting.localization.Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], **kwargs_32365) # Getting the type of 'config' (line 97) config_32367 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 97, 11), 'config') # Assigning a type to the variable 'stypy_return_type' (line 97) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 97, 4), 'stypy_return_type', config_32367) # ################# End of 'configuration(...)' code ################## # Teardown call information teardown_call_information(localization, arguments) # Storing the return type of function 'configuration' in the type store # Getting the type of 'stypy_return_type' (line 9) stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 9, 0), 'stypy_return_type') module_type_store.store_return_type_of_current_context(stypy_return_type_32368) # Destroy the current context module_type_store = module_type_store.close_function_context() # Return type of the function 'configuration' return stypy_return_type_32368 # Assigning a type to the variable 'configuration' (line 9) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 9, 0), 'configuration', configuration) if (__name__ == '__main__'): stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 101, 4)) # 'from numpy.distutils.core import setup' statement (line 101) update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/') import_32369 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core') if (type(import_32369) is not StypyTypeError): if (import_32369 != 'pyd_module'): __import__(import_32369) sys_modules_32370 = sys.modules[import_32369] import_from_module(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core', sys_modules_32370.module_type_store, module_type_store, ['setup']) nest_module(stypy.reporting.localization.Localization(__file__, 101, 4), __file__, sys_modules_32370, sys_modules_32370.module_type_store, module_type_store) else: from numpy.distutils.core import setup import_from_module(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core', None, module_type_store, ['setup'], [setup]) else: # Assigning a type to the variable 'numpy.distutils.core' (line 101) module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core', import_32369) remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/') # Call to setup(...): (line 102) # Processing the call keyword arguments (line 102) # Call to todict(...): (line 102) # Processing the call keyword arguments (line 102) kwargs_32378 = {} # Call to configuration(...): (line 102) # Processing the call keyword arguments (line 102) str_32373 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 102, 35), 'str', '') keyword_32374 = str_32373 kwargs_32375 = {'top_path': keyword_32374} # Getting the type of 'configuration' (line 102) configuration_32372 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 102, 12), 'configuration', False) # Calling configuration(args, kwargs) (line 102) configuration_call_result_32376 = invoke(stypy.reporting.localization.Localization(__file__, 102, 12), configuration_32372, *[], **kwargs_32375) # Obtaining the member 'todict' of a type (line 102) todict_32377 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 102, 12), configuration_call_result_32376, 'todict') # Calling todict(args, kwargs) (line 102) todict_call_result_32379 = invoke(stypy.reporting.localization.Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378) kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379} # Getting the type of 'setup' (line 102) setup_32371 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 102, 4), 'setup', False) # Calling setup(args, kwargs) (line 102) setup_call_result_32381 = invoke(stypy.reporting.localization.Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380) # ################# End of the type inference program ################## module_errors = stypy.errors.type_error.StypyTypeError.get_error_msgs() module_warnings = stypy.errors.type_warning.TypeWarning.get_warning_msgs()
flexible
{ "blob_id": "4453b8176cda60a3a8f4800860b87bddfdb6cafa", "index": 7963, "step-1": "<mask token>\n\n\n@norecursion\ndef configuration(localization, *varargs, **kwargs):\n global module_type_store\n str_32070 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 9, 33), 'str', '')\n None_32071 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 9, 45), 'None')\n defaults = [str_32070, None_32071]\n module_type_store = module_type_store.open_function_context('configuration'\n , 9, 0, False)\n configuration.stypy_localization = localization\n configuration.stypy_type_of_self = None\n configuration.stypy_type_store = module_type_store\n configuration.stypy_function_name = 'configuration'\n configuration.stypy_param_names_list = ['parent_package', 'top_path']\n configuration.stypy_varargs_param_name = None\n configuration.stypy_kwargs_param_name = None\n configuration.stypy_call_defaults = defaults\n configuration.stypy_call_varargs = varargs\n configuration.stypy_call_kwargs = kwargs\n arguments = process_argument_values(localization, None,\n module_type_store, 'configuration', ['parent_package', 'top_path'],\n None, None, defaults, varargs, kwargs)\n if is_error_type(arguments):\n module_type_store = module_type_store.close_function_context()\n return arguments\n init_call_information(module_type_store, 'configuration', localization,\n ['parent_package', 'top_path'], arguments)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 0, 0), 'stypy_return_type', None)\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 10, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32072 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util'\n )\n if type(import_32072) is not StypyTypeError:\n if import_32072 != 'pyd_module':\n __import__(import_32072)\n sys_modules_32073 = sys.modules[import_32072]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util',\n sys_modules_32073.module_type_store, module_type_store, [\n 'Configuration'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 10, 4), __file__, sys_modules_32073, sys_modules_32073.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.misc_util import Configuration\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util', None,\n module_type_store, ['Configuration'], [Configuration])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 10, 4), 'numpy.distutils.misc_util',\n import_32072)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 11, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32074 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 11, 4),\n 'numpy.distutils.system_info')\n if type(import_32074) is not StypyTypeError:\n if import_32074 != 'pyd_module':\n __import__(import_32074)\n sys_modules_32075 = sys.modules[import_32074]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info',\n sys_modules_32075.module_type_store, module_type_store, [\n 'get_info'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 11, 4), __file__, sys_modules_32075, sys_modules_32075.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.system_info import get_info\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info', None,\n module_type_store, ['get_info'], [get_info])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 11, 4), 'numpy.distutils.system_info',\n import_32074)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n str_32077 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 12, 27), 'str', 'integrate')\n parent_package_32078 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 40), 'parent_package', False)\n top_path_32079 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 56), 'top_path', False)\n kwargs_32080 = {}\n Configuration_32076 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 13), 'Configuration', False)\n Configuration_call_result_32081 = invoke(stypy.reporting.localization.\n Localization(__file__, 12, 13), Configuration_32076, *[str_32077,\n parent_package_32078, top_path_32079], **kwargs_32080)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 12, 4), 'config', Configuration_call_result_32081)\n str_32084 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 31), 'str', 'lapack_opt')\n int_32085 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 60), 'int')\n keyword_32086 = int_32085\n kwargs_32087 = {'notfound_action': keyword_32086}\n get_info_32083 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 15, 22), 'get_info', False)\n get_info_call_result_32088 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 22), get_info_32083, *[str_32084], **\n kwargs_32087)\n kwargs_32089 = {}\n dict_32082 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 15, 17), 'dict', False)\n dict_call_result_32090 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 17), dict_32082, *[\n get_info_call_result_32088], **kwargs_32089)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 15, 4), 'lapack_opt', dict_call_result_32090)\n str_32093 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 33), 'str', 'libraries')\n list_32094 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 46), 'list')\n kwargs_32095 = {}\n lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 18, 18), 'lapack_opt', False)\n pop_32092 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop')\n pop_call_result_32096 = invoke(stypy.reporting.localization.\n Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094],\n **kwargs_32095)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 18, 4), 'lapack_libs', pop_call_result_32096)\n list_32097 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 15), 'list')\n str_32099 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 21), 'str', 'mach')\n str_32100 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 28), 'str', '*.f')\n kwargs_32101 = {}\n join_32098 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 20, 16), 'join', False)\n join_call_result_32102 = invoke(stypy.reporting.localization.\n Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100],\n **kwargs_32101)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 20, 15), list_32097, join_call_result_32102)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 20, 4), 'mach_src', list_32097)\n list_32103 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 19), 'list')\n str_32105 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 25), 'str', 'quadpack')\n str_32106 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 37), 'str', '*.f')\n kwargs_32107 = {}\n join_32104 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 21, 20), 'join', False)\n join_call_result_32108 = invoke(stypy.reporting.localization.\n Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106],\n **kwargs_32107)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 21, 19), list_32103, join_call_result_32108)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 21, 4), 'quadpack_src', list_32103)\n list_32114 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 47), 'list')\n str_32115 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32115)\n str_32116 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 23), 'str', 'bnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32116)\n str_32117 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 34), 'str', 'cfode.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32117)\n str_32118 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 8), 'str', 'ewset.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32118)\n str_32119 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 19), 'str', 'fnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32119)\n str_32120 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 30), 'str', 'intdy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32120)\n str_32121 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 8), 'str', 'lsoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32121)\n str_32122 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 19), 'str', 'prja.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32122)\n str_32123 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 29), 'str', 'solsy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32123)\n str_32124 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 40), 'str', 'srcma.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32124)\n str_32125 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 8), 'str', 'stoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32125)\n str_32126 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32126)\n str_32127 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32127)\n str_32128 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 43), 'str', 'xsetf.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32128)\n str_32129 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 27, 8), 'str', 'xsetun.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32129)\n comprehension_32130 = get_contained_elements_type(stypy.reporting.\n localization.Localization(__file__, 22, 17), list_32114)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 17), 'fn', comprehension_32130)\n str_32110 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 22), 'str', 'odepack')\n fn_32111 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 22, 33), 'fn', False)\n kwargs_32112 = {}\n join_32109 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 22, 17), 'join', False)\n join_call_result_32113 = invoke(stypy.reporting.localization.\n Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111],\n **kwargs_32112)\n list_32131 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 17), 'list')\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 17), list_32131, join_call_result_32113)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 4), 'lsoda_src', list_32131)\n list_32132 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 15), 'list')\n str_32134 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 21), 'str', 'odepack')\n str_32135 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 32), 'str', 'vode.f')\n kwargs_32136 = {}\n join_32133 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 16), 'join', False)\n join_call_result_32137 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135],\n **kwargs_32136)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32137)\n str_32139 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 48), 'str', 'odepack')\n str_32140 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 59), 'str', 'zvode.f')\n kwargs_32141 = {}\n join_32138 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 43), 'join', False)\n join_call_result_32142 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140],\n **kwargs_32141)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32142)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 28, 4), 'vode_src', list_32132)\n list_32143 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 14), 'list')\n str_32145 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 20), 'str', 'dop')\n str_32146 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 26), 'str', '*.f')\n kwargs_32147 = {}\n join_32144 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 29, 15), 'join', False)\n join_call_result_32148 = invoke(stypy.reporting.localization.\n Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146],\n **kwargs_32147)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 29, 14), list_32143, join_call_result_32148)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 29, 4), 'dop_src', list_32143)\n list_32149 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 24), 'list')\n str_32151 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 30), 'str', 'tests')\n str_32152 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 38), 'str',\n '_test_multivariate.c')\n kwargs_32153 = {}\n join_32150 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 30, 25), 'join', False)\n join_call_result_32154 = invoke(stypy.reporting.localization.\n Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152],\n **kwargs_32153)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 30, 24), list_32149, join_call_result_32154)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 30, 4), 'quadpack_test_src', list_32149)\n list_32155 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 29), 'list')\n str_32157 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 35), 'str', 'tests')\n str_32158 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f')\n kwargs_32159 = {}\n join_32156 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 31, 30), 'join', False)\n join_call_result_32160 = invoke(stypy.reporting.localization.\n Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158],\n **kwargs_32159)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 31, 29), list_32155, join_call_result_32160)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 31, 4), 'odeint_banded_test_src', list_32155)\n str_32163 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 33, 23), 'str', 'mach')\n mach_src_32164 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 39), 'mach_src', False)\n keyword_32165 = mach_src_32164\n dict_32166 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 33), 'dict')\n str_32167 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 34), 'str', 'noopt')\n tuple_32168 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 43), 'tuple')\n file___32169 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 34, 43), '__file__', False)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, file___32169)\n int_32170 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 52), 'int')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, int_32170)\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 33), dict_32166, (str_32167, tuple_32168))\n keyword_32171 = dict_32166\n kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171}\n config_32161 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 4), 'config', False)\n add_library_32162 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 33, 4), config_32161,\n 'add_library')\n add_library_call_result_32173 = invoke(stypy.reporting.localization.\n Localization(__file__, 33, 4), add_library_32162, *[str_32163], **\n kwargs_32172)\n str_32176 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 35, 23), 'str', 'quadpack')\n quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 43), 'quadpack_src', False)\n keyword_32178 = quadpack_src_32177\n kwargs_32179 = {'sources': keyword_32178}\n config_32174 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 4), 'config', False)\n add_library_32175 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 35, 4), config_32174,\n 'add_library')\n add_library_call_result_32180 = invoke(stypy.reporting.localization.\n Localization(__file__, 35, 4), add_library_32175, *[str_32176], **\n kwargs_32179)\n str_32183 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 36, 23), 'str', 'lsoda')\n lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 40), 'lsoda_src', False)\n keyword_32185 = lsoda_src_32184\n kwargs_32186 = {'sources': keyword_32185}\n config_32181 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 4), 'config', False)\n add_library_32182 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 36, 4), config_32181,\n 'add_library')\n add_library_call_result_32187 = invoke(stypy.reporting.localization.\n Localization(__file__, 36, 4), add_library_32182, *[str_32183], **\n kwargs_32186)\n str_32190 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 37, 23), 'str', 'vode')\n vode_src_32191 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 39), 'vode_src', False)\n keyword_32192 = vode_src_32191\n kwargs_32193 = {'sources': keyword_32192}\n config_32188 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 4), 'config', False)\n add_library_32189 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 37, 4), config_32188,\n 'add_library')\n add_library_call_result_32194 = invoke(stypy.reporting.localization.\n Localization(__file__, 37, 4), add_library_32189, *[str_32190], **\n kwargs_32193)\n str_32197 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 38, 23), 'str', 'dop')\n dop_src_32198 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 38), 'dop_src', False)\n keyword_32199 = dop_src_32198\n kwargs_32200 = {'sources': keyword_32199}\n config_32195 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 4), 'config', False)\n add_library_32196 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 38, 4), config_32195,\n 'add_library')\n add_library_call_result_32201 = invoke(stypy.reporting.localization.\n Localization(__file__, 38, 4), add_library_32196, *[str_32197], **\n kwargs_32200)\n list_32202 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 19), 'list')\n file___32207 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 42, 41), '__file__', False)\n kwargs_32208 = {}\n os_32204 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 42, 25), 'os', False)\n path_32205 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), os_32204, 'path')\n dirname_32206 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), path_32205, 'dirname')\n dirname_call_result_32209 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 25), dirname_32206, *[file___32207], **\n kwargs_32208)\n str_32210 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 52), 'str', '..')\n str_32211 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 58), 'str', '_lib')\n str_32212 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 66), 'str', 'src')\n kwargs_32213 = {}\n join_32203 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 42, 20), 'join', False)\n join_call_result_32214 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 20), join_32203, *[\n dirname_call_result_32209, str_32210, str_32211, str_32212], **\n kwargs_32213)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 42, 19), list_32202, join_call_result_32214)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 42, 4), 'include_dirs', list_32202)\n str_32215 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 43, 7), 'str', 'include_dirs')\n lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 43, 25), 'lapack_opt')\n result_contains_32217 = python_operator(stypy.reporting.localization.\n Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216)\n if_condition_32218 = is_suitable_condition(stypy.reporting.localization\n .Localization(__file__, 43, 4), result_contains_32217)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 43, 4), 'if_condition_32218', if_condition_32218)\n module_type_store = SSAContext.create_ssa_context(module_type_store, 'if')\n lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 44, 26), 'lapack_opt', False)\n kwargs_32221 = {}\n dict_32219 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 44, 21), 'dict', False)\n dict_call_result_32222 = invoke(stypy.reporting.localization.\n Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], **\n kwargs_32221)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 44, 8), 'lapack_opt', dict_call_result_32222)\n str_32227 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 45, 43), 'str', 'include_dirs')\n kwargs_32228 = {}\n lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 28), 'lapack_opt', False)\n pop_32226 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop')\n pop_call_result_32229 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228\n )\n kwargs_32230 = {}\n include_dirs_32223 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 8), 'include_dirs', False)\n extend_32224 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 8), include_dirs_32223,\n 'extend')\n extend_call_result_32231 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 8), extend_32224, *[\n pop_call_result_32229], **kwargs_32230)\n module_type_store = module_type_store.join_ssa_context()\n str_32234 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 47, 25), 'str', '_quadpack')\n list_32235 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 33), 'list')\n str_32236 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c'\n )\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 48, 33), list_32235, str_32236)\n keyword_32237 = list_32235\n list_32238 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 35), 'list')\n str_32239 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 36), 'str', 'quadpack')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32239)\n str_32240 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 48), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32240)\n lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 49, 58), 'lapack_libs', False)\n result_add_32242 = python_operator(stypy.reporting.localization.\n Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241)\n keyword_32243 = result_add_32242\n list_32244 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 34), 'list')\n str_32245 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 35), 'str', '__quadpack.h')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 50, 34), list_32244, str_32245)\n quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 36), 'quadpack_src', False)\n result_add_32247 = python_operator(stypy.reporting.localization.\n Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246)\n mach_src_32248 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 51), 'mach_src', False)\n result_add_32249 = python_operator(stypy.reporting.localization.\n Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248)\n keyword_32250 = result_add_32249\n include_dirs_32251 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 52, 38), 'include_dirs', False)\n keyword_32252 = include_dirs_32251\n lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 53, 27), 'lapack_opt', False)\n kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237,\n 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253,\n 'include_dirs': keyword_32252}\n config_32232 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 47, 4), 'config', False)\n add_extension_32233 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 47, 4), config_32232,\n 'add_extension')\n add_extension_call_result_32255 = invoke(stypy.reporting.localization.\n Localization(__file__, 47, 4), add_extension_32233, *[str_32234],\n **kwargs_32254)\n kwargs_32258 = {}\n lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 56, 19), 'lapack_opt', False)\n copy_32257 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy')\n copy_call_result_32259 = invoke(stypy.reporting.localization.\n Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 56, 4), 'odepack_opts', copy_call_result_32259)\n numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False)\n kwargs_32263 = {}\n odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 4), 'odepack_opts', False)\n update_32261 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 57, 4), odepack_opts_32260,\n 'update')\n update_call_result_32264 = invoke(stypy.reporting.localization.\n Localization(__file__, 57, 4), update_32261, *[\n numpy_nodepr_api_32262], **kwargs_32263)\n str_32267 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 58, 25), 'str', '_odepack')\n list_32268 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 33), 'list')\n str_32269 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 59, 33), list_32268, str_32269)\n keyword_32270 = list_32268\n list_32271 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 35), 'list')\n str_32272 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32272)\n str_32273 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32273)\n lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 60, 55), 'lapack_libs', False)\n result_add_32275 = python_operator(stypy.reporting.localization.\n Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274)\n keyword_32276 = result_add_32275\n lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 34), 'lsoda_src', False)\n mach_src_32278 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 46), 'mach_src', False)\n result_add_32279 = python_operator(stypy.reporting.localization.\n Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278)\n keyword_32280 = result_add_32279\n odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 62, 27), 'odepack_opts', False)\n kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270,\n 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281}\n config_32265 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 58, 4), 'config', False)\n add_extension_32266 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 58, 4), config_32265,\n 'add_extension')\n add_extension_call_result_32283 = invoke(stypy.reporting.localization.\n Localization(__file__, 58, 4), add_extension_32266, *[str_32267],\n **kwargs_32282)\n str_32286 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 65, 25), 'str', 'vode')\n list_32287 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 33), 'list')\n str_32288 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 34), 'str', 'vode.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 66, 33), list_32287, str_32288)\n keyword_32289 = list_32287\n list_32290 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 35), 'list')\n str_32291 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 36), 'str', 'vode')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 67, 35), list_32290, str_32291)\n lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 67, 46), 'lapack_libs', False)\n result_add_32293 = python_operator(stypy.reporting.localization.\n Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292)\n keyword_32294 = result_add_32293\n vode_src_32295 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 68, 33), 'vode_src', False)\n keyword_32296 = vode_src_32295\n lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 69, 27), 'lapack_opt', False)\n kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289,\n 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297}\n config_32284 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 65, 4), 'config', False)\n add_extension_32285 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 65, 4), config_32284,\n 'add_extension')\n add_extension_call_result_32299 = invoke(stypy.reporting.localization.\n Localization(__file__, 65, 4), add_extension_32285, *[str_32286],\n **kwargs_32298)\n str_32302 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 72, 25), 'str', 'lsoda')\n list_32303 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 33), 'list')\n str_32304 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 73, 33), list_32303, str_32304)\n keyword_32305 = list_32303\n list_32306 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 35), 'list')\n str_32307 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32307)\n str_32308 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32308)\n lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 74, 55), 'lapack_libs', False)\n result_add_32310 = python_operator(stypy.reporting.localization.\n Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309)\n keyword_32311 = result_add_32310\n lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 34), 'lsoda_src', False)\n mach_src_32313 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 46), 'mach_src', False)\n result_add_32314 = python_operator(stypy.reporting.localization.\n Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313)\n keyword_32315 = result_add_32314\n lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 76, 27), 'lapack_opt', False)\n kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305,\n 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316}\n config_32300 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 72, 4), 'config', False)\n add_extension_32301 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 72, 4), config_32300,\n 'add_extension')\n add_extension_call_result_32318 = invoke(stypy.reporting.localization.\n Localization(__file__, 72, 4), add_extension_32301, *[str_32302],\n **kwargs_32317)\n str_32321 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 79, 25), 'str', '_dop')\n list_32322 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 33), 'list')\n str_32323 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 34), 'str', 'dop.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 80, 33), list_32322, str_32323)\n keyword_32324 = list_32322\n list_32325 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 35), 'list')\n str_32326 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 36), 'str', 'dop')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 81, 35), list_32325, str_32326)\n keyword_32327 = list_32325\n dop_src_32328 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 82, 33), 'dop_src', False)\n keyword_32329 = dop_src_32328\n kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324,\n 'depends': keyword_32329}\n config_32319 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 79, 4), 'config', False)\n add_extension_32320 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 79, 4), config_32319,\n 'add_extension')\n add_extension_call_result_32331 = invoke(stypy.reporting.localization.\n Localization(__file__, 79, 4), add_extension_32320, *[str_32321],\n **kwargs_32330)\n str_32334 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 84, 25), 'str',\n '_test_multivariate')\n quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 85, 33), 'quadpack_test_src', \n False)\n keyword_32336 = quadpack_test_src_32335\n kwargs_32337 = {'sources': keyword_32336}\n config_32332 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 84, 4), 'config', False)\n add_extension_32333 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 84, 4), config_32332,\n 'add_extension')\n add_extension_call_result_32338 = invoke(stypy.reporting.localization.\n Localization(__file__, 84, 4), add_extension_32333, *[str_32334],\n **kwargs_32337)\n str_32341 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 88, 25), 'str',\n '_test_odeint_banded')\n odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy.\n reporting.localization.Localization(__file__, 89, 33),\n 'odeint_banded_test_src', False)\n keyword_32343 = odeint_banded_test_src_32342\n list_32344 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 35), 'list')\n str_32345 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32345)\n str_32346 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32346)\n lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 90, 55), 'lapack_libs', False)\n result_add_32348 = python_operator(stypy.reporting.localization.\n Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347)\n keyword_32349 = result_add_32348\n lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 34), 'lsoda_src', False)\n mach_src_32351 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 46), 'mach_src', False)\n result_add_32352 = python_operator(stypy.reporting.localization.\n Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351)\n keyword_32353 = result_add_32352\n lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 92, 27), 'lapack_opt', False)\n kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343,\n 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354}\n config_32339 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 88, 4), 'config', False)\n add_extension_32340 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 88, 4), config_32339,\n 'add_extension')\n add_extension_call_result_32356 = invoke(stypy.reporting.localization.\n Localization(__file__, 88, 4), add_extension_32340, *[str_32341],\n **kwargs_32355)\n str_32359 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 94, 26), 'str', '_ivp')\n kwargs_32360 = {}\n config_32357 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 94, 4), 'config', False)\n add_subpackage_32358 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 94, 4), config_32357,\n 'add_subpackage')\n add_subpackage_call_result_32361 = invoke(stypy.reporting.localization.\n Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359],\n **kwargs_32360)\n str_32364 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 96, 24), 'str', 'tests')\n kwargs_32365 = {}\n config_32362 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 96, 4), 'config', False)\n add_data_dir_32363 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 96, 4), config_32362,\n 'add_data_dir')\n add_data_dir_call_result_32366 = invoke(stypy.reporting.localization.\n Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], **\n kwargs_32365)\n config_32367 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 97, 11), 'config')\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 97, 4), 'stypy_return_type', config_32367)\n teardown_call_information(localization, arguments)\n stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 9, 0), 'stypy_return_type')\n module_type_store.store_return_type_of_current_context(\n stypy_return_type_32368)\n module_type_store = module_type_store.close_function_context()\n return stypy_return_type_32368\n\n\n<mask token>\n", "step-2": "<mask token>\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 3, 0))\n<mask token>\nimport_module(stypy.reporting.localization.Localization(__file__, 3, 0),\n 'os', os, module_type_store)\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 4, 0))\nupdate_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n<mask token>\nif type(import_32066) is not StypyTypeError:\n if import_32066 != 'pyd_module':\n __import__(import_32066)\n sys_modules_32067 = sys.modules[import_32066]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 4, 0), 'os.path', sys_modules_32067.module_type_store,\n module_type_store, ['join'])\n nest_module(stypy.reporting.localization.Localization(__file__, 4, \n 0), __file__, sys_modules_32067, sys_modules_32067.\n module_type_store, module_type_store)\n else:\n from os.path import join\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 4, 0), 'os.path', None, module_type_store, ['join'],\n [join])\nelse:\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 4, 0), 'os.path', import_32066)\nremove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 6, 0))\nupdate_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n<mask token>\nif type(import_32068) is not StypyTypeError:\n if import_32068 != 'pyd_module':\n __import__(import_32068)\n sys_modules_32069 = sys.modules[import_32068]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 6, 0), 'scipy._build_utils', sys_modules_32069.\n module_type_store, module_type_store, ['numpy_nodepr_api'])\n nest_module(stypy.reporting.localization.Localization(__file__, 6, \n 0), __file__, sys_modules_32069, sys_modules_32069.\n module_type_store, module_type_store)\n else:\n from scipy._build_utils import numpy_nodepr_api\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 6, 0), 'scipy._build_utils', None, module_type_store,\n ['numpy_nodepr_api'], [numpy_nodepr_api])\nelse:\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 6, 0), 'scipy._build_utils', import_32068)\nremove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n\n\n@norecursion\ndef configuration(localization, *varargs, **kwargs):\n global module_type_store\n str_32070 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 9, 33), 'str', '')\n None_32071 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 9, 45), 'None')\n defaults = [str_32070, None_32071]\n module_type_store = module_type_store.open_function_context('configuration'\n , 9, 0, False)\n configuration.stypy_localization = localization\n configuration.stypy_type_of_self = None\n configuration.stypy_type_store = module_type_store\n configuration.stypy_function_name = 'configuration'\n configuration.stypy_param_names_list = ['parent_package', 'top_path']\n configuration.stypy_varargs_param_name = None\n configuration.stypy_kwargs_param_name = None\n configuration.stypy_call_defaults = defaults\n configuration.stypy_call_varargs = varargs\n configuration.stypy_call_kwargs = kwargs\n arguments = process_argument_values(localization, None,\n module_type_store, 'configuration', ['parent_package', 'top_path'],\n None, None, defaults, varargs, kwargs)\n if is_error_type(arguments):\n module_type_store = module_type_store.close_function_context()\n return arguments\n init_call_information(module_type_store, 'configuration', localization,\n ['parent_package', 'top_path'], arguments)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 0, 0), 'stypy_return_type', None)\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 10, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32072 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util'\n )\n if type(import_32072) is not StypyTypeError:\n if import_32072 != 'pyd_module':\n __import__(import_32072)\n sys_modules_32073 = sys.modules[import_32072]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util',\n sys_modules_32073.module_type_store, module_type_store, [\n 'Configuration'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 10, 4), __file__, sys_modules_32073, sys_modules_32073.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.misc_util import Configuration\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util', None,\n module_type_store, ['Configuration'], [Configuration])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 10, 4), 'numpy.distutils.misc_util',\n import_32072)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 11, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32074 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 11, 4),\n 'numpy.distutils.system_info')\n if type(import_32074) is not StypyTypeError:\n if import_32074 != 'pyd_module':\n __import__(import_32074)\n sys_modules_32075 = sys.modules[import_32074]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info',\n sys_modules_32075.module_type_store, module_type_store, [\n 'get_info'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 11, 4), __file__, sys_modules_32075, sys_modules_32075.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.system_info import get_info\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info', None,\n module_type_store, ['get_info'], [get_info])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 11, 4), 'numpy.distutils.system_info',\n import_32074)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n str_32077 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 12, 27), 'str', 'integrate')\n parent_package_32078 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 40), 'parent_package', False)\n top_path_32079 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 56), 'top_path', False)\n kwargs_32080 = {}\n Configuration_32076 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 13), 'Configuration', False)\n Configuration_call_result_32081 = invoke(stypy.reporting.localization.\n Localization(__file__, 12, 13), Configuration_32076, *[str_32077,\n parent_package_32078, top_path_32079], **kwargs_32080)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 12, 4), 'config', Configuration_call_result_32081)\n str_32084 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 31), 'str', 'lapack_opt')\n int_32085 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 60), 'int')\n keyword_32086 = int_32085\n kwargs_32087 = {'notfound_action': keyword_32086}\n get_info_32083 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 15, 22), 'get_info', False)\n get_info_call_result_32088 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 22), get_info_32083, *[str_32084], **\n kwargs_32087)\n kwargs_32089 = {}\n dict_32082 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 15, 17), 'dict', False)\n dict_call_result_32090 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 17), dict_32082, *[\n get_info_call_result_32088], **kwargs_32089)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 15, 4), 'lapack_opt', dict_call_result_32090)\n str_32093 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 33), 'str', 'libraries')\n list_32094 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 46), 'list')\n kwargs_32095 = {}\n lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 18, 18), 'lapack_opt', False)\n pop_32092 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop')\n pop_call_result_32096 = invoke(stypy.reporting.localization.\n Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094],\n **kwargs_32095)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 18, 4), 'lapack_libs', pop_call_result_32096)\n list_32097 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 15), 'list')\n str_32099 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 21), 'str', 'mach')\n str_32100 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 28), 'str', '*.f')\n kwargs_32101 = {}\n join_32098 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 20, 16), 'join', False)\n join_call_result_32102 = invoke(stypy.reporting.localization.\n Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100],\n **kwargs_32101)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 20, 15), list_32097, join_call_result_32102)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 20, 4), 'mach_src', list_32097)\n list_32103 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 19), 'list')\n str_32105 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 25), 'str', 'quadpack')\n str_32106 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 37), 'str', '*.f')\n kwargs_32107 = {}\n join_32104 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 21, 20), 'join', False)\n join_call_result_32108 = invoke(stypy.reporting.localization.\n Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106],\n **kwargs_32107)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 21, 19), list_32103, join_call_result_32108)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 21, 4), 'quadpack_src', list_32103)\n list_32114 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 47), 'list')\n str_32115 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32115)\n str_32116 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 23), 'str', 'bnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32116)\n str_32117 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 34), 'str', 'cfode.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32117)\n str_32118 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 8), 'str', 'ewset.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32118)\n str_32119 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 19), 'str', 'fnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32119)\n str_32120 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 30), 'str', 'intdy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32120)\n str_32121 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 8), 'str', 'lsoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32121)\n str_32122 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 19), 'str', 'prja.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32122)\n str_32123 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 29), 'str', 'solsy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32123)\n str_32124 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 40), 'str', 'srcma.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32124)\n str_32125 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 8), 'str', 'stoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32125)\n str_32126 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32126)\n str_32127 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32127)\n str_32128 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 43), 'str', 'xsetf.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32128)\n str_32129 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 27, 8), 'str', 'xsetun.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32129)\n comprehension_32130 = get_contained_elements_type(stypy.reporting.\n localization.Localization(__file__, 22, 17), list_32114)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 17), 'fn', comprehension_32130)\n str_32110 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 22), 'str', 'odepack')\n fn_32111 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 22, 33), 'fn', False)\n kwargs_32112 = {}\n join_32109 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 22, 17), 'join', False)\n join_call_result_32113 = invoke(stypy.reporting.localization.\n Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111],\n **kwargs_32112)\n list_32131 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 17), 'list')\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 17), list_32131, join_call_result_32113)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 4), 'lsoda_src', list_32131)\n list_32132 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 15), 'list')\n str_32134 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 21), 'str', 'odepack')\n str_32135 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 32), 'str', 'vode.f')\n kwargs_32136 = {}\n join_32133 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 16), 'join', False)\n join_call_result_32137 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135],\n **kwargs_32136)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32137)\n str_32139 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 48), 'str', 'odepack')\n str_32140 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 59), 'str', 'zvode.f')\n kwargs_32141 = {}\n join_32138 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 43), 'join', False)\n join_call_result_32142 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140],\n **kwargs_32141)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32142)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 28, 4), 'vode_src', list_32132)\n list_32143 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 14), 'list')\n str_32145 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 20), 'str', 'dop')\n str_32146 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 26), 'str', '*.f')\n kwargs_32147 = {}\n join_32144 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 29, 15), 'join', False)\n join_call_result_32148 = invoke(stypy.reporting.localization.\n Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146],\n **kwargs_32147)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 29, 14), list_32143, join_call_result_32148)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 29, 4), 'dop_src', list_32143)\n list_32149 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 24), 'list')\n str_32151 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 30), 'str', 'tests')\n str_32152 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 38), 'str',\n '_test_multivariate.c')\n kwargs_32153 = {}\n join_32150 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 30, 25), 'join', False)\n join_call_result_32154 = invoke(stypy.reporting.localization.\n Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152],\n **kwargs_32153)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 30, 24), list_32149, join_call_result_32154)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 30, 4), 'quadpack_test_src', list_32149)\n list_32155 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 29), 'list')\n str_32157 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 35), 'str', 'tests')\n str_32158 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f')\n kwargs_32159 = {}\n join_32156 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 31, 30), 'join', False)\n join_call_result_32160 = invoke(stypy.reporting.localization.\n Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158],\n **kwargs_32159)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 31, 29), list_32155, join_call_result_32160)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 31, 4), 'odeint_banded_test_src', list_32155)\n str_32163 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 33, 23), 'str', 'mach')\n mach_src_32164 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 39), 'mach_src', False)\n keyword_32165 = mach_src_32164\n dict_32166 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 33), 'dict')\n str_32167 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 34), 'str', 'noopt')\n tuple_32168 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 43), 'tuple')\n file___32169 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 34, 43), '__file__', False)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, file___32169)\n int_32170 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 52), 'int')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, int_32170)\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 33), dict_32166, (str_32167, tuple_32168))\n keyword_32171 = dict_32166\n kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171}\n config_32161 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 4), 'config', False)\n add_library_32162 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 33, 4), config_32161,\n 'add_library')\n add_library_call_result_32173 = invoke(stypy.reporting.localization.\n Localization(__file__, 33, 4), add_library_32162, *[str_32163], **\n kwargs_32172)\n str_32176 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 35, 23), 'str', 'quadpack')\n quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 43), 'quadpack_src', False)\n keyword_32178 = quadpack_src_32177\n kwargs_32179 = {'sources': keyword_32178}\n config_32174 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 4), 'config', False)\n add_library_32175 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 35, 4), config_32174,\n 'add_library')\n add_library_call_result_32180 = invoke(stypy.reporting.localization.\n Localization(__file__, 35, 4), add_library_32175, *[str_32176], **\n kwargs_32179)\n str_32183 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 36, 23), 'str', 'lsoda')\n lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 40), 'lsoda_src', False)\n keyword_32185 = lsoda_src_32184\n kwargs_32186 = {'sources': keyword_32185}\n config_32181 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 4), 'config', False)\n add_library_32182 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 36, 4), config_32181,\n 'add_library')\n add_library_call_result_32187 = invoke(stypy.reporting.localization.\n Localization(__file__, 36, 4), add_library_32182, *[str_32183], **\n kwargs_32186)\n str_32190 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 37, 23), 'str', 'vode')\n vode_src_32191 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 39), 'vode_src', False)\n keyword_32192 = vode_src_32191\n kwargs_32193 = {'sources': keyword_32192}\n config_32188 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 4), 'config', False)\n add_library_32189 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 37, 4), config_32188,\n 'add_library')\n add_library_call_result_32194 = invoke(stypy.reporting.localization.\n Localization(__file__, 37, 4), add_library_32189, *[str_32190], **\n kwargs_32193)\n str_32197 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 38, 23), 'str', 'dop')\n dop_src_32198 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 38), 'dop_src', False)\n keyword_32199 = dop_src_32198\n kwargs_32200 = {'sources': keyword_32199}\n config_32195 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 4), 'config', False)\n add_library_32196 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 38, 4), config_32195,\n 'add_library')\n add_library_call_result_32201 = invoke(stypy.reporting.localization.\n Localization(__file__, 38, 4), add_library_32196, *[str_32197], **\n kwargs_32200)\n list_32202 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 19), 'list')\n file___32207 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 42, 41), '__file__', False)\n kwargs_32208 = {}\n os_32204 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 42, 25), 'os', False)\n path_32205 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), os_32204, 'path')\n dirname_32206 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), path_32205, 'dirname')\n dirname_call_result_32209 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 25), dirname_32206, *[file___32207], **\n kwargs_32208)\n str_32210 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 52), 'str', '..')\n str_32211 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 58), 'str', '_lib')\n str_32212 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 66), 'str', 'src')\n kwargs_32213 = {}\n join_32203 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 42, 20), 'join', False)\n join_call_result_32214 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 20), join_32203, *[\n dirname_call_result_32209, str_32210, str_32211, str_32212], **\n kwargs_32213)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 42, 19), list_32202, join_call_result_32214)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 42, 4), 'include_dirs', list_32202)\n str_32215 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 43, 7), 'str', 'include_dirs')\n lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 43, 25), 'lapack_opt')\n result_contains_32217 = python_operator(stypy.reporting.localization.\n Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216)\n if_condition_32218 = is_suitable_condition(stypy.reporting.localization\n .Localization(__file__, 43, 4), result_contains_32217)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 43, 4), 'if_condition_32218', if_condition_32218)\n module_type_store = SSAContext.create_ssa_context(module_type_store, 'if')\n lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 44, 26), 'lapack_opt', False)\n kwargs_32221 = {}\n dict_32219 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 44, 21), 'dict', False)\n dict_call_result_32222 = invoke(stypy.reporting.localization.\n Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], **\n kwargs_32221)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 44, 8), 'lapack_opt', dict_call_result_32222)\n str_32227 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 45, 43), 'str', 'include_dirs')\n kwargs_32228 = {}\n lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 28), 'lapack_opt', False)\n pop_32226 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop')\n pop_call_result_32229 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228\n )\n kwargs_32230 = {}\n include_dirs_32223 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 8), 'include_dirs', False)\n extend_32224 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 8), include_dirs_32223,\n 'extend')\n extend_call_result_32231 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 8), extend_32224, *[\n pop_call_result_32229], **kwargs_32230)\n module_type_store = module_type_store.join_ssa_context()\n str_32234 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 47, 25), 'str', '_quadpack')\n list_32235 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 33), 'list')\n str_32236 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c'\n )\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 48, 33), list_32235, str_32236)\n keyword_32237 = list_32235\n list_32238 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 35), 'list')\n str_32239 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 36), 'str', 'quadpack')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32239)\n str_32240 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 48), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32240)\n lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 49, 58), 'lapack_libs', False)\n result_add_32242 = python_operator(stypy.reporting.localization.\n Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241)\n keyword_32243 = result_add_32242\n list_32244 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 34), 'list')\n str_32245 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 35), 'str', '__quadpack.h')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 50, 34), list_32244, str_32245)\n quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 36), 'quadpack_src', False)\n result_add_32247 = python_operator(stypy.reporting.localization.\n Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246)\n mach_src_32248 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 51), 'mach_src', False)\n result_add_32249 = python_operator(stypy.reporting.localization.\n Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248)\n keyword_32250 = result_add_32249\n include_dirs_32251 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 52, 38), 'include_dirs', False)\n keyword_32252 = include_dirs_32251\n lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 53, 27), 'lapack_opt', False)\n kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237,\n 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253,\n 'include_dirs': keyword_32252}\n config_32232 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 47, 4), 'config', False)\n add_extension_32233 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 47, 4), config_32232,\n 'add_extension')\n add_extension_call_result_32255 = invoke(stypy.reporting.localization.\n Localization(__file__, 47, 4), add_extension_32233, *[str_32234],\n **kwargs_32254)\n kwargs_32258 = {}\n lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 56, 19), 'lapack_opt', False)\n copy_32257 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy')\n copy_call_result_32259 = invoke(stypy.reporting.localization.\n Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 56, 4), 'odepack_opts', copy_call_result_32259)\n numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False)\n kwargs_32263 = {}\n odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 4), 'odepack_opts', False)\n update_32261 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 57, 4), odepack_opts_32260,\n 'update')\n update_call_result_32264 = invoke(stypy.reporting.localization.\n Localization(__file__, 57, 4), update_32261, *[\n numpy_nodepr_api_32262], **kwargs_32263)\n str_32267 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 58, 25), 'str', '_odepack')\n list_32268 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 33), 'list')\n str_32269 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 59, 33), list_32268, str_32269)\n keyword_32270 = list_32268\n list_32271 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 35), 'list')\n str_32272 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32272)\n str_32273 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32273)\n lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 60, 55), 'lapack_libs', False)\n result_add_32275 = python_operator(stypy.reporting.localization.\n Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274)\n keyword_32276 = result_add_32275\n lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 34), 'lsoda_src', False)\n mach_src_32278 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 46), 'mach_src', False)\n result_add_32279 = python_operator(stypy.reporting.localization.\n Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278)\n keyword_32280 = result_add_32279\n odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 62, 27), 'odepack_opts', False)\n kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270,\n 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281}\n config_32265 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 58, 4), 'config', False)\n add_extension_32266 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 58, 4), config_32265,\n 'add_extension')\n add_extension_call_result_32283 = invoke(stypy.reporting.localization.\n Localization(__file__, 58, 4), add_extension_32266, *[str_32267],\n **kwargs_32282)\n str_32286 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 65, 25), 'str', 'vode')\n list_32287 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 33), 'list')\n str_32288 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 34), 'str', 'vode.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 66, 33), list_32287, str_32288)\n keyword_32289 = list_32287\n list_32290 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 35), 'list')\n str_32291 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 36), 'str', 'vode')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 67, 35), list_32290, str_32291)\n lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 67, 46), 'lapack_libs', False)\n result_add_32293 = python_operator(stypy.reporting.localization.\n Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292)\n keyword_32294 = result_add_32293\n vode_src_32295 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 68, 33), 'vode_src', False)\n keyword_32296 = vode_src_32295\n lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 69, 27), 'lapack_opt', False)\n kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289,\n 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297}\n config_32284 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 65, 4), 'config', False)\n add_extension_32285 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 65, 4), config_32284,\n 'add_extension')\n add_extension_call_result_32299 = invoke(stypy.reporting.localization.\n Localization(__file__, 65, 4), add_extension_32285, *[str_32286],\n **kwargs_32298)\n str_32302 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 72, 25), 'str', 'lsoda')\n list_32303 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 33), 'list')\n str_32304 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 73, 33), list_32303, str_32304)\n keyword_32305 = list_32303\n list_32306 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 35), 'list')\n str_32307 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32307)\n str_32308 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32308)\n lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 74, 55), 'lapack_libs', False)\n result_add_32310 = python_operator(stypy.reporting.localization.\n Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309)\n keyword_32311 = result_add_32310\n lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 34), 'lsoda_src', False)\n mach_src_32313 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 46), 'mach_src', False)\n result_add_32314 = python_operator(stypy.reporting.localization.\n Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313)\n keyword_32315 = result_add_32314\n lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 76, 27), 'lapack_opt', False)\n kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305,\n 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316}\n config_32300 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 72, 4), 'config', False)\n add_extension_32301 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 72, 4), config_32300,\n 'add_extension')\n add_extension_call_result_32318 = invoke(stypy.reporting.localization.\n Localization(__file__, 72, 4), add_extension_32301, *[str_32302],\n **kwargs_32317)\n str_32321 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 79, 25), 'str', '_dop')\n list_32322 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 33), 'list')\n str_32323 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 34), 'str', 'dop.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 80, 33), list_32322, str_32323)\n keyword_32324 = list_32322\n list_32325 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 35), 'list')\n str_32326 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 36), 'str', 'dop')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 81, 35), list_32325, str_32326)\n keyword_32327 = list_32325\n dop_src_32328 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 82, 33), 'dop_src', False)\n keyword_32329 = dop_src_32328\n kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324,\n 'depends': keyword_32329}\n config_32319 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 79, 4), 'config', False)\n add_extension_32320 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 79, 4), config_32319,\n 'add_extension')\n add_extension_call_result_32331 = invoke(stypy.reporting.localization.\n Localization(__file__, 79, 4), add_extension_32320, *[str_32321],\n **kwargs_32330)\n str_32334 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 84, 25), 'str',\n '_test_multivariate')\n quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 85, 33), 'quadpack_test_src', \n False)\n keyword_32336 = quadpack_test_src_32335\n kwargs_32337 = {'sources': keyword_32336}\n config_32332 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 84, 4), 'config', False)\n add_extension_32333 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 84, 4), config_32332,\n 'add_extension')\n add_extension_call_result_32338 = invoke(stypy.reporting.localization.\n Localization(__file__, 84, 4), add_extension_32333, *[str_32334],\n **kwargs_32337)\n str_32341 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 88, 25), 'str',\n '_test_odeint_banded')\n odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy.\n reporting.localization.Localization(__file__, 89, 33),\n 'odeint_banded_test_src', False)\n keyword_32343 = odeint_banded_test_src_32342\n list_32344 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 35), 'list')\n str_32345 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32345)\n str_32346 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32346)\n lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 90, 55), 'lapack_libs', False)\n result_add_32348 = python_operator(stypy.reporting.localization.\n Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347)\n keyword_32349 = result_add_32348\n lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 34), 'lsoda_src', False)\n mach_src_32351 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 46), 'mach_src', False)\n result_add_32352 = python_operator(stypy.reporting.localization.\n Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351)\n keyword_32353 = result_add_32352\n lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 92, 27), 'lapack_opt', False)\n kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343,\n 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354}\n config_32339 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 88, 4), 'config', False)\n add_extension_32340 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 88, 4), config_32339,\n 'add_extension')\n add_extension_call_result_32356 = invoke(stypy.reporting.localization.\n Localization(__file__, 88, 4), add_extension_32340, *[str_32341],\n **kwargs_32355)\n str_32359 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 94, 26), 'str', '_ivp')\n kwargs_32360 = {}\n config_32357 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 94, 4), 'config', False)\n add_subpackage_32358 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 94, 4), config_32357,\n 'add_subpackage')\n add_subpackage_call_result_32361 = invoke(stypy.reporting.localization.\n Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359],\n **kwargs_32360)\n str_32364 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 96, 24), 'str', 'tests')\n kwargs_32365 = {}\n config_32362 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 96, 4), 'config', False)\n add_data_dir_32363 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 96, 4), config_32362,\n 'add_data_dir')\n add_data_dir_call_result_32366 = invoke(stypy.reporting.localization.\n Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], **\n kwargs_32365)\n config_32367 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 97, 11), 'config')\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 97, 4), 'stypy_return_type', config_32367)\n teardown_call_information(localization, arguments)\n stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 9, 0), 'stypy_return_type')\n module_type_store.store_return_type_of_current_context(\n stypy_return_type_32368)\n module_type_store = module_type_store.close_function_context()\n return stypy_return_type_32368\n\n\nmodule_type_store.set_type_of(stypy.reporting.localization.Localization(\n __file__, 9, 0), 'configuration', configuration)\nif __name__ == '__main__':\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 101, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32369 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 101, 4), 'numpy.distutils.core')\n if type(import_32369) is not StypyTypeError:\n if import_32369 != 'pyd_module':\n __import__(import_32369)\n sys_modules_32370 = sys.modules[import_32369]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 101, 4), 'numpy.distutils.core',\n sys_modules_32370.module_type_store, module_type_store, [\n 'setup'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 101, 4), __file__, sys_modules_32370, sys_modules_32370.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.core import setup\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 101, 4), 'numpy.distutils.core', None,\n module_type_store, ['setup'], [setup])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 101, 4), 'numpy.distutils.core',\n import_32369)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n kwargs_32378 = {}\n str_32373 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 102, 35), 'str', '')\n keyword_32374 = str_32373\n kwargs_32375 = {'top_path': keyword_32374}\n configuration_32372 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 102, 12), 'configuration', False)\n configuration_call_result_32376 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 12), configuration_32372, *[], **\n kwargs_32375)\n todict_32377 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 102, 12),\n configuration_call_result_32376, 'todict')\n todict_call_result_32379 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378)\n kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379}\n setup_32371 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 102, 4), 'setup', False)\n setup_call_result_32381 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380)\n<mask token>\n", "step-3": "<mask token>\nmodule_type_store = Context(None, __file__)\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 3, 0))\n<mask token>\nimport_module(stypy.reporting.localization.Localization(__file__, 3, 0),\n 'os', os, module_type_store)\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 4, 0))\nupdate_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\nimport_32066 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 4, 0), 'os.path')\nif type(import_32066) is not StypyTypeError:\n if import_32066 != 'pyd_module':\n __import__(import_32066)\n sys_modules_32067 = sys.modules[import_32066]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 4, 0), 'os.path', sys_modules_32067.module_type_store,\n module_type_store, ['join'])\n nest_module(stypy.reporting.localization.Localization(__file__, 4, \n 0), __file__, sys_modules_32067, sys_modules_32067.\n module_type_store, module_type_store)\n else:\n from os.path import join\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 4, 0), 'os.path', None, module_type_store, ['join'],\n [join])\nelse:\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 4, 0), 'os.path', import_32066)\nremove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 6, 0))\nupdate_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\nimport_32068 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 6, 0), 'scipy._build_utils')\nif type(import_32068) is not StypyTypeError:\n if import_32068 != 'pyd_module':\n __import__(import_32068)\n sys_modules_32069 = sys.modules[import_32068]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 6, 0), 'scipy._build_utils', sys_modules_32069.\n module_type_store, module_type_store, ['numpy_nodepr_api'])\n nest_module(stypy.reporting.localization.Localization(__file__, 6, \n 0), __file__, sys_modules_32069, sys_modules_32069.\n module_type_store, module_type_store)\n else:\n from scipy._build_utils import numpy_nodepr_api\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 6, 0), 'scipy._build_utils', None, module_type_store,\n ['numpy_nodepr_api'], [numpy_nodepr_api])\nelse:\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 6, 0), 'scipy._build_utils', import_32068)\nremove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n\n\n@norecursion\ndef configuration(localization, *varargs, **kwargs):\n global module_type_store\n str_32070 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 9, 33), 'str', '')\n None_32071 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 9, 45), 'None')\n defaults = [str_32070, None_32071]\n module_type_store = module_type_store.open_function_context('configuration'\n , 9, 0, False)\n configuration.stypy_localization = localization\n configuration.stypy_type_of_self = None\n configuration.stypy_type_store = module_type_store\n configuration.stypy_function_name = 'configuration'\n configuration.stypy_param_names_list = ['parent_package', 'top_path']\n configuration.stypy_varargs_param_name = None\n configuration.stypy_kwargs_param_name = None\n configuration.stypy_call_defaults = defaults\n configuration.stypy_call_varargs = varargs\n configuration.stypy_call_kwargs = kwargs\n arguments = process_argument_values(localization, None,\n module_type_store, 'configuration', ['parent_package', 'top_path'],\n None, None, defaults, varargs, kwargs)\n if is_error_type(arguments):\n module_type_store = module_type_store.close_function_context()\n return arguments\n init_call_information(module_type_store, 'configuration', localization,\n ['parent_package', 'top_path'], arguments)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 0, 0), 'stypy_return_type', None)\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 10, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32072 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util'\n )\n if type(import_32072) is not StypyTypeError:\n if import_32072 != 'pyd_module':\n __import__(import_32072)\n sys_modules_32073 = sys.modules[import_32072]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util',\n sys_modules_32073.module_type_store, module_type_store, [\n 'Configuration'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 10, 4), __file__, sys_modules_32073, sys_modules_32073.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.misc_util import Configuration\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util', None,\n module_type_store, ['Configuration'], [Configuration])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 10, 4), 'numpy.distutils.misc_util',\n import_32072)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 11, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32074 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 11, 4),\n 'numpy.distutils.system_info')\n if type(import_32074) is not StypyTypeError:\n if import_32074 != 'pyd_module':\n __import__(import_32074)\n sys_modules_32075 = sys.modules[import_32074]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info',\n sys_modules_32075.module_type_store, module_type_store, [\n 'get_info'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 11, 4), __file__, sys_modules_32075, sys_modules_32075.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.system_info import get_info\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info', None,\n module_type_store, ['get_info'], [get_info])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 11, 4), 'numpy.distutils.system_info',\n import_32074)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n str_32077 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 12, 27), 'str', 'integrate')\n parent_package_32078 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 40), 'parent_package', False)\n top_path_32079 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 56), 'top_path', False)\n kwargs_32080 = {}\n Configuration_32076 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 13), 'Configuration', False)\n Configuration_call_result_32081 = invoke(stypy.reporting.localization.\n Localization(__file__, 12, 13), Configuration_32076, *[str_32077,\n parent_package_32078, top_path_32079], **kwargs_32080)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 12, 4), 'config', Configuration_call_result_32081)\n str_32084 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 31), 'str', 'lapack_opt')\n int_32085 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 60), 'int')\n keyword_32086 = int_32085\n kwargs_32087 = {'notfound_action': keyword_32086}\n get_info_32083 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 15, 22), 'get_info', False)\n get_info_call_result_32088 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 22), get_info_32083, *[str_32084], **\n kwargs_32087)\n kwargs_32089 = {}\n dict_32082 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 15, 17), 'dict', False)\n dict_call_result_32090 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 17), dict_32082, *[\n get_info_call_result_32088], **kwargs_32089)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 15, 4), 'lapack_opt', dict_call_result_32090)\n str_32093 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 33), 'str', 'libraries')\n list_32094 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 46), 'list')\n kwargs_32095 = {}\n lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 18, 18), 'lapack_opt', False)\n pop_32092 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop')\n pop_call_result_32096 = invoke(stypy.reporting.localization.\n Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094],\n **kwargs_32095)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 18, 4), 'lapack_libs', pop_call_result_32096)\n list_32097 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 15), 'list')\n str_32099 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 21), 'str', 'mach')\n str_32100 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 28), 'str', '*.f')\n kwargs_32101 = {}\n join_32098 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 20, 16), 'join', False)\n join_call_result_32102 = invoke(stypy.reporting.localization.\n Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100],\n **kwargs_32101)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 20, 15), list_32097, join_call_result_32102)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 20, 4), 'mach_src', list_32097)\n list_32103 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 19), 'list')\n str_32105 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 25), 'str', 'quadpack')\n str_32106 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 37), 'str', '*.f')\n kwargs_32107 = {}\n join_32104 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 21, 20), 'join', False)\n join_call_result_32108 = invoke(stypy.reporting.localization.\n Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106],\n **kwargs_32107)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 21, 19), list_32103, join_call_result_32108)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 21, 4), 'quadpack_src', list_32103)\n list_32114 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 47), 'list')\n str_32115 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32115)\n str_32116 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 23), 'str', 'bnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32116)\n str_32117 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 34), 'str', 'cfode.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32117)\n str_32118 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 8), 'str', 'ewset.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32118)\n str_32119 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 19), 'str', 'fnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32119)\n str_32120 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 30), 'str', 'intdy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32120)\n str_32121 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 8), 'str', 'lsoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32121)\n str_32122 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 19), 'str', 'prja.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32122)\n str_32123 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 29), 'str', 'solsy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32123)\n str_32124 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 40), 'str', 'srcma.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32124)\n str_32125 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 8), 'str', 'stoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32125)\n str_32126 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32126)\n str_32127 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32127)\n str_32128 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 43), 'str', 'xsetf.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32128)\n str_32129 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 27, 8), 'str', 'xsetun.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32129)\n comprehension_32130 = get_contained_elements_type(stypy.reporting.\n localization.Localization(__file__, 22, 17), list_32114)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 17), 'fn', comprehension_32130)\n str_32110 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 22), 'str', 'odepack')\n fn_32111 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 22, 33), 'fn', False)\n kwargs_32112 = {}\n join_32109 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 22, 17), 'join', False)\n join_call_result_32113 = invoke(stypy.reporting.localization.\n Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111],\n **kwargs_32112)\n list_32131 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 17), 'list')\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 17), list_32131, join_call_result_32113)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 4), 'lsoda_src', list_32131)\n list_32132 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 15), 'list')\n str_32134 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 21), 'str', 'odepack')\n str_32135 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 32), 'str', 'vode.f')\n kwargs_32136 = {}\n join_32133 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 16), 'join', False)\n join_call_result_32137 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135],\n **kwargs_32136)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32137)\n str_32139 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 48), 'str', 'odepack')\n str_32140 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 59), 'str', 'zvode.f')\n kwargs_32141 = {}\n join_32138 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 43), 'join', False)\n join_call_result_32142 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140],\n **kwargs_32141)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32142)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 28, 4), 'vode_src', list_32132)\n list_32143 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 14), 'list')\n str_32145 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 20), 'str', 'dop')\n str_32146 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 26), 'str', '*.f')\n kwargs_32147 = {}\n join_32144 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 29, 15), 'join', False)\n join_call_result_32148 = invoke(stypy.reporting.localization.\n Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146],\n **kwargs_32147)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 29, 14), list_32143, join_call_result_32148)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 29, 4), 'dop_src', list_32143)\n list_32149 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 24), 'list')\n str_32151 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 30), 'str', 'tests')\n str_32152 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 38), 'str',\n '_test_multivariate.c')\n kwargs_32153 = {}\n join_32150 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 30, 25), 'join', False)\n join_call_result_32154 = invoke(stypy.reporting.localization.\n Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152],\n **kwargs_32153)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 30, 24), list_32149, join_call_result_32154)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 30, 4), 'quadpack_test_src', list_32149)\n list_32155 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 29), 'list')\n str_32157 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 35), 'str', 'tests')\n str_32158 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f')\n kwargs_32159 = {}\n join_32156 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 31, 30), 'join', False)\n join_call_result_32160 = invoke(stypy.reporting.localization.\n Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158],\n **kwargs_32159)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 31, 29), list_32155, join_call_result_32160)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 31, 4), 'odeint_banded_test_src', list_32155)\n str_32163 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 33, 23), 'str', 'mach')\n mach_src_32164 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 39), 'mach_src', False)\n keyword_32165 = mach_src_32164\n dict_32166 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 33), 'dict')\n str_32167 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 34), 'str', 'noopt')\n tuple_32168 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 43), 'tuple')\n file___32169 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 34, 43), '__file__', False)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, file___32169)\n int_32170 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 52), 'int')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, int_32170)\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 33), dict_32166, (str_32167, tuple_32168))\n keyword_32171 = dict_32166\n kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171}\n config_32161 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 4), 'config', False)\n add_library_32162 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 33, 4), config_32161,\n 'add_library')\n add_library_call_result_32173 = invoke(stypy.reporting.localization.\n Localization(__file__, 33, 4), add_library_32162, *[str_32163], **\n kwargs_32172)\n str_32176 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 35, 23), 'str', 'quadpack')\n quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 43), 'quadpack_src', False)\n keyword_32178 = quadpack_src_32177\n kwargs_32179 = {'sources': keyword_32178}\n config_32174 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 4), 'config', False)\n add_library_32175 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 35, 4), config_32174,\n 'add_library')\n add_library_call_result_32180 = invoke(stypy.reporting.localization.\n Localization(__file__, 35, 4), add_library_32175, *[str_32176], **\n kwargs_32179)\n str_32183 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 36, 23), 'str', 'lsoda')\n lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 40), 'lsoda_src', False)\n keyword_32185 = lsoda_src_32184\n kwargs_32186 = {'sources': keyword_32185}\n config_32181 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 4), 'config', False)\n add_library_32182 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 36, 4), config_32181,\n 'add_library')\n add_library_call_result_32187 = invoke(stypy.reporting.localization.\n Localization(__file__, 36, 4), add_library_32182, *[str_32183], **\n kwargs_32186)\n str_32190 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 37, 23), 'str', 'vode')\n vode_src_32191 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 39), 'vode_src', False)\n keyword_32192 = vode_src_32191\n kwargs_32193 = {'sources': keyword_32192}\n config_32188 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 4), 'config', False)\n add_library_32189 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 37, 4), config_32188,\n 'add_library')\n add_library_call_result_32194 = invoke(stypy.reporting.localization.\n Localization(__file__, 37, 4), add_library_32189, *[str_32190], **\n kwargs_32193)\n str_32197 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 38, 23), 'str', 'dop')\n dop_src_32198 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 38), 'dop_src', False)\n keyword_32199 = dop_src_32198\n kwargs_32200 = {'sources': keyword_32199}\n config_32195 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 4), 'config', False)\n add_library_32196 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 38, 4), config_32195,\n 'add_library')\n add_library_call_result_32201 = invoke(stypy.reporting.localization.\n Localization(__file__, 38, 4), add_library_32196, *[str_32197], **\n kwargs_32200)\n list_32202 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 19), 'list')\n file___32207 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 42, 41), '__file__', False)\n kwargs_32208 = {}\n os_32204 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 42, 25), 'os', False)\n path_32205 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), os_32204, 'path')\n dirname_32206 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), path_32205, 'dirname')\n dirname_call_result_32209 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 25), dirname_32206, *[file___32207], **\n kwargs_32208)\n str_32210 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 52), 'str', '..')\n str_32211 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 58), 'str', '_lib')\n str_32212 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 66), 'str', 'src')\n kwargs_32213 = {}\n join_32203 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 42, 20), 'join', False)\n join_call_result_32214 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 20), join_32203, *[\n dirname_call_result_32209, str_32210, str_32211, str_32212], **\n kwargs_32213)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 42, 19), list_32202, join_call_result_32214)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 42, 4), 'include_dirs', list_32202)\n str_32215 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 43, 7), 'str', 'include_dirs')\n lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 43, 25), 'lapack_opt')\n result_contains_32217 = python_operator(stypy.reporting.localization.\n Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216)\n if_condition_32218 = is_suitable_condition(stypy.reporting.localization\n .Localization(__file__, 43, 4), result_contains_32217)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 43, 4), 'if_condition_32218', if_condition_32218)\n module_type_store = SSAContext.create_ssa_context(module_type_store, 'if')\n lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 44, 26), 'lapack_opt', False)\n kwargs_32221 = {}\n dict_32219 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 44, 21), 'dict', False)\n dict_call_result_32222 = invoke(stypy.reporting.localization.\n Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], **\n kwargs_32221)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 44, 8), 'lapack_opt', dict_call_result_32222)\n str_32227 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 45, 43), 'str', 'include_dirs')\n kwargs_32228 = {}\n lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 28), 'lapack_opt', False)\n pop_32226 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop')\n pop_call_result_32229 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228\n )\n kwargs_32230 = {}\n include_dirs_32223 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 8), 'include_dirs', False)\n extend_32224 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 8), include_dirs_32223,\n 'extend')\n extend_call_result_32231 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 8), extend_32224, *[\n pop_call_result_32229], **kwargs_32230)\n module_type_store = module_type_store.join_ssa_context()\n str_32234 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 47, 25), 'str', '_quadpack')\n list_32235 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 33), 'list')\n str_32236 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c'\n )\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 48, 33), list_32235, str_32236)\n keyword_32237 = list_32235\n list_32238 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 35), 'list')\n str_32239 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 36), 'str', 'quadpack')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32239)\n str_32240 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 48), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32240)\n lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 49, 58), 'lapack_libs', False)\n result_add_32242 = python_operator(stypy.reporting.localization.\n Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241)\n keyword_32243 = result_add_32242\n list_32244 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 34), 'list')\n str_32245 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 35), 'str', '__quadpack.h')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 50, 34), list_32244, str_32245)\n quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 36), 'quadpack_src', False)\n result_add_32247 = python_operator(stypy.reporting.localization.\n Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246)\n mach_src_32248 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 51), 'mach_src', False)\n result_add_32249 = python_operator(stypy.reporting.localization.\n Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248)\n keyword_32250 = result_add_32249\n include_dirs_32251 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 52, 38), 'include_dirs', False)\n keyword_32252 = include_dirs_32251\n lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 53, 27), 'lapack_opt', False)\n kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237,\n 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253,\n 'include_dirs': keyword_32252}\n config_32232 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 47, 4), 'config', False)\n add_extension_32233 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 47, 4), config_32232,\n 'add_extension')\n add_extension_call_result_32255 = invoke(stypy.reporting.localization.\n Localization(__file__, 47, 4), add_extension_32233, *[str_32234],\n **kwargs_32254)\n kwargs_32258 = {}\n lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 56, 19), 'lapack_opt', False)\n copy_32257 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy')\n copy_call_result_32259 = invoke(stypy.reporting.localization.\n Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 56, 4), 'odepack_opts', copy_call_result_32259)\n numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False)\n kwargs_32263 = {}\n odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 4), 'odepack_opts', False)\n update_32261 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 57, 4), odepack_opts_32260,\n 'update')\n update_call_result_32264 = invoke(stypy.reporting.localization.\n Localization(__file__, 57, 4), update_32261, *[\n numpy_nodepr_api_32262], **kwargs_32263)\n str_32267 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 58, 25), 'str', '_odepack')\n list_32268 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 33), 'list')\n str_32269 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 59, 33), list_32268, str_32269)\n keyword_32270 = list_32268\n list_32271 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 35), 'list')\n str_32272 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32272)\n str_32273 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32273)\n lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 60, 55), 'lapack_libs', False)\n result_add_32275 = python_operator(stypy.reporting.localization.\n Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274)\n keyword_32276 = result_add_32275\n lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 34), 'lsoda_src', False)\n mach_src_32278 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 46), 'mach_src', False)\n result_add_32279 = python_operator(stypy.reporting.localization.\n Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278)\n keyword_32280 = result_add_32279\n odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 62, 27), 'odepack_opts', False)\n kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270,\n 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281}\n config_32265 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 58, 4), 'config', False)\n add_extension_32266 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 58, 4), config_32265,\n 'add_extension')\n add_extension_call_result_32283 = invoke(stypy.reporting.localization.\n Localization(__file__, 58, 4), add_extension_32266, *[str_32267],\n **kwargs_32282)\n str_32286 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 65, 25), 'str', 'vode')\n list_32287 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 33), 'list')\n str_32288 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 34), 'str', 'vode.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 66, 33), list_32287, str_32288)\n keyword_32289 = list_32287\n list_32290 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 35), 'list')\n str_32291 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 36), 'str', 'vode')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 67, 35), list_32290, str_32291)\n lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 67, 46), 'lapack_libs', False)\n result_add_32293 = python_operator(stypy.reporting.localization.\n Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292)\n keyword_32294 = result_add_32293\n vode_src_32295 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 68, 33), 'vode_src', False)\n keyword_32296 = vode_src_32295\n lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 69, 27), 'lapack_opt', False)\n kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289,\n 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297}\n config_32284 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 65, 4), 'config', False)\n add_extension_32285 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 65, 4), config_32284,\n 'add_extension')\n add_extension_call_result_32299 = invoke(stypy.reporting.localization.\n Localization(__file__, 65, 4), add_extension_32285, *[str_32286],\n **kwargs_32298)\n str_32302 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 72, 25), 'str', 'lsoda')\n list_32303 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 33), 'list')\n str_32304 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 73, 33), list_32303, str_32304)\n keyword_32305 = list_32303\n list_32306 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 35), 'list')\n str_32307 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32307)\n str_32308 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32308)\n lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 74, 55), 'lapack_libs', False)\n result_add_32310 = python_operator(stypy.reporting.localization.\n Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309)\n keyword_32311 = result_add_32310\n lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 34), 'lsoda_src', False)\n mach_src_32313 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 46), 'mach_src', False)\n result_add_32314 = python_operator(stypy.reporting.localization.\n Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313)\n keyword_32315 = result_add_32314\n lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 76, 27), 'lapack_opt', False)\n kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305,\n 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316}\n config_32300 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 72, 4), 'config', False)\n add_extension_32301 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 72, 4), config_32300,\n 'add_extension')\n add_extension_call_result_32318 = invoke(stypy.reporting.localization.\n Localization(__file__, 72, 4), add_extension_32301, *[str_32302],\n **kwargs_32317)\n str_32321 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 79, 25), 'str', '_dop')\n list_32322 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 33), 'list')\n str_32323 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 34), 'str', 'dop.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 80, 33), list_32322, str_32323)\n keyword_32324 = list_32322\n list_32325 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 35), 'list')\n str_32326 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 36), 'str', 'dop')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 81, 35), list_32325, str_32326)\n keyword_32327 = list_32325\n dop_src_32328 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 82, 33), 'dop_src', False)\n keyword_32329 = dop_src_32328\n kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324,\n 'depends': keyword_32329}\n config_32319 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 79, 4), 'config', False)\n add_extension_32320 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 79, 4), config_32319,\n 'add_extension')\n add_extension_call_result_32331 = invoke(stypy.reporting.localization.\n Localization(__file__, 79, 4), add_extension_32320, *[str_32321],\n **kwargs_32330)\n str_32334 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 84, 25), 'str',\n '_test_multivariate')\n quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 85, 33), 'quadpack_test_src', \n False)\n keyword_32336 = quadpack_test_src_32335\n kwargs_32337 = {'sources': keyword_32336}\n config_32332 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 84, 4), 'config', False)\n add_extension_32333 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 84, 4), config_32332,\n 'add_extension')\n add_extension_call_result_32338 = invoke(stypy.reporting.localization.\n Localization(__file__, 84, 4), add_extension_32333, *[str_32334],\n **kwargs_32337)\n str_32341 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 88, 25), 'str',\n '_test_odeint_banded')\n odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy.\n reporting.localization.Localization(__file__, 89, 33),\n 'odeint_banded_test_src', False)\n keyword_32343 = odeint_banded_test_src_32342\n list_32344 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 35), 'list')\n str_32345 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32345)\n str_32346 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32346)\n lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 90, 55), 'lapack_libs', False)\n result_add_32348 = python_operator(stypy.reporting.localization.\n Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347)\n keyword_32349 = result_add_32348\n lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 34), 'lsoda_src', False)\n mach_src_32351 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 46), 'mach_src', False)\n result_add_32352 = python_operator(stypy.reporting.localization.\n Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351)\n keyword_32353 = result_add_32352\n lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 92, 27), 'lapack_opt', False)\n kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343,\n 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354}\n config_32339 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 88, 4), 'config', False)\n add_extension_32340 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 88, 4), config_32339,\n 'add_extension')\n add_extension_call_result_32356 = invoke(stypy.reporting.localization.\n Localization(__file__, 88, 4), add_extension_32340, *[str_32341],\n **kwargs_32355)\n str_32359 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 94, 26), 'str', '_ivp')\n kwargs_32360 = {}\n config_32357 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 94, 4), 'config', False)\n add_subpackage_32358 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 94, 4), config_32357,\n 'add_subpackage')\n add_subpackage_call_result_32361 = invoke(stypy.reporting.localization.\n Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359],\n **kwargs_32360)\n str_32364 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 96, 24), 'str', 'tests')\n kwargs_32365 = {}\n config_32362 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 96, 4), 'config', False)\n add_data_dir_32363 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 96, 4), config_32362,\n 'add_data_dir')\n add_data_dir_call_result_32366 = invoke(stypy.reporting.localization.\n Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], **\n kwargs_32365)\n config_32367 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 97, 11), 'config')\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 97, 4), 'stypy_return_type', config_32367)\n teardown_call_information(localization, arguments)\n stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 9, 0), 'stypy_return_type')\n module_type_store.store_return_type_of_current_context(\n stypy_return_type_32368)\n module_type_store = module_type_store.close_function_context()\n return stypy_return_type_32368\n\n\nmodule_type_store.set_type_of(stypy.reporting.localization.Localization(\n __file__, 9, 0), 'configuration', configuration)\nif __name__ == '__main__':\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 101, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32369 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 101, 4), 'numpy.distutils.core')\n if type(import_32369) is not StypyTypeError:\n if import_32369 != 'pyd_module':\n __import__(import_32369)\n sys_modules_32370 = sys.modules[import_32369]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 101, 4), 'numpy.distutils.core',\n sys_modules_32370.module_type_store, module_type_store, [\n 'setup'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 101, 4), __file__, sys_modules_32370, sys_modules_32370.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.core import setup\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 101, 4), 'numpy.distutils.core', None,\n module_type_store, ['setup'], [setup])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 101, 4), 'numpy.distutils.core',\n import_32369)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n kwargs_32378 = {}\n str_32373 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 102, 35), 'str', '')\n keyword_32374 = str_32373\n kwargs_32375 = {'top_path': keyword_32374}\n configuration_32372 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 102, 12), 'configuration', False)\n configuration_call_result_32376 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 12), configuration_32372, *[], **\n kwargs_32375)\n todict_32377 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 102, 12),\n configuration_call_result_32376, 'todict')\n todict_call_result_32379 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378)\n kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379}\n setup_32371 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 102, 4), 'setup', False)\n setup_call_result_32381 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380)\nmodule_errors = stypy.errors.type_error.StypyTypeError.get_error_msgs()\nmodule_warnings = stypy.errors.type_warning.TypeWarning.get_warning_msgs()\n", "step-4": "<mask token>\nfrom stypy.type_inference_programs.type_inference_programs_imports import *\nmodule_type_store = Context(None, __file__)\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 3, 0))\nimport os\nimport_module(stypy.reporting.localization.Localization(__file__, 3, 0),\n 'os', os, module_type_store)\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 4, 0))\nupdate_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\nimport_32066 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 4, 0), 'os.path')\nif type(import_32066) is not StypyTypeError:\n if import_32066 != 'pyd_module':\n __import__(import_32066)\n sys_modules_32067 = sys.modules[import_32066]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 4, 0), 'os.path', sys_modules_32067.module_type_store,\n module_type_store, ['join'])\n nest_module(stypy.reporting.localization.Localization(__file__, 4, \n 0), __file__, sys_modules_32067, sys_modules_32067.\n module_type_store, module_type_store)\n else:\n from os.path import join\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 4, 0), 'os.path', None, module_type_store, ['join'],\n [join])\nelse:\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 4, 0), 'os.path', import_32066)\nremove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\nstypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 6, 0))\nupdate_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\nimport_32068 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 6, 0), 'scipy._build_utils')\nif type(import_32068) is not StypyTypeError:\n if import_32068 != 'pyd_module':\n __import__(import_32068)\n sys_modules_32069 = sys.modules[import_32068]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 6, 0), 'scipy._build_utils', sys_modules_32069.\n module_type_store, module_type_store, ['numpy_nodepr_api'])\n nest_module(stypy.reporting.localization.Localization(__file__, 6, \n 0), __file__, sys_modules_32069, sys_modules_32069.\n module_type_store, module_type_store)\n else:\n from scipy._build_utils import numpy_nodepr_api\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 6, 0), 'scipy._build_utils', None, module_type_store,\n ['numpy_nodepr_api'], [numpy_nodepr_api])\nelse:\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 6, 0), 'scipy._build_utils', import_32068)\nremove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n\n\n@norecursion\ndef configuration(localization, *varargs, **kwargs):\n global module_type_store\n str_32070 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 9, 33), 'str', '')\n None_32071 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 9, 45), 'None')\n defaults = [str_32070, None_32071]\n module_type_store = module_type_store.open_function_context('configuration'\n , 9, 0, False)\n configuration.stypy_localization = localization\n configuration.stypy_type_of_self = None\n configuration.stypy_type_store = module_type_store\n configuration.stypy_function_name = 'configuration'\n configuration.stypy_param_names_list = ['parent_package', 'top_path']\n configuration.stypy_varargs_param_name = None\n configuration.stypy_kwargs_param_name = None\n configuration.stypy_call_defaults = defaults\n configuration.stypy_call_varargs = varargs\n configuration.stypy_call_kwargs = kwargs\n arguments = process_argument_values(localization, None,\n module_type_store, 'configuration', ['parent_package', 'top_path'],\n None, None, defaults, varargs, kwargs)\n if is_error_type(arguments):\n module_type_store = module_type_store.close_function_context()\n return arguments\n init_call_information(module_type_store, 'configuration', localization,\n ['parent_package', 'top_path'], arguments)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 0, 0), 'stypy_return_type', None)\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 10, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32072 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util'\n )\n if type(import_32072) is not StypyTypeError:\n if import_32072 != 'pyd_module':\n __import__(import_32072)\n sys_modules_32073 = sys.modules[import_32072]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util',\n sys_modules_32073.module_type_store, module_type_store, [\n 'Configuration'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 10, 4), __file__, sys_modules_32073, sys_modules_32073.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.misc_util import Configuration\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 10, 4), 'numpy.distutils.misc_util', None,\n module_type_store, ['Configuration'], [Configuration])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 10, 4), 'numpy.distutils.misc_util',\n import_32072)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 11, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32074 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 11, 4),\n 'numpy.distutils.system_info')\n if type(import_32074) is not StypyTypeError:\n if import_32074 != 'pyd_module':\n __import__(import_32074)\n sys_modules_32075 = sys.modules[import_32074]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info',\n sys_modules_32075.module_type_store, module_type_store, [\n 'get_info'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 11, 4), __file__, sys_modules_32075, sys_modules_32075.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.system_info import get_info\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 11, 4), 'numpy.distutils.system_info', None,\n module_type_store, ['get_info'], [get_info])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 11, 4), 'numpy.distutils.system_info',\n import_32074)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n str_32077 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 12, 27), 'str', 'integrate')\n parent_package_32078 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 40), 'parent_package', False)\n top_path_32079 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 56), 'top_path', False)\n kwargs_32080 = {}\n Configuration_32076 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 12, 13), 'Configuration', False)\n Configuration_call_result_32081 = invoke(stypy.reporting.localization.\n Localization(__file__, 12, 13), Configuration_32076, *[str_32077,\n parent_package_32078, top_path_32079], **kwargs_32080)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 12, 4), 'config', Configuration_call_result_32081)\n str_32084 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 31), 'str', 'lapack_opt')\n int_32085 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 15, 60), 'int')\n keyword_32086 = int_32085\n kwargs_32087 = {'notfound_action': keyword_32086}\n get_info_32083 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 15, 22), 'get_info', False)\n get_info_call_result_32088 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 22), get_info_32083, *[str_32084], **\n kwargs_32087)\n kwargs_32089 = {}\n dict_32082 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 15, 17), 'dict', False)\n dict_call_result_32090 = invoke(stypy.reporting.localization.\n Localization(__file__, 15, 17), dict_32082, *[\n get_info_call_result_32088], **kwargs_32089)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 15, 4), 'lapack_opt', dict_call_result_32090)\n str_32093 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 33), 'str', 'libraries')\n list_32094 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 18, 46), 'list')\n kwargs_32095 = {}\n lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 18, 18), 'lapack_opt', False)\n pop_32092 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop')\n pop_call_result_32096 = invoke(stypy.reporting.localization.\n Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094],\n **kwargs_32095)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 18, 4), 'lapack_libs', pop_call_result_32096)\n list_32097 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 15), 'list')\n str_32099 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 21), 'str', 'mach')\n str_32100 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 20, 28), 'str', '*.f')\n kwargs_32101 = {}\n join_32098 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 20, 16), 'join', False)\n join_call_result_32102 = invoke(stypy.reporting.localization.\n Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100],\n **kwargs_32101)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 20, 15), list_32097, join_call_result_32102)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 20, 4), 'mach_src', list_32097)\n list_32103 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 19), 'list')\n str_32105 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 25), 'str', 'quadpack')\n str_32106 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 21, 37), 'str', '*.f')\n kwargs_32107 = {}\n join_32104 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 21, 20), 'join', False)\n join_call_result_32108 = invoke(stypy.reporting.localization.\n Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106],\n **kwargs_32107)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 21, 19), list_32103, join_call_result_32108)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 21, 4), 'quadpack_src', list_32103)\n list_32114 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 47), 'list')\n str_32115 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32115)\n str_32116 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 23), 'str', 'bnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32116)\n str_32117 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 23, 34), 'str', 'cfode.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32117)\n str_32118 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 8), 'str', 'ewset.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32118)\n str_32119 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 19), 'str', 'fnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32119)\n str_32120 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 24, 30), 'str', 'intdy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32120)\n str_32121 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 8), 'str', 'lsoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32121)\n str_32122 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 19), 'str', 'prja.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32122)\n str_32123 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 29), 'str', 'solsy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32123)\n str_32124 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 25, 40), 'str', 'srcma.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32124)\n str_32125 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 8), 'str', 'stoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32125)\n str_32126 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32126)\n str_32127 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32127)\n str_32128 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 26, 43), 'str', 'xsetf.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32128)\n str_32129 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 27, 8), 'str', 'xsetun.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 47), list_32114, str_32129)\n comprehension_32130 = get_contained_elements_type(stypy.reporting.\n localization.Localization(__file__, 22, 17), list_32114)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 17), 'fn', comprehension_32130)\n str_32110 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 22), 'str', 'odepack')\n fn_32111 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 22, 33), 'fn', False)\n kwargs_32112 = {}\n join_32109 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 22, 17), 'join', False)\n join_call_result_32113 = invoke(stypy.reporting.localization.\n Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111],\n **kwargs_32112)\n list_32131 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 22, 17), 'list')\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 22, 17), list_32131, join_call_result_32113)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 22, 4), 'lsoda_src', list_32131)\n list_32132 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 15), 'list')\n str_32134 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 21), 'str', 'odepack')\n str_32135 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 32), 'str', 'vode.f')\n kwargs_32136 = {}\n join_32133 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 16), 'join', False)\n join_call_result_32137 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135],\n **kwargs_32136)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32137)\n str_32139 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 48), 'str', 'odepack')\n str_32140 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 28, 59), 'str', 'zvode.f')\n kwargs_32141 = {}\n join_32138 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 28, 43), 'join', False)\n join_call_result_32142 = invoke(stypy.reporting.localization.\n Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140],\n **kwargs_32141)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 28, 15), list_32132, join_call_result_32142)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 28, 4), 'vode_src', list_32132)\n list_32143 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 14), 'list')\n str_32145 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 20), 'str', 'dop')\n str_32146 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 29, 26), 'str', '*.f')\n kwargs_32147 = {}\n join_32144 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 29, 15), 'join', False)\n join_call_result_32148 = invoke(stypy.reporting.localization.\n Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146],\n **kwargs_32147)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 29, 14), list_32143, join_call_result_32148)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 29, 4), 'dop_src', list_32143)\n list_32149 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 24), 'list')\n str_32151 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 30), 'str', 'tests')\n str_32152 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 30, 38), 'str',\n '_test_multivariate.c')\n kwargs_32153 = {}\n join_32150 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 30, 25), 'join', False)\n join_call_result_32154 = invoke(stypy.reporting.localization.\n Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152],\n **kwargs_32153)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 30, 24), list_32149, join_call_result_32154)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 30, 4), 'quadpack_test_src', list_32149)\n list_32155 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 29), 'list')\n str_32157 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 35), 'str', 'tests')\n str_32158 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f')\n kwargs_32159 = {}\n join_32156 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 31, 30), 'join', False)\n join_call_result_32160 = invoke(stypy.reporting.localization.\n Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158],\n **kwargs_32159)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 31, 29), list_32155, join_call_result_32160)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 31, 4), 'odeint_banded_test_src', list_32155)\n str_32163 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 33, 23), 'str', 'mach')\n mach_src_32164 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 39), 'mach_src', False)\n keyword_32165 = mach_src_32164\n dict_32166 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 33), 'dict')\n str_32167 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 34), 'str', 'noopt')\n tuple_32168 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 43), 'tuple')\n file___32169 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 34, 43), '__file__', False)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, file___32169)\n int_32170 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 34, 52), 'int')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 43), tuple_32168, int_32170)\n set_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 34, 33), dict_32166, (str_32167, tuple_32168))\n keyword_32171 = dict_32166\n kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171}\n config_32161 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 33, 4), 'config', False)\n add_library_32162 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 33, 4), config_32161,\n 'add_library')\n add_library_call_result_32173 = invoke(stypy.reporting.localization.\n Localization(__file__, 33, 4), add_library_32162, *[str_32163], **\n kwargs_32172)\n str_32176 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 35, 23), 'str', 'quadpack')\n quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 43), 'quadpack_src', False)\n keyword_32178 = quadpack_src_32177\n kwargs_32179 = {'sources': keyword_32178}\n config_32174 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 35, 4), 'config', False)\n add_library_32175 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 35, 4), config_32174,\n 'add_library')\n add_library_call_result_32180 = invoke(stypy.reporting.localization.\n Localization(__file__, 35, 4), add_library_32175, *[str_32176], **\n kwargs_32179)\n str_32183 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 36, 23), 'str', 'lsoda')\n lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 40), 'lsoda_src', False)\n keyword_32185 = lsoda_src_32184\n kwargs_32186 = {'sources': keyword_32185}\n config_32181 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 36, 4), 'config', False)\n add_library_32182 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 36, 4), config_32181,\n 'add_library')\n add_library_call_result_32187 = invoke(stypy.reporting.localization.\n Localization(__file__, 36, 4), add_library_32182, *[str_32183], **\n kwargs_32186)\n str_32190 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 37, 23), 'str', 'vode')\n vode_src_32191 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 39), 'vode_src', False)\n keyword_32192 = vode_src_32191\n kwargs_32193 = {'sources': keyword_32192}\n config_32188 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 37, 4), 'config', False)\n add_library_32189 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 37, 4), config_32188,\n 'add_library')\n add_library_call_result_32194 = invoke(stypy.reporting.localization.\n Localization(__file__, 37, 4), add_library_32189, *[str_32190], **\n kwargs_32193)\n str_32197 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 38, 23), 'str', 'dop')\n dop_src_32198 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 38), 'dop_src', False)\n keyword_32199 = dop_src_32198\n kwargs_32200 = {'sources': keyword_32199}\n config_32195 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 38, 4), 'config', False)\n add_library_32196 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 38, 4), config_32195,\n 'add_library')\n add_library_call_result_32201 = invoke(stypy.reporting.localization.\n Localization(__file__, 38, 4), add_library_32196, *[str_32197], **\n kwargs_32200)\n list_32202 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 19), 'list')\n file___32207 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 42, 41), '__file__', False)\n kwargs_32208 = {}\n os_32204 = module_type_store.get_type_of(stypy.reporting.localization.\n Localization(__file__, 42, 25), 'os', False)\n path_32205 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), os_32204, 'path')\n dirname_32206 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 42, 25), path_32205, 'dirname')\n dirname_call_result_32209 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 25), dirname_32206, *[file___32207], **\n kwargs_32208)\n str_32210 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 52), 'str', '..')\n str_32211 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 58), 'str', '_lib')\n str_32212 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 42, 66), 'str', 'src')\n kwargs_32213 = {}\n join_32203 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 42, 20), 'join', False)\n join_call_result_32214 = invoke(stypy.reporting.localization.\n Localization(__file__, 42, 20), join_32203, *[\n dirname_call_result_32209, str_32210, str_32211, str_32212], **\n kwargs_32213)\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 42, 19), list_32202, join_call_result_32214)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 42, 4), 'include_dirs', list_32202)\n str_32215 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 43, 7), 'str', 'include_dirs')\n lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 43, 25), 'lapack_opt')\n result_contains_32217 = python_operator(stypy.reporting.localization.\n Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216)\n if_condition_32218 = is_suitable_condition(stypy.reporting.localization\n .Localization(__file__, 43, 4), result_contains_32217)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 43, 4), 'if_condition_32218', if_condition_32218)\n module_type_store = SSAContext.create_ssa_context(module_type_store, 'if')\n lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 44, 26), 'lapack_opt', False)\n kwargs_32221 = {}\n dict_32219 = module_type_store.get_type_of(stypy.reporting.localization\n .Localization(__file__, 44, 21), 'dict', False)\n dict_call_result_32222 = invoke(stypy.reporting.localization.\n Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], **\n kwargs_32221)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 44, 8), 'lapack_opt', dict_call_result_32222)\n str_32227 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 45, 43), 'str', 'include_dirs')\n kwargs_32228 = {}\n lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 28), 'lapack_opt', False)\n pop_32226 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop')\n pop_call_result_32229 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228\n )\n kwargs_32230 = {}\n include_dirs_32223 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 45, 8), 'include_dirs', False)\n extend_32224 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 45, 8), include_dirs_32223,\n 'extend')\n extend_call_result_32231 = invoke(stypy.reporting.localization.\n Localization(__file__, 45, 8), extend_32224, *[\n pop_call_result_32229], **kwargs_32230)\n module_type_store = module_type_store.join_ssa_context()\n str_32234 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 47, 25), 'str', '_quadpack')\n list_32235 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 33), 'list')\n str_32236 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c'\n )\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 48, 33), list_32235, str_32236)\n keyword_32237 = list_32235\n list_32238 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 35), 'list')\n str_32239 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 36), 'str', 'quadpack')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32239)\n str_32240 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 49, 48), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 49, 35), list_32238, str_32240)\n lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 49, 58), 'lapack_libs', False)\n result_add_32242 = python_operator(stypy.reporting.localization.\n Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241)\n keyword_32243 = result_add_32242\n list_32244 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 34), 'list')\n str_32245 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 50, 35), 'str', '__quadpack.h')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 50, 34), list_32244, str_32245)\n quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 36), 'quadpack_src', False)\n result_add_32247 = python_operator(stypy.reporting.localization.\n Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246)\n mach_src_32248 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 51, 51), 'mach_src', False)\n result_add_32249 = python_operator(stypy.reporting.localization.\n Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248)\n keyword_32250 = result_add_32249\n include_dirs_32251 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 52, 38), 'include_dirs', False)\n keyword_32252 = include_dirs_32251\n lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 53, 27), 'lapack_opt', False)\n kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237,\n 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253,\n 'include_dirs': keyword_32252}\n config_32232 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 47, 4), 'config', False)\n add_extension_32233 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 47, 4), config_32232,\n 'add_extension')\n add_extension_call_result_32255 = invoke(stypy.reporting.localization.\n Localization(__file__, 47, 4), add_extension_32233, *[str_32234],\n **kwargs_32254)\n kwargs_32258 = {}\n lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 56, 19), 'lapack_opt', False)\n copy_32257 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy')\n copy_call_result_32259 = invoke(stypy.reporting.localization.\n Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258)\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 56, 4), 'odepack_opts', copy_call_result_32259)\n numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False)\n kwargs_32263 = {}\n odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 57, 4), 'odepack_opts', False)\n update_32261 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 57, 4), odepack_opts_32260,\n 'update')\n update_call_result_32264 = invoke(stypy.reporting.localization.\n Localization(__file__, 57, 4), update_32261, *[\n numpy_nodepr_api_32262], **kwargs_32263)\n str_32267 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 58, 25), 'str', '_odepack')\n list_32268 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 33), 'list')\n str_32269 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 59, 33), list_32268, str_32269)\n keyword_32270 = list_32268\n list_32271 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 35), 'list')\n str_32272 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32272)\n str_32273 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 60, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 60, 35), list_32271, str_32273)\n lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 60, 55), 'lapack_libs', False)\n result_add_32275 = python_operator(stypy.reporting.localization.\n Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274)\n keyword_32276 = result_add_32275\n lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 34), 'lsoda_src', False)\n mach_src_32278 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 61, 46), 'mach_src', False)\n result_add_32279 = python_operator(stypy.reporting.localization.\n Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278)\n keyword_32280 = result_add_32279\n odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 62, 27), 'odepack_opts', False)\n kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270,\n 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281}\n config_32265 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 58, 4), 'config', False)\n add_extension_32266 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 58, 4), config_32265,\n 'add_extension')\n add_extension_call_result_32283 = invoke(stypy.reporting.localization.\n Localization(__file__, 58, 4), add_extension_32266, *[str_32267],\n **kwargs_32282)\n str_32286 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 65, 25), 'str', 'vode')\n list_32287 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 33), 'list')\n str_32288 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 66, 34), 'str', 'vode.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 66, 33), list_32287, str_32288)\n keyword_32289 = list_32287\n list_32290 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 35), 'list')\n str_32291 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 67, 36), 'str', 'vode')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 67, 35), list_32290, str_32291)\n lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 67, 46), 'lapack_libs', False)\n result_add_32293 = python_operator(stypy.reporting.localization.\n Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292)\n keyword_32294 = result_add_32293\n vode_src_32295 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 68, 33), 'vode_src', False)\n keyword_32296 = vode_src_32295\n lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 69, 27), 'lapack_opt', False)\n kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289,\n 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297}\n config_32284 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 65, 4), 'config', False)\n add_extension_32285 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 65, 4), config_32284,\n 'add_extension')\n add_extension_call_result_32299 = invoke(stypy.reporting.localization.\n Localization(__file__, 65, 4), add_extension_32285, *[str_32286],\n **kwargs_32298)\n str_32302 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 72, 25), 'str', 'lsoda')\n list_32303 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 33), 'list')\n str_32304 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 73, 33), list_32303, str_32304)\n keyword_32305 = list_32303\n list_32306 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 35), 'list')\n str_32307 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32307)\n str_32308 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 74, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 74, 35), list_32306, str_32308)\n lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 74, 55), 'lapack_libs', False)\n result_add_32310 = python_operator(stypy.reporting.localization.\n Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309)\n keyword_32311 = result_add_32310\n lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 34), 'lsoda_src', False)\n mach_src_32313 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 75, 46), 'mach_src', False)\n result_add_32314 = python_operator(stypy.reporting.localization.\n Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313)\n keyword_32315 = result_add_32314\n lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 76, 27), 'lapack_opt', False)\n kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305,\n 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316}\n config_32300 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 72, 4), 'config', False)\n add_extension_32301 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 72, 4), config_32300,\n 'add_extension')\n add_extension_call_result_32318 = invoke(stypy.reporting.localization.\n Localization(__file__, 72, 4), add_extension_32301, *[str_32302],\n **kwargs_32317)\n str_32321 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 79, 25), 'str', '_dop')\n list_32322 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 33), 'list')\n str_32323 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 80, 34), 'str', 'dop.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 80, 33), list_32322, str_32323)\n keyword_32324 = list_32322\n list_32325 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 35), 'list')\n str_32326 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 81, 36), 'str', 'dop')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 81, 35), list_32325, str_32326)\n keyword_32327 = list_32325\n dop_src_32328 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 82, 33), 'dop_src', False)\n keyword_32329 = dop_src_32328\n kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324,\n 'depends': keyword_32329}\n config_32319 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 79, 4), 'config', False)\n add_extension_32320 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 79, 4), config_32319,\n 'add_extension')\n add_extension_call_result_32331 = invoke(stypy.reporting.localization.\n Localization(__file__, 79, 4), add_extension_32320, *[str_32321],\n **kwargs_32330)\n str_32334 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 84, 25), 'str',\n '_test_multivariate')\n quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 85, 33), 'quadpack_test_src', \n False)\n keyword_32336 = quadpack_test_src_32335\n kwargs_32337 = {'sources': keyword_32336}\n config_32332 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 84, 4), 'config', False)\n add_extension_32333 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 84, 4), config_32332,\n 'add_extension')\n add_extension_call_result_32338 = invoke(stypy.reporting.localization.\n Localization(__file__, 84, 4), add_extension_32333, *[str_32334],\n **kwargs_32337)\n str_32341 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 88, 25), 'str',\n '_test_odeint_banded')\n odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy.\n reporting.localization.Localization(__file__, 89, 33),\n 'odeint_banded_test_src', False)\n keyword_32343 = odeint_banded_test_src_32342\n list_32344 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 35), 'list')\n str_32345 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32345)\n str_32346 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 90, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(\n __file__, 90, 35), list_32344, str_32346)\n lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 90, 55), 'lapack_libs', False)\n result_add_32348 = python_operator(stypy.reporting.localization.\n Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347)\n keyword_32349 = result_add_32348\n lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 34), 'lsoda_src', False)\n mach_src_32351 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 91, 46), 'mach_src', False)\n result_add_32352 = python_operator(stypy.reporting.localization.\n Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351)\n keyword_32353 = result_add_32352\n lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 92, 27), 'lapack_opt', False)\n kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343,\n 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354}\n config_32339 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 88, 4), 'config', False)\n add_extension_32340 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 88, 4), config_32339,\n 'add_extension')\n add_extension_call_result_32356 = invoke(stypy.reporting.localization.\n Localization(__file__, 88, 4), add_extension_32340, *[str_32341],\n **kwargs_32355)\n str_32359 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 94, 26), 'str', '_ivp')\n kwargs_32360 = {}\n config_32357 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 94, 4), 'config', False)\n add_subpackage_32358 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 94, 4), config_32357,\n 'add_subpackage')\n add_subpackage_call_result_32361 = invoke(stypy.reporting.localization.\n Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359],\n **kwargs_32360)\n str_32364 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 96, 24), 'str', 'tests')\n kwargs_32365 = {}\n config_32362 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 96, 4), 'config', False)\n add_data_dir_32363 = module_type_store.get_type_of_member(stypy.\n reporting.localization.Localization(__file__, 96, 4), config_32362,\n 'add_data_dir')\n add_data_dir_call_result_32366 = invoke(stypy.reporting.localization.\n Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], **\n kwargs_32365)\n config_32367 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 97, 11), 'config')\n module_type_store.set_type_of(stypy.reporting.localization.Localization\n (__file__, 97, 4), 'stypy_return_type', config_32367)\n teardown_call_information(localization, arguments)\n stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting\n .localization.Localization(__file__, 9, 0), 'stypy_return_type')\n module_type_store.store_return_type_of_current_context(\n stypy_return_type_32368)\n module_type_store = module_type_store.close_function_context()\n return stypy_return_type_32368\n\n\nmodule_type_store.set_type_of(stypy.reporting.localization.Localization(\n __file__, 9, 0), 'configuration', configuration)\nif __name__ == '__main__':\n stypy.reporting.localization.Localization.set_current(stypy.reporting.\n localization.Localization(__file__, 101, 4))\n update_path_to_current_file_folder(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n import_32369 = generate_type_inference_code_for_module(stypy.reporting.\n localization.Localization(__file__, 101, 4), 'numpy.distutils.core')\n if type(import_32369) is not StypyTypeError:\n if import_32369 != 'pyd_module':\n __import__(import_32369)\n sys_modules_32370 = sys.modules[import_32369]\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 101, 4), 'numpy.distutils.core',\n sys_modules_32370.module_type_store, module_type_store, [\n 'setup'])\n nest_module(stypy.reporting.localization.Localization(__file__,\n 101, 4), __file__, sys_modules_32370, sys_modules_32370.\n module_type_store, module_type_store)\n else:\n from numpy.distutils.core import setup\n import_from_module(stypy.reporting.localization.Localization(\n __file__, 101, 4), 'numpy.distutils.core', None,\n module_type_store, ['setup'], [setup])\n else:\n module_type_store.set_type_of(stypy.reporting.localization.\n Localization(__file__, 101, 4), 'numpy.distutils.core',\n import_32369)\n remove_current_file_folder_from_path(\n 'C:/Python27/lib/site-packages/scipy/integrate/')\n kwargs_32378 = {}\n str_32373 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 102, 35), 'str', '')\n keyword_32374 = str_32373\n kwargs_32375 = {'top_path': keyword_32374}\n configuration_32372 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 102, 12), 'configuration', False)\n configuration_call_result_32376 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 12), configuration_32372, *[], **\n kwargs_32375)\n todict_32377 = module_type_store.get_type_of_member(stypy.reporting.\n localization.Localization(__file__, 102, 12),\n configuration_call_result_32376, 'todict')\n todict_call_result_32379 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378)\n kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379}\n setup_32371 = module_type_store.get_type_of(stypy.reporting.\n localization.Localization(__file__, 102, 4), 'setup', False)\n setup_call_result_32381 = invoke(stypy.reporting.localization.\n Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380)\nmodule_errors = stypy.errors.type_error.StypyTypeError.get_error_msgs()\nmodule_warnings = stypy.errors.type_warning.TypeWarning.get_warning_msgs()\n", "step-5": "\n# -*- coding: utf-8 -*-\n\n\"\"\"\nORIGINAL PROGRAM SOURCE CODE:\n1: from __future__ import division, print_function, absolute_import\n2: \n3: import os\n4: from os.path import join\n5: \n6: from scipy._build_utils import numpy_nodepr_api\n7: \n8: \n9: def configuration(parent_package='',top_path=None):\n10: from numpy.distutils.misc_util import Configuration\n11: from numpy.distutils.system_info import get_info\n12: config = Configuration('integrate', parent_package, top_path)\n13: \n14: # Get a local copy of lapack_opt_info\n15: lapack_opt = dict(get_info('lapack_opt',notfound_action=2))\n16: # Pop off the libraries list so it can be combined with\n17: # additional required libraries\n18: lapack_libs = lapack_opt.pop('libraries', [])\n19: \n20: mach_src = [join('mach','*.f')]\n21: quadpack_src = [join('quadpack', '*.f')]\n22: lsoda_src = [join('odepack', fn) for fn in [\n23: 'blkdta000.f', 'bnorm.f', 'cfode.f',\n24: 'ewset.f', 'fnorm.f', 'intdy.f',\n25: 'lsoda.f', 'prja.f', 'solsy.f', 'srcma.f',\n26: 'stoda.f', 'vmnorm.f', 'xerrwv.f', 'xsetf.f',\n27: 'xsetun.f']]\n28: vode_src = [join('odepack', 'vode.f'), join('odepack', 'zvode.f')]\n29: dop_src = [join('dop','*.f')]\n30: quadpack_test_src = [join('tests','_test_multivariate.c')]\n31: odeint_banded_test_src = [join('tests', 'banded5x5.f')]\n32: \n33: config.add_library('mach', sources=mach_src,\n34: config_fc={'noopt':(__file__,1)})\n35: config.add_library('quadpack', sources=quadpack_src)\n36: config.add_library('lsoda', sources=lsoda_src)\n37: config.add_library('vode', sources=vode_src)\n38: config.add_library('dop', sources=dop_src)\n39: \n40: # Extensions\n41: # quadpack:\n42: include_dirs = [join(os.path.dirname(__file__), '..', '_lib', 'src')]\n43: if 'include_dirs' in lapack_opt:\n44: lapack_opt = dict(lapack_opt)\n45: include_dirs.extend(lapack_opt.pop('include_dirs'))\n46: \n47: config.add_extension('_quadpack',\n48: sources=['_quadpackmodule.c'],\n49: libraries=['quadpack', 'mach'] + lapack_libs,\n50: depends=(['__quadpack.h']\n51: + quadpack_src + mach_src),\n52: include_dirs=include_dirs,\n53: **lapack_opt)\n54: \n55: # odepack/lsoda-odeint\n56: odepack_opts = lapack_opt.copy()\n57: odepack_opts.update(numpy_nodepr_api)\n58: config.add_extension('_odepack',\n59: sources=['_odepackmodule.c'],\n60: libraries=['lsoda', 'mach'] + lapack_libs,\n61: depends=(lsoda_src + mach_src),\n62: **odepack_opts)\n63: \n64: # vode\n65: config.add_extension('vode',\n66: sources=['vode.pyf'],\n67: libraries=['vode'] + lapack_libs,\n68: depends=vode_src,\n69: **lapack_opt)\n70: \n71: # lsoda\n72: config.add_extension('lsoda',\n73: sources=['lsoda.pyf'],\n74: libraries=['lsoda', 'mach'] + lapack_libs,\n75: depends=(lsoda_src + mach_src),\n76: **lapack_opt)\n77: \n78: # dop\n79: config.add_extension('_dop',\n80: sources=['dop.pyf'],\n81: libraries=['dop'],\n82: depends=dop_src)\n83: \n84: config.add_extension('_test_multivariate',\n85: sources=quadpack_test_src)\n86: \n87: # Fortran+f2py extension module for testing odeint.\n88: config.add_extension('_test_odeint_banded',\n89: sources=odeint_banded_test_src,\n90: libraries=['lsoda', 'mach'] + lapack_libs,\n91: depends=(lsoda_src + mach_src),\n92: **lapack_opt)\n93: \n94: config.add_subpackage('_ivp')\n95: \n96: config.add_data_dir('tests')\n97: return config\n98: \n99: \n100: if __name__ == '__main__':\n101: from numpy.distutils.core import setup\n102: setup(**configuration(top_path='').todict())\n103: \n\n\"\"\"\n\n# Import the stypy library necessary elements\nfrom stypy.type_inference_programs.type_inference_programs_imports import *\n\n# Create the module type store\nmodule_type_store = Context(None, __file__)\n\n# ################# Begin of the type inference program ##################\n\nstypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 3, 0))\n\n# 'import os' statement (line 3)\nimport os\n\nimport_module(stypy.reporting.localization.Localization(__file__, 3, 0), 'os', os, module_type_store)\n\nstypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 4, 0))\n\n# 'from os.path import join' statement (line 4)\nupdate_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/')\nimport_32066 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path')\n\nif (type(import_32066) is not StypyTypeError):\n\n if (import_32066 != 'pyd_module'):\n __import__(import_32066)\n sys_modules_32067 = sys.modules[import_32066]\n import_from_module(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path', sys_modules_32067.module_type_store, module_type_store, ['join'])\n nest_module(stypy.reporting.localization.Localization(__file__, 4, 0), __file__, sys_modules_32067, sys_modules_32067.module_type_store, module_type_store)\n else:\n from os.path import join\n\n import_from_module(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path', None, module_type_store, ['join'], [join])\n\nelse:\n # Assigning a type to the variable 'os.path' (line 4)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 4, 0), 'os.path', import_32066)\n\nremove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/')\n\nstypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 6, 0))\n\n# 'from scipy._build_utils import numpy_nodepr_api' statement (line 6)\nupdate_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/')\nimport_32068 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils')\n\nif (type(import_32068) is not StypyTypeError):\n\n if (import_32068 != 'pyd_module'):\n __import__(import_32068)\n sys_modules_32069 = sys.modules[import_32068]\n import_from_module(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils', sys_modules_32069.module_type_store, module_type_store, ['numpy_nodepr_api'])\n nest_module(stypy.reporting.localization.Localization(__file__, 6, 0), __file__, sys_modules_32069, sys_modules_32069.module_type_store, module_type_store)\n else:\n from scipy._build_utils import numpy_nodepr_api\n\n import_from_module(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils', None, module_type_store, ['numpy_nodepr_api'], [numpy_nodepr_api])\n\nelse:\n # Assigning a type to the variable 'scipy._build_utils' (line 6)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 6, 0), 'scipy._build_utils', import_32068)\n\nremove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/')\n\n\n@norecursion\ndef configuration(localization, *varargs, **kwargs):\n global module_type_store\n # Assign values to the parameters with defaults\n str_32070 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 9, 33), 'str', '')\n # Getting the type of 'None' (line 9)\n None_32071 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 9, 45), 'None')\n defaults = [str_32070, None_32071]\n # Create a new context for function 'configuration'\n module_type_store = module_type_store.open_function_context('configuration', 9, 0, False)\n \n # Passed parameters checking function\n configuration.stypy_localization = localization\n configuration.stypy_type_of_self = None\n configuration.stypy_type_store = module_type_store\n configuration.stypy_function_name = 'configuration'\n configuration.stypy_param_names_list = ['parent_package', 'top_path']\n configuration.stypy_varargs_param_name = None\n configuration.stypy_kwargs_param_name = None\n configuration.stypy_call_defaults = defaults\n configuration.stypy_call_varargs = varargs\n configuration.stypy_call_kwargs = kwargs\n arguments = process_argument_values(localization, None, module_type_store, 'configuration', ['parent_package', 'top_path'], None, None, defaults, varargs, kwargs)\n\n if is_error_type(arguments):\n # Destroy the current context\n module_type_store = module_type_store.close_function_context()\n return arguments\n\n # Initialize method data\n init_call_information(module_type_store, 'configuration', localization, ['parent_package', 'top_path'], arguments)\n \n # Default return type storage variable (SSA)\n # Assigning a type to the variable 'stypy_return_type'\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 0, 0), 'stypy_return_type', None)\n \n \n # ################# Begin of 'configuration(...)' code ##################\n\n stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 10, 4))\n \n # 'from numpy.distutils.misc_util import Configuration' statement (line 10)\n update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/')\n import_32072 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util')\n\n if (type(import_32072) is not StypyTypeError):\n\n if (import_32072 != 'pyd_module'):\n __import__(import_32072)\n sys_modules_32073 = sys.modules[import_32072]\n import_from_module(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util', sys_modules_32073.module_type_store, module_type_store, ['Configuration'])\n nest_module(stypy.reporting.localization.Localization(__file__, 10, 4), __file__, sys_modules_32073, sys_modules_32073.module_type_store, module_type_store)\n else:\n from numpy.distutils.misc_util import Configuration\n\n import_from_module(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util', None, module_type_store, ['Configuration'], [Configuration])\n\n else:\n # Assigning a type to the variable 'numpy.distutils.misc_util' (line 10)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 10, 4), 'numpy.distutils.misc_util', import_32072)\n\n remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/')\n \n stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 11, 4))\n \n # 'from numpy.distutils.system_info import get_info' statement (line 11)\n update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/')\n import_32074 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info')\n\n if (type(import_32074) is not StypyTypeError):\n\n if (import_32074 != 'pyd_module'):\n __import__(import_32074)\n sys_modules_32075 = sys.modules[import_32074]\n import_from_module(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info', sys_modules_32075.module_type_store, module_type_store, ['get_info'])\n nest_module(stypy.reporting.localization.Localization(__file__, 11, 4), __file__, sys_modules_32075, sys_modules_32075.module_type_store, module_type_store)\n else:\n from numpy.distutils.system_info import get_info\n\n import_from_module(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info', None, module_type_store, ['get_info'], [get_info])\n\n else:\n # Assigning a type to the variable 'numpy.distutils.system_info' (line 11)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 11, 4), 'numpy.distutils.system_info', import_32074)\n\n remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/')\n \n \n # Assigning a Call to a Name (line 12):\n \n # Call to Configuration(...): (line 12)\n # Processing the call arguments (line 12)\n str_32077 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 12, 27), 'str', 'integrate')\n # Getting the type of 'parent_package' (line 12)\n parent_package_32078 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 12, 40), 'parent_package', False)\n # Getting the type of 'top_path' (line 12)\n top_path_32079 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 12, 56), 'top_path', False)\n # Processing the call keyword arguments (line 12)\n kwargs_32080 = {}\n # Getting the type of 'Configuration' (line 12)\n Configuration_32076 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 12, 13), 'Configuration', False)\n # Calling Configuration(args, kwargs) (line 12)\n Configuration_call_result_32081 = invoke(stypy.reporting.localization.Localization(__file__, 12, 13), Configuration_32076, *[str_32077, parent_package_32078, top_path_32079], **kwargs_32080)\n \n # Assigning a type to the variable 'config' (line 12)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 12, 4), 'config', Configuration_call_result_32081)\n \n # Assigning a Call to a Name (line 15):\n \n # Call to dict(...): (line 15)\n # Processing the call arguments (line 15)\n \n # Call to get_info(...): (line 15)\n # Processing the call arguments (line 15)\n str_32084 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 15, 31), 'str', 'lapack_opt')\n # Processing the call keyword arguments (line 15)\n int_32085 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 15, 60), 'int')\n keyword_32086 = int_32085\n kwargs_32087 = {'notfound_action': keyword_32086}\n # Getting the type of 'get_info' (line 15)\n get_info_32083 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 15, 22), 'get_info', False)\n # Calling get_info(args, kwargs) (line 15)\n get_info_call_result_32088 = invoke(stypy.reporting.localization.Localization(__file__, 15, 22), get_info_32083, *[str_32084], **kwargs_32087)\n \n # Processing the call keyword arguments (line 15)\n kwargs_32089 = {}\n # Getting the type of 'dict' (line 15)\n dict_32082 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 15, 17), 'dict', False)\n # Calling dict(args, kwargs) (line 15)\n dict_call_result_32090 = invoke(stypy.reporting.localization.Localization(__file__, 15, 17), dict_32082, *[get_info_call_result_32088], **kwargs_32089)\n \n # Assigning a type to the variable 'lapack_opt' (line 15)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 15, 4), 'lapack_opt', dict_call_result_32090)\n \n # Assigning a Call to a Name (line 18):\n \n # Call to pop(...): (line 18)\n # Processing the call arguments (line 18)\n str_32093 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 18, 33), 'str', 'libraries')\n \n # Obtaining an instance of the builtin type 'list' (line 18)\n list_32094 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 18, 46), 'list')\n # Adding type elements to the builtin type 'list' instance (line 18)\n \n # Processing the call keyword arguments (line 18)\n kwargs_32095 = {}\n # Getting the type of 'lapack_opt' (line 18)\n lapack_opt_32091 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 18, 18), 'lapack_opt', False)\n # Obtaining the member 'pop' of a type (line 18)\n pop_32092 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 18, 18), lapack_opt_32091, 'pop')\n # Calling pop(args, kwargs) (line 18)\n pop_call_result_32096 = invoke(stypy.reporting.localization.Localization(__file__, 18, 18), pop_32092, *[str_32093, list_32094], **kwargs_32095)\n \n # Assigning a type to the variable 'lapack_libs' (line 18)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 18, 4), 'lapack_libs', pop_call_result_32096)\n \n # Assigning a List to a Name (line 20):\n \n # Obtaining an instance of the builtin type 'list' (line 20)\n list_32097 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 20, 15), 'list')\n # Adding type elements to the builtin type 'list' instance (line 20)\n # Adding element type (line 20)\n \n # Call to join(...): (line 20)\n # Processing the call arguments (line 20)\n str_32099 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 20, 21), 'str', 'mach')\n str_32100 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 20, 28), 'str', '*.f')\n # Processing the call keyword arguments (line 20)\n kwargs_32101 = {}\n # Getting the type of 'join' (line 20)\n join_32098 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 20, 16), 'join', False)\n # Calling join(args, kwargs) (line 20)\n join_call_result_32102 = invoke(stypy.reporting.localization.Localization(__file__, 20, 16), join_32098, *[str_32099, str_32100], **kwargs_32101)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 20, 15), list_32097, join_call_result_32102)\n \n # Assigning a type to the variable 'mach_src' (line 20)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 20, 4), 'mach_src', list_32097)\n \n # Assigning a List to a Name (line 21):\n \n # Obtaining an instance of the builtin type 'list' (line 21)\n list_32103 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 21, 19), 'list')\n # Adding type elements to the builtin type 'list' instance (line 21)\n # Adding element type (line 21)\n \n # Call to join(...): (line 21)\n # Processing the call arguments (line 21)\n str_32105 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 21, 25), 'str', 'quadpack')\n str_32106 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 21, 37), 'str', '*.f')\n # Processing the call keyword arguments (line 21)\n kwargs_32107 = {}\n # Getting the type of 'join' (line 21)\n join_32104 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 21, 20), 'join', False)\n # Calling join(args, kwargs) (line 21)\n join_call_result_32108 = invoke(stypy.reporting.localization.Localization(__file__, 21, 20), join_32104, *[str_32105, str_32106], **kwargs_32107)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 21, 19), list_32103, join_call_result_32108)\n \n # Assigning a type to the variable 'quadpack_src' (line 21)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 21, 4), 'quadpack_src', list_32103)\n \n # Assigning a ListComp to a Name (line 22):\n # Calculating list comprehension\n # Calculating comprehension expression\n \n # Obtaining an instance of the builtin type 'list' (line 22)\n list_32114 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 22, 47), 'list')\n # Adding type elements to the builtin type 'list' instance (line 22)\n # Adding element type (line 22)\n str_32115 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 23, 8), 'str', 'blkdta000.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32115)\n # Adding element type (line 22)\n str_32116 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 23, 23), 'str', 'bnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32116)\n # Adding element type (line 22)\n str_32117 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 23, 34), 'str', 'cfode.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32117)\n # Adding element type (line 22)\n str_32118 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 24, 8), 'str', 'ewset.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32118)\n # Adding element type (line 22)\n str_32119 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 24, 19), 'str', 'fnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32119)\n # Adding element type (line 22)\n str_32120 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 24, 30), 'str', 'intdy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32120)\n # Adding element type (line 22)\n str_32121 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 8), 'str', 'lsoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32121)\n # Adding element type (line 22)\n str_32122 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 19), 'str', 'prja.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32122)\n # Adding element type (line 22)\n str_32123 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 29), 'str', 'solsy.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32123)\n # Adding element type (line 22)\n str_32124 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 25, 40), 'str', 'srcma.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32124)\n # Adding element type (line 22)\n str_32125 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 8), 'str', 'stoda.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32125)\n # Adding element type (line 22)\n str_32126 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 19), 'str', 'vmnorm.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32126)\n # Adding element type (line 22)\n str_32127 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 31), 'str', 'xerrwv.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32127)\n # Adding element type (line 22)\n str_32128 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 26, 43), 'str', 'xsetf.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32128)\n # Adding element type (line 22)\n str_32129 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 27, 8), 'str', 'xsetun.f')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 47), list_32114, str_32129)\n \n comprehension_32130 = get_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 17), list_32114)\n # Assigning a type to the variable 'fn' (line 22)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 22, 17), 'fn', comprehension_32130)\n \n # Call to join(...): (line 22)\n # Processing the call arguments (line 22)\n str_32110 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 22, 22), 'str', 'odepack')\n # Getting the type of 'fn' (line 22)\n fn_32111 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 22, 33), 'fn', False)\n # Processing the call keyword arguments (line 22)\n kwargs_32112 = {}\n # Getting the type of 'join' (line 22)\n join_32109 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 22, 17), 'join', False)\n # Calling join(args, kwargs) (line 22)\n join_call_result_32113 = invoke(stypy.reporting.localization.Localization(__file__, 22, 17), join_32109, *[str_32110, fn_32111], **kwargs_32112)\n \n list_32131 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 22, 17), 'list')\n set_contained_elements_type(stypy.reporting.localization.Localization(__file__, 22, 17), list_32131, join_call_result_32113)\n # Assigning a type to the variable 'lsoda_src' (line 22)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 22, 4), 'lsoda_src', list_32131)\n \n # Assigning a List to a Name (line 28):\n \n # Obtaining an instance of the builtin type 'list' (line 28)\n list_32132 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 15), 'list')\n # Adding type elements to the builtin type 'list' instance (line 28)\n # Adding element type (line 28)\n \n # Call to join(...): (line 28)\n # Processing the call arguments (line 28)\n str_32134 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 21), 'str', 'odepack')\n str_32135 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 32), 'str', 'vode.f')\n # Processing the call keyword arguments (line 28)\n kwargs_32136 = {}\n # Getting the type of 'join' (line 28)\n join_32133 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 28, 16), 'join', False)\n # Calling join(args, kwargs) (line 28)\n join_call_result_32137 = invoke(stypy.reporting.localization.Localization(__file__, 28, 16), join_32133, *[str_32134, str_32135], **kwargs_32136)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 28, 15), list_32132, join_call_result_32137)\n # Adding element type (line 28)\n \n # Call to join(...): (line 28)\n # Processing the call arguments (line 28)\n str_32139 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 48), 'str', 'odepack')\n str_32140 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 28, 59), 'str', 'zvode.f')\n # Processing the call keyword arguments (line 28)\n kwargs_32141 = {}\n # Getting the type of 'join' (line 28)\n join_32138 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 28, 43), 'join', False)\n # Calling join(args, kwargs) (line 28)\n join_call_result_32142 = invoke(stypy.reporting.localization.Localization(__file__, 28, 43), join_32138, *[str_32139, str_32140], **kwargs_32141)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 28, 15), list_32132, join_call_result_32142)\n \n # Assigning a type to the variable 'vode_src' (line 28)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 28, 4), 'vode_src', list_32132)\n \n # Assigning a List to a Name (line 29):\n \n # Obtaining an instance of the builtin type 'list' (line 29)\n list_32143 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 29, 14), 'list')\n # Adding type elements to the builtin type 'list' instance (line 29)\n # Adding element type (line 29)\n \n # Call to join(...): (line 29)\n # Processing the call arguments (line 29)\n str_32145 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 29, 20), 'str', 'dop')\n str_32146 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 29, 26), 'str', '*.f')\n # Processing the call keyword arguments (line 29)\n kwargs_32147 = {}\n # Getting the type of 'join' (line 29)\n join_32144 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 29, 15), 'join', False)\n # Calling join(args, kwargs) (line 29)\n join_call_result_32148 = invoke(stypy.reporting.localization.Localization(__file__, 29, 15), join_32144, *[str_32145, str_32146], **kwargs_32147)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 29, 14), list_32143, join_call_result_32148)\n \n # Assigning a type to the variable 'dop_src' (line 29)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 29, 4), 'dop_src', list_32143)\n \n # Assigning a List to a Name (line 30):\n \n # Obtaining an instance of the builtin type 'list' (line 30)\n list_32149 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 30, 24), 'list')\n # Adding type elements to the builtin type 'list' instance (line 30)\n # Adding element type (line 30)\n \n # Call to join(...): (line 30)\n # Processing the call arguments (line 30)\n str_32151 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 30, 30), 'str', 'tests')\n str_32152 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 30, 38), 'str', '_test_multivariate.c')\n # Processing the call keyword arguments (line 30)\n kwargs_32153 = {}\n # Getting the type of 'join' (line 30)\n join_32150 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 30, 25), 'join', False)\n # Calling join(args, kwargs) (line 30)\n join_call_result_32154 = invoke(stypy.reporting.localization.Localization(__file__, 30, 25), join_32150, *[str_32151, str_32152], **kwargs_32153)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 30, 24), list_32149, join_call_result_32154)\n \n # Assigning a type to the variable 'quadpack_test_src' (line 30)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 30, 4), 'quadpack_test_src', list_32149)\n \n # Assigning a List to a Name (line 31):\n \n # Obtaining an instance of the builtin type 'list' (line 31)\n list_32155 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 31, 29), 'list')\n # Adding type elements to the builtin type 'list' instance (line 31)\n # Adding element type (line 31)\n \n # Call to join(...): (line 31)\n # Processing the call arguments (line 31)\n str_32157 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 31, 35), 'str', 'tests')\n str_32158 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 31, 44), 'str', 'banded5x5.f')\n # Processing the call keyword arguments (line 31)\n kwargs_32159 = {}\n # Getting the type of 'join' (line 31)\n join_32156 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 31, 30), 'join', False)\n # Calling join(args, kwargs) (line 31)\n join_call_result_32160 = invoke(stypy.reporting.localization.Localization(__file__, 31, 30), join_32156, *[str_32157, str_32158], **kwargs_32159)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 31, 29), list_32155, join_call_result_32160)\n \n # Assigning a type to the variable 'odeint_banded_test_src' (line 31)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 31, 4), 'odeint_banded_test_src', list_32155)\n \n # Call to add_library(...): (line 33)\n # Processing the call arguments (line 33)\n str_32163 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 33, 23), 'str', 'mach')\n # Processing the call keyword arguments (line 33)\n # Getting the type of 'mach_src' (line 33)\n mach_src_32164 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 33, 39), 'mach_src', False)\n keyword_32165 = mach_src_32164\n \n # Obtaining an instance of the builtin type 'dict' (line 34)\n dict_32166 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 33), 'dict')\n # Adding type elements to the builtin type 'dict' instance (line 34)\n # Adding element type (key, value) (line 34)\n str_32167 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 34), 'str', 'noopt')\n \n # Obtaining an instance of the builtin type 'tuple' (line 34)\n tuple_32168 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 43), 'tuple')\n # Adding type elements to the builtin type 'tuple' instance (line 34)\n # Adding element type (line 34)\n # Getting the type of '__file__' (line 34)\n file___32169 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 34, 43), '__file__', False)\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 34, 43), tuple_32168, file___32169)\n # Adding element type (line 34)\n int_32170 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 34, 52), 'int')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 34, 43), tuple_32168, int_32170)\n \n set_contained_elements_type(stypy.reporting.localization.Localization(__file__, 34, 33), dict_32166, (str_32167, tuple_32168))\n \n keyword_32171 = dict_32166\n kwargs_32172 = {'sources': keyword_32165, 'config_fc': keyword_32171}\n # Getting the type of 'config' (line 33)\n config_32161 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 33, 4), 'config', False)\n # Obtaining the member 'add_library' of a type (line 33)\n add_library_32162 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 33, 4), config_32161, 'add_library')\n # Calling add_library(args, kwargs) (line 33)\n add_library_call_result_32173 = invoke(stypy.reporting.localization.Localization(__file__, 33, 4), add_library_32162, *[str_32163], **kwargs_32172)\n \n \n # Call to add_library(...): (line 35)\n # Processing the call arguments (line 35)\n str_32176 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 35, 23), 'str', 'quadpack')\n # Processing the call keyword arguments (line 35)\n # Getting the type of 'quadpack_src' (line 35)\n quadpack_src_32177 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 35, 43), 'quadpack_src', False)\n keyword_32178 = quadpack_src_32177\n kwargs_32179 = {'sources': keyword_32178}\n # Getting the type of 'config' (line 35)\n config_32174 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 35, 4), 'config', False)\n # Obtaining the member 'add_library' of a type (line 35)\n add_library_32175 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 35, 4), config_32174, 'add_library')\n # Calling add_library(args, kwargs) (line 35)\n add_library_call_result_32180 = invoke(stypy.reporting.localization.Localization(__file__, 35, 4), add_library_32175, *[str_32176], **kwargs_32179)\n \n \n # Call to add_library(...): (line 36)\n # Processing the call arguments (line 36)\n str_32183 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 36, 23), 'str', 'lsoda')\n # Processing the call keyword arguments (line 36)\n # Getting the type of 'lsoda_src' (line 36)\n lsoda_src_32184 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 36, 40), 'lsoda_src', False)\n keyword_32185 = lsoda_src_32184\n kwargs_32186 = {'sources': keyword_32185}\n # Getting the type of 'config' (line 36)\n config_32181 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 36, 4), 'config', False)\n # Obtaining the member 'add_library' of a type (line 36)\n add_library_32182 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 36, 4), config_32181, 'add_library')\n # Calling add_library(args, kwargs) (line 36)\n add_library_call_result_32187 = invoke(stypy.reporting.localization.Localization(__file__, 36, 4), add_library_32182, *[str_32183], **kwargs_32186)\n \n \n # Call to add_library(...): (line 37)\n # Processing the call arguments (line 37)\n str_32190 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 37, 23), 'str', 'vode')\n # Processing the call keyword arguments (line 37)\n # Getting the type of 'vode_src' (line 37)\n vode_src_32191 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 37, 39), 'vode_src', False)\n keyword_32192 = vode_src_32191\n kwargs_32193 = {'sources': keyword_32192}\n # Getting the type of 'config' (line 37)\n config_32188 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 37, 4), 'config', False)\n # Obtaining the member 'add_library' of a type (line 37)\n add_library_32189 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 37, 4), config_32188, 'add_library')\n # Calling add_library(args, kwargs) (line 37)\n add_library_call_result_32194 = invoke(stypy.reporting.localization.Localization(__file__, 37, 4), add_library_32189, *[str_32190], **kwargs_32193)\n \n \n # Call to add_library(...): (line 38)\n # Processing the call arguments (line 38)\n str_32197 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 38, 23), 'str', 'dop')\n # Processing the call keyword arguments (line 38)\n # Getting the type of 'dop_src' (line 38)\n dop_src_32198 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 38, 38), 'dop_src', False)\n keyword_32199 = dop_src_32198\n kwargs_32200 = {'sources': keyword_32199}\n # Getting the type of 'config' (line 38)\n config_32195 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 38, 4), 'config', False)\n # Obtaining the member 'add_library' of a type (line 38)\n add_library_32196 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 38, 4), config_32195, 'add_library')\n # Calling add_library(args, kwargs) (line 38)\n add_library_call_result_32201 = invoke(stypy.reporting.localization.Localization(__file__, 38, 4), add_library_32196, *[str_32197], **kwargs_32200)\n \n \n # Assigning a List to a Name (line 42):\n \n # Obtaining an instance of the builtin type 'list' (line 42)\n list_32202 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 19), 'list')\n # Adding type elements to the builtin type 'list' instance (line 42)\n # Adding element type (line 42)\n \n # Call to join(...): (line 42)\n # Processing the call arguments (line 42)\n \n # Call to dirname(...): (line 42)\n # Processing the call arguments (line 42)\n # Getting the type of '__file__' (line 42)\n file___32207 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 42, 41), '__file__', False)\n # Processing the call keyword arguments (line 42)\n kwargs_32208 = {}\n # Getting the type of 'os' (line 42)\n os_32204 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 42, 25), 'os', False)\n # Obtaining the member 'path' of a type (line 42)\n path_32205 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 42, 25), os_32204, 'path')\n # Obtaining the member 'dirname' of a type (line 42)\n dirname_32206 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 42, 25), path_32205, 'dirname')\n # Calling dirname(args, kwargs) (line 42)\n dirname_call_result_32209 = invoke(stypy.reporting.localization.Localization(__file__, 42, 25), dirname_32206, *[file___32207], **kwargs_32208)\n \n str_32210 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 52), 'str', '..')\n str_32211 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 58), 'str', '_lib')\n str_32212 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 42, 66), 'str', 'src')\n # Processing the call keyword arguments (line 42)\n kwargs_32213 = {}\n # Getting the type of 'join' (line 42)\n join_32203 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 42, 20), 'join', False)\n # Calling join(args, kwargs) (line 42)\n join_call_result_32214 = invoke(stypy.reporting.localization.Localization(__file__, 42, 20), join_32203, *[dirname_call_result_32209, str_32210, str_32211, str_32212], **kwargs_32213)\n \n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 42, 19), list_32202, join_call_result_32214)\n \n # Assigning a type to the variable 'include_dirs' (line 42)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 42, 4), 'include_dirs', list_32202)\n \n \n str_32215 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 43, 7), 'str', 'include_dirs')\n # Getting the type of 'lapack_opt' (line 43)\n lapack_opt_32216 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 43, 25), 'lapack_opt')\n # Applying the binary operator 'in' (line 43)\n result_contains_32217 = python_operator(stypy.reporting.localization.Localization(__file__, 43, 7), 'in', str_32215, lapack_opt_32216)\n \n # Testing the type of an if condition (line 43)\n if_condition_32218 = is_suitable_condition(stypy.reporting.localization.Localization(__file__, 43, 4), result_contains_32217)\n # Assigning a type to the variable 'if_condition_32218' (line 43)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 43, 4), 'if_condition_32218', if_condition_32218)\n # SSA begins for if statement (line 43)\n module_type_store = SSAContext.create_ssa_context(module_type_store, 'if')\n \n # Assigning a Call to a Name (line 44):\n \n # Call to dict(...): (line 44)\n # Processing the call arguments (line 44)\n # Getting the type of 'lapack_opt' (line 44)\n lapack_opt_32220 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 44, 26), 'lapack_opt', False)\n # Processing the call keyword arguments (line 44)\n kwargs_32221 = {}\n # Getting the type of 'dict' (line 44)\n dict_32219 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 44, 21), 'dict', False)\n # Calling dict(args, kwargs) (line 44)\n dict_call_result_32222 = invoke(stypy.reporting.localization.Localization(__file__, 44, 21), dict_32219, *[lapack_opt_32220], **kwargs_32221)\n \n # Assigning a type to the variable 'lapack_opt' (line 44)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 44, 8), 'lapack_opt', dict_call_result_32222)\n \n # Call to extend(...): (line 45)\n # Processing the call arguments (line 45)\n \n # Call to pop(...): (line 45)\n # Processing the call arguments (line 45)\n str_32227 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 45, 43), 'str', 'include_dirs')\n # Processing the call keyword arguments (line 45)\n kwargs_32228 = {}\n # Getting the type of 'lapack_opt' (line 45)\n lapack_opt_32225 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 45, 28), 'lapack_opt', False)\n # Obtaining the member 'pop' of a type (line 45)\n pop_32226 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 45, 28), lapack_opt_32225, 'pop')\n # Calling pop(args, kwargs) (line 45)\n pop_call_result_32229 = invoke(stypy.reporting.localization.Localization(__file__, 45, 28), pop_32226, *[str_32227], **kwargs_32228)\n \n # Processing the call keyword arguments (line 45)\n kwargs_32230 = {}\n # Getting the type of 'include_dirs' (line 45)\n include_dirs_32223 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 45, 8), 'include_dirs', False)\n # Obtaining the member 'extend' of a type (line 45)\n extend_32224 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 45, 8), include_dirs_32223, 'extend')\n # Calling extend(args, kwargs) (line 45)\n extend_call_result_32231 = invoke(stypy.reporting.localization.Localization(__file__, 45, 8), extend_32224, *[pop_call_result_32229], **kwargs_32230)\n \n # SSA join for if statement (line 43)\n module_type_store = module_type_store.join_ssa_context()\n \n \n # Call to add_extension(...): (line 47)\n # Processing the call arguments (line 47)\n str_32234 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 47, 25), 'str', '_quadpack')\n # Processing the call keyword arguments (line 47)\n \n # Obtaining an instance of the builtin type 'list' (line 48)\n list_32235 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 48, 33), 'list')\n # Adding type elements to the builtin type 'list' instance (line 48)\n # Adding element type (line 48)\n str_32236 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 48, 34), 'str', '_quadpackmodule.c')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 48, 33), list_32235, str_32236)\n \n keyword_32237 = list_32235\n \n # Obtaining an instance of the builtin type 'list' (line 49)\n list_32238 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 49, 35), 'list')\n # Adding type elements to the builtin type 'list' instance (line 49)\n # Adding element type (line 49)\n str_32239 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 49, 36), 'str', 'quadpack')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 49, 35), list_32238, str_32239)\n # Adding element type (line 49)\n str_32240 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 49, 48), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 49, 35), list_32238, str_32240)\n \n # Getting the type of 'lapack_libs' (line 49)\n lapack_libs_32241 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 49, 58), 'lapack_libs', False)\n # Applying the binary operator '+' (line 49)\n result_add_32242 = python_operator(stypy.reporting.localization.Localization(__file__, 49, 35), '+', list_32238, lapack_libs_32241)\n \n keyword_32243 = result_add_32242\n \n # Obtaining an instance of the builtin type 'list' (line 50)\n list_32244 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 50, 34), 'list')\n # Adding type elements to the builtin type 'list' instance (line 50)\n # Adding element type (line 50)\n str_32245 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 50, 35), 'str', '__quadpack.h')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 50, 34), list_32244, str_32245)\n \n # Getting the type of 'quadpack_src' (line 51)\n quadpack_src_32246 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 51, 36), 'quadpack_src', False)\n # Applying the binary operator '+' (line 50)\n result_add_32247 = python_operator(stypy.reporting.localization.Localization(__file__, 50, 34), '+', list_32244, quadpack_src_32246)\n \n # Getting the type of 'mach_src' (line 51)\n mach_src_32248 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 51, 51), 'mach_src', False)\n # Applying the binary operator '+' (line 51)\n result_add_32249 = python_operator(stypy.reporting.localization.Localization(__file__, 51, 49), '+', result_add_32247, mach_src_32248)\n \n keyword_32250 = result_add_32249\n # Getting the type of 'include_dirs' (line 52)\n include_dirs_32251 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 52, 38), 'include_dirs', False)\n keyword_32252 = include_dirs_32251\n # Getting the type of 'lapack_opt' (line 53)\n lapack_opt_32253 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 53, 27), 'lapack_opt', False)\n kwargs_32254 = {'libraries': keyword_32243, 'sources': keyword_32237, 'depends': keyword_32250, 'lapack_opt_32253': lapack_opt_32253, 'include_dirs': keyword_32252}\n # Getting the type of 'config' (line 47)\n config_32232 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 47, 4), 'config', False)\n # Obtaining the member 'add_extension' of a type (line 47)\n add_extension_32233 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 47, 4), config_32232, 'add_extension')\n # Calling add_extension(args, kwargs) (line 47)\n add_extension_call_result_32255 = invoke(stypy.reporting.localization.Localization(__file__, 47, 4), add_extension_32233, *[str_32234], **kwargs_32254)\n \n \n # Assigning a Call to a Name (line 56):\n \n # Call to copy(...): (line 56)\n # Processing the call keyword arguments (line 56)\n kwargs_32258 = {}\n # Getting the type of 'lapack_opt' (line 56)\n lapack_opt_32256 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 56, 19), 'lapack_opt', False)\n # Obtaining the member 'copy' of a type (line 56)\n copy_32257 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 56, 19), lapack_opt_32256, 'copy')\n # Calling copy(args, kwargs) (line 56)\n copy_call_result_32259 = invoke(stypy.reporting.localization.Localization(__file__, 56, 19), copy_32257, *[], **kwargs_32258)\n \n # Assigning a type to the variable 'odepack_opts' (line 56)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 56, 4), 'odepack_opts', copy_call_result_32259)\n \n # Call to update(...): (line 57)\n # Processing the call arguments (line 57)\n # Getting the type of 'numpy_nodepr_api' (line 57)\n numpy_nodepr_api_32262 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 57, 24), 'numpy_nodepr_api', False)\n # Processing the call keyword arguments (line 57)\n kwargs_32263 = {}\n # Getting the type of 'odepack_opts' (line 57)\n odepack_opts_32260 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 57, 4), 'odepack_opts', False)\n # Obtaining the member 'update' of a type (line 57)\n update_32261 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 57, 4), odepack_opts_32260, 'update')\n # Calling update(args, kwargs) (line 57)\n update_call_result_32264 = invoke(stypy.reporting.localization.Localization(__file__, 57, 4), update_32261, *[numpy_nodepr_api_32262], **kwargs_32263)\n \n \n # Call to add_extension(...): (line 58)\n # Processing the call arguments (line 58)\n str_32267 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 58, 25), 'str', '_odepack')\n # Processing the call keyword arguments (line 58)\n \n # Obtaining an instance of the builtin type 'list' (line 59)\n list_32268 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 59, 33), 'list')\n # Adding type elements to the builtin type 'list' instance (line 59)\n # Adding element type (line 59)\n str_32269 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 59, 34), 'str', '_odepackmodule.c')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 59, 33), list_32268, str_32269)\n \n keyword_32270 = list_32268\n \n # Obtaining an instance of the builtin type 'list' (line 60)\n list_32271 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 60, 35), 'list')\n # Adding type elements to the builtin type 'list' instance (line 60)\n # Adding element type (line 60)\n str_32272 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 60, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 60, 35), list_32271, str_32272)\n # Adding element type (line 60)\n str_32273 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 60, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 60, 35), list_32271, str_32273)\n \n # Getting the type of 'lapack_libs' (line 60)\n lapack_libs_32274 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 60, 55), 'lapack_libs', False)\n # Applying the binary operator '+' (line 60)\n result_add_32275 = python_operator(stypy.reporting.localization.Localization(__file__, 60, 35), '+', list_32271, lapack_libs_32274)\n \n keyword_32276 = result_add_32275\n # Getting the type of 'lsoda_src' (line 61)\n lsoda_src_32277 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 61, 34), 'lsoda_src', False)\n # Getting the type of 'mach_src' (line 61)\n mach_src_32278 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 61, 46), 'mach_src', False)\n # Applying the binary operator '+' (line 61)\n result_add_32279 = python_operator(stypy.reporting.localization.Localization(__file__, 61, 34), '+', lsoda_src_32277, mach_src_32278)\n \n keyword_32280 = result_add_32279\n # Getting the type of 'odepack_opts' (line 62)\n odepack_opts_32281 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 62, 27), 'odepack_opts', False)\n kwargs_32282 = {'libraries': keyword_32276, 'sources': keyword_32270, 'depends': keyword_32280, 'odepack_opts_32281': odepack_opts_32281}\n # Getting the type of 'config' (line 58)\n config_32265 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 58, 4), 'config', False)\n # Obtaining the member 'add_extension' of a type (line 58)\n add_extension_32266 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 58, 4), config_32265, 'add_extension')\n # Calling add_extension(args, kwargs) (line 58)\n add_extension_call_result_32283 = invoke(stypy.reporting.localization.Localization(__file__, 58, 4), add_extension_32266, *[str_32267], **kwargs_32282)\n \n \n # Call to add_extension(...): (line 65)\n # Processing the call arguments (line 65)\n str_32286 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 65, 25), 'str', 'vode')\n # Processing the call keyword arguments (line 65)\n \n # Obtaining an instance of the builtin type 'list' (line 66)\n list_32287 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 66, 33), 'list')\n # Adding type elements to the builtin type 'list' instance (line 66)\n # Adding element type (line 66)\n str_32288 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 66, 34), 'str', 'vode.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 66, 33), list_32287, str_32288)\n \n keyword_32289 = list_32287\n \n # Obtaining an instance of the builtin type 'list' (line 67)\n list_32290 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 67, 35), 'list')\n # Adding type elements to the builtin type 'list' instance (line 67)\n # Adding element type (line 67)\n str_32291 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 67, 36), 'str', 'vode')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 67, 35), list_32290, str_32291)\n \n # Getting the type of 'lapack_libs' (line 67)\n lapack_libs_32292 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 67, 46), 'lapack_libs', False)\n # Applying the binary operator '+' (line 67)\n result_add_32293 = python_operator(stypy.reporting.localization.Localization(__file__, 67, 35), '+', list_32290, lapack_libs_32292)\n \n keyword_32294 = result_add_32293\n # Getting the type of 'vode_src' (line 68)\n vode_src_32295 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 68, 33), 'vode_src', False)\n keyword_32296 = vode_src_32295\n # Getting the type of 'lapack_opt' (line 69)\n lapack_opt_32297 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 69, 27), 'lapack_opt', False)\n kwargs_32298 = {'libraries': keyword_32294, 'sources': keyword_32289, 'depends': keyword_32296, 'lapack_opt_32297': lapack_opt_32297}\n # Getting the type of 'config' (line 65)\n config_32284 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 65, 4), 'config', False)\n # Obtaining the member 'add_extension' of a type (line 65)\n add_extension_32285 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 65, 4), config_32284, 'add_extension')\n # Calling add_extension(args, kwargs) (line 65)\n add_extension_call_result_32299 = invoke(stypy.reporting.localization.Localization(__file__, 65, 4), add_extension_32285, *[str_32286], **kwargs_32298)\n \n \n # Call to add_extension(...): (line 72)\n # Processing the call arguments (line 72)\n str_32302 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 72, 25), 'str', 'lsoda')\n # Processing the call keyword arguments (line 72)\n \n # Obtaining an instance of the builtin type 'list' (line 73)\n list_32303 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 73, 33), 'list')\n # Adding type elements to the builtin type 'list' instance (line 73)\n # Adding element type (line 73)\n str_32304 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 73, 34), 'str', 'lsoda.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 73, 33), list_32303, str_32304)\n \n keyword_32305 = list_32303\n \n # Obtaining an instance of the builtin type 'list' (line 74)\n list_32306 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 74, 35), 'list')\n # Adding type elements to the builtin type 'list' instance (line 74)\n # Adding element type (line 74)\n str_32307 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 74, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 74, 35), list_32306, str_32307)\n # Adding element type (line 74)\n str_32308 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 74, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 74, 35), list_32306, str_32308)\n \n # Getting the type of 'lapack_libs' (line 74)\n lapack_libs_32309 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 74, 55), 'lapack_libs', False)\n # Applying the binary operator '+' (line 74)\n result_add_32310 = python_operator(stypy.reporting.localization.Localization(__file__, 74, 35), '+', list_32306, lapack_libs_32309)\n \n keyword_32311 = result_add_32310\n # Getting the type of 'lsoda_src' (line 75)\n lsoda_src_32312 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 75, 34), 'lsoda_src', False)\n # Getting the type of 'mach_src' (line 75)\n mach_src_32313 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 75, 46), 'mach_src', False)\n # Applying the binary operator '+' (line 75)\n result_add_32314 = python_operator(stypy.reporting.localization.Localization(__file__, 75, 34), '+', lsoda_src_32312, mach_src_32313)\n \n keyword_32315 = result_add_32314\n # Getting the type of 'lapack_opt' (line 76)\n lapack_opt_32316 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 76, 27), 'lapack_opt', False)\n kwargs_32317 = {'libraries': keyword_32311, 'sources': keyword_32305, 'depends': keyword_32315, 'lapack_opt_32316': lapack_opt_32316}\n # Getting the type of 'config' (line 72)\n config_32300 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 72, 4), 'config', False)\n # Obtaining the member 'add_extension' of a type (line 72)\n add_extension_32301 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 72, 4), config_32300, 'add_extension')\n # Calling add_extension(args, kwargs) (line 72)\n add_extension_call_result_32318 = invoke(stypy.reporting.localization.Localization(__file__, 72, 4), add_extension_32301, *[str_32302], **kwargs_32317)\n \n \n # Call to add_extension(...): (line 79)\n # Processing the call arguments (line 79)\n str_32321 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 79, 25), 'str', '_dop')\n # Processing the call keyword arguments (line 79)\n \n # Obtaining an instance of the builtin type 'list' (line 80)\n list_32322 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 80, 33), 'list')\n # Adding type elements to the builtin type 'list' instance (line 80)\n # Adding element type (line 80)\n str_32323 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 80, 34), 'str', 'dop.pyf')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 80, 33), list_32322, str_32323)\n \n keyword_32324 = list_32322\n \n # Obtaining an instance of the builtin type 'list' (line 81)\n list_32325 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 81, 35), 'list')\n # Adding type elements to the builtin type 'list' instance (line 81)\n # Adding element type (line 81)\n str_32326 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 81, 36), 'str', 'dop')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 81, 35), list_32325, str_32326)\n \n keyword_32327 = list_32325\n # Getting the type of 'dop_src' (line 82)\n dop_src_32328 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 82, 33), 'dop_src', False)\n keyword_32329 = dop_src_32328\n kwargs_32330 = {'libraries': keyword_32327, 'sources': keyword_32324, 'depends': keyword_32329}\n # Getting the type of 'config' (line 79)\n config_32319 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 79, 4), 'config', False)\n # Obtaining the member 'add_extension' of a type (line 79)\n add_extension_32320 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 79, 4), config_32319, 'add_extension')\n # Calling add_extension(args, kwargs) (line 79)\n add_extension_call_result_32331 = invoke(stypy.reporting.localization.Localization(__file__, 79, 4), add_extension_32320, *[str_32321], **kwargs_32330)\n \n \n # Call to add_extension(...): (line 84)\n # Processing the call arguments (line 84)\n str_32334 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 84, 25), 'str', '_test_multivariate')\n # Processing the call keyword arguments (line 84)\n # Getting the type of 'quadpack_test_src' (line 85)\n quadpack_test_src_32335 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 85, 33), 'quadpack_test_src', False)\n keyword_32336 = quadpack_test_src_32335\n kwargs_32337 = {'sources': keyword_32336}\n # Getting the type of 'config' (line 84)\n config_32332 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 84, 4), 'config', False)\n # Obtaining the member 'add_extension' of a type (line 84)\n add_extension_32333 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 84, 4), config_32332, 'add_extension')\n # Calling add_extension(args, kwargs) (line 84)\n add_extension_call_result_32338 = invoke(stypy.reporting.localization.Localization(__file__, 84, 4), add_extension_32333, *[str_32334], **kwargs_32337)\n \n \n # Call to add_extension(...): (line 88)\n # Processing the call arguments (line 88)\n str_32341 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 88, 25), 'str', '_test_odeint_banded')\n # Processing the call keyword arguments (line 88)\n # Getting the type of 'odeint_banded_test_src' (line 89)\n odeint_banded_test_src_32342 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 89, 33), 'odeint_banded_test_src', False)\n keyword_32343 = odeint_banded_test_src_32342\n \n # Obtaining an instance of the builtin type 'list' (line 90)\n list_32344 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 90, 35), 'list')\n # Adding type elements to the builtin type 'list' instance (line 90)\n # Adding element type (line 90)\n str_32345 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 90, 36), 'str', 'lsoda')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 90, 35), list_32344, str_32345)\n # Adding element type (line 90)\n str_32346 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 90, 45), 'str', 'mach')\n add_contained_elements_type(stypy.reporting.localization.Localization(__file__, 90, 35), list_32344, str_32346)\n \n # Getting the type of 'lapack_libs' (line 90)\n lapack_libs_32347 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 90, 55), 'lapack_libs', False)\n # Applying the binary operator '+' (line 90)\n result_add_32348 = python_operator(stypy.reporting.localization.Localization(__file__, 90, 35), '+', list_32344, lapack_libs_32347)\n \n keyword_32349 = result_add_32348\n # Getting the type of 'lsoda_src' (line 91)\n lsoda_src_32350 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 91, 34), 'lsoda_src', False)\n # Getting the type of 'mach_src' (line 91)\n mach_src_32351 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 91, 46), 'mach_src', False)\n # Applying the binary operator '+' (line 91)\n result_add_32352 = python_operator(stypy.reporting.localization.Localization(__file__, 91, 34), '+', lsoda_src_32350, mach_src_32351)\n \n keyword_32353 = result_add_32352\n # Getting the type of 'lapack_opt' (line 92)\n lapack_opt_32354 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 92, 27), 'lapack_opt', False)\n kwargs_32355 = {'libraries': keyword_32349, 'sources': keyword_32343, 'depends': keyword_32353, 'lapack_opt_32354': lapack_opt_32354}\n # Getting the type of 'config' (line 88)\n config_32339 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 88, 4), 'config', False)\n # Obtaining the member 'add_extension' of a type (line 88)\n add_extension_32340 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 88, 4), config_32339, 'add_extension')\n # Calling add_extension(args, kwargs) (line 88)\n add_extension_call_result_32356 = invoke(stypy.reporting.localization.Localization(__file__, 88, 4), add_extension_32340, *[str_32341], **kwargs_32355)\n \n \n # Call to add_subpackage(...): (line 94)\n # Processing the call arguments (line 94)\n str_32359 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 94, 26), 'str', '_ivp')\n # Processing the call keyword arguments (line 94)\n kwargs_32360 = {}\n # Getting the type of 'config' (line 94)\n config_32357 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 94, 4), 'config', False)\n # Obtaining the member 'add_subpackage' of a type (line 94)\n add_subpackage_32358 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 94, 4), config_32357, 'add_subpackage')\n # Calling add_subpackage(args, kwargs) (line 94)\n add_subpackage_call_result_32361 = invoke(stypy.reporting.localization.Localization(__file__, 94, 4), add_subpackage_32358, *[str_32359], **kwargs_32360)\n \n \n # Call to add_data_dir(...): (line 96)\n # Processing the call arguments (line 96)\n str_32364 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 96, 24), 'str', 'tests')\n # Processing the call keyword arguments (line 96)\n kwargs_32365 = {}\n # Getting the type of 'config' (line 96)\n config_32362 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 96, 4), 'config', False)\n # Obtaining the member 'add_data_dir' of a type (line 96)\n add_data_dir_32363 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 96, 4), config_32362, 'add_data_dir')\n # Calling add_data_dir(args, kwargs) (line 96)\n add_data_dir_call_result_32366 = invoke(stypy.reporting.localization.Localization(__file__, 96, 4), add_data_dir_32363, *[str_32364], **kwargs_32365)\n \n # Getting the type of 'config' (line 97)\n config_32367 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 97, 11), 'config')\n # Assigning a type to the variable 'stypy_return_type' (line 97)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 97, 4), 'stypy_return_type', config_32367)\n \n # ################# End of 'configuration(...)' code ##################\n\n # Teardown call information\n teardown_call_information(localization, arguments)\n \n # Storing the return type of function 'configuration' in the type store\n # Getting the type of 'stypy_return_type' (line 9)\n stypy_return_type_32368 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 9, 0), 'stypy_return_type')\n module_type_store.store_return_type_of_current_context(stypy_return_type_32368)\n \n # Destroy the current context\n module_type_store = module_type_store.close_function_context()\n \n # Return type of the function 'configuration'\n return stypy_return_type_32368\n\n# Assigning a type to the variable 'configuration' (line 9)\nmodule_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 9, 0), 'configuration', configuration)\n\nif (__name__ == '__main__'):\n stypy.reporting.localization.Localization.set_current(stypy.reporting.localization.Localization(__file__, 101, 4))\n \n # 'from numpy.distutils.core import setup' statement (line 101)\n update_path_to_current_file_folder('C:/Python27/lib/site-packages/scipy/integrate/')\n import_32369 = generate_type_inference_code_for_module(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core')\n\n if (type(import_32369) is not StypyTypeError):\n\n if (import_32369 != 'pyd_module'):\n __import__(import_32369)\n sys_modules_32370 = sys.modules[import_32369]\n import_from_module(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core', sys_modules_32370.module_type_store, module_type_store, ['setup'])\n nest_module(stypy.reporting.localization.Localization(__file__, 101, 4), __file__, sys_modules_32370, sys_modules_32370.module_type_store, module_type_store)\n else:\n from numpy.distutils.core import setup\n\n import_from_module(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core', None, module_type_store, ['setup'], [setup])\n\n else:\n # Assigning a type to the variable 'numpy.distutils.core' (line 101)\n module_type_store.set_type_of(stypy.reporting.localization.Localization(__file__, 101, 4), 'numpy.distutils.core', import_32369)\n\n remove_current_file_folder_from_path('C:/Python27/lib/site-packages/scipy/integrate/')\n \n \n # Call to setup(...): (line 102)\n # Processing the call keyword arguments (line 102)\n \n # Call to todict(...): (line 102)\n # Processing the call keyword arguments (line 102)\n kwargs_32378 = {}\n \n # Call to configuration(...): (line 102)\n # Processing the call keyword arguments (line 102)\n str_32373 = get_builtin_python_type_instance(stypy.reporting.localization.Localization(__file__, 102, 35), 'str', '')\n keyword_32374 = str_32373\n kwargs_32375 = {'top_path': keyword_32374}\n # Getting the type of 'configuration' (line 102)\n configuration_32372 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 102, 12), 'configuration', False)\n # Calling configuration(args, kwargs) (line 102)\n configuration_call_result_32376 = invoke(stypy.reporting.localization.Localization(__file__, 102, 12), configuration_32372, *[], **kwargs_32375)\n \n # Obtaining the member 'todict' of a type (line 102)\n todict_32377 = module_type_store.get_type_of_member(stypy.reporting.localization.Localization(__file__, 102, 12), configuration_call_result_32376, 'todict')\n # Calling todict(args, kwargs) (line 102)\n todict_call_result_32379 = invoke(stypy.reporting.localization.Localization(__file__, 102, 12), todict_32377, *[], **kwargs_32378)\n \n kwargs_32380 = {'todict_call_result_32379': todict_call_result_32379}\n # Getting the type of 'setup' (line 102)\n setup_32371 = module_type_store.get_type_of(stypy.reporting.localization.Localization(__file__, 102, 4), 'setup', False)\n # Calling setup(args, kwargs) (line 102)\n setup_call_result_32381 = invoke(stypy.reporting.localization.Localization(__file__, 102, 4), setup_32371, *[], **kwargs_32380)\n \n\n\n# ################# End of the type inference program ##################\n\nmodule_errors = stypy.errors.type_error.StypyTypeError.get_error_msgs()\nmodule_warnings = stypy.errors.type_warning.TypeWarning.get_warning_msgs()\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> @app.route('/healthz') def healthz(): return 'ok' @app.route('/alive') def alive(): return 'ok' @app.route('/hello') def hello(): myhost = os.uname()[1] body = 'V1 - Hello World! - %s' % myhost return body <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @app.route('/healthz') def healthz(): return 'ok' @app.route('/alive') def alive(): return 'ok' @app.route('/hello') def hello(): myhost = os.uname()[1] body = 'V1 - Hello World! - %s' % myhost return body if __name__ == '__main__': from waitress import serve serve(app, host='0.0.0.0', port=80) <|reserved_special_token_1|> <|reserved_special_token_0|> app = Flask(__name__) @app.route('/healthz') def healthz(): return 'ok' @app.route('/alive') def alive(): return 'ok' @app.route('/hello') def hello(): myhost = os.uname()[1] body = 'V1 - Hello World! - %s' % myhost return body if __name__ == '__main__': from waitress import serve serve(app, host='0.0.0.0', port=80) <|reserved_special_token_1|> from flask import Flask import os app = Flask(__name__) @app.route('/healthz') def healthz(): return 'ok' @app.route('/alive') def alive(): return 'ok' @app.route('/hello') def hello(): myhost = os.uname()[1] body = 'V1 - Hello World! - %s' % myhost return body if __name__ == '__main__': from waitress import serve serve(app, host='0.0.0.0', port=80) <|reserved_special_token_1|> from flask import Flask import os app = Flask(__name__) @app.route("/healthz") def healthz(): return "ok" @app.route("/alive") def alive(): return "ok" @app.route("/hello") # def healthz(): # introduces application crash bug def hello(): myhost = os.uname()[1] body = ("V1 - Hello World! - %s" % myhost) # body = ("V2 - Hello World! - %s" % myhost) return body if __name__ == "__main__": from waitress import serve serve(app, host="0.0.0.0", port=80)
flexible
{ "blob_id": "0259fddbe3ce030030a508ce7118a6a03930aa51", "index": 7375, "step-1": "<mask token>\n\n\[email protected]('/healthz')\ndef healthz():\n return 'ok'\n\n\[email protected]('/alive')\ndef alive():\n return 'ok'\n\n\[email protected]('/hello')\ndef hello():\n myhost = os.uname()[1]\n body = 'V1 - Hello World! - %s' % myhost\n return body\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\[email protected]('/healthz')\ndef healthz():\n return 'ok'\n\n\[email protected]('/alive')\ndef alive():\n return 'ok'\n\n\[email protected]('/hello')\ndef hello():\n myhost = os.uname()[1]\n body = 'V1 - Hello World! - %s' % myhost\n return body\n\n\nif __name__ == '__main__':\n from waitress import serve\n serve(app, host='0.0.0.0', port=80)\n", "step-3": "<mask token>\napp = Flask(__name__)\n\n\[email protected]('/healthz')\ndef healthz():\n return 'ok'\n\n\[email protected]('/alive')\ndef alive():\n return 'ok'\n\n\[email protected]('/hello')\ndef hello():\n myhost = os.uname()[1]\n body = 'V1 - Hello World! - %s' % myhost\n return body\n\n\nif __name__ == '__main__':\n from waitress import serve\n serve(app, host='0.0.0.0', port=80)\n", "step-4": "from flask import Flask\nimport os\napp = Flask(__name__)\n\n\[email protected]('/healthz')\ndef healthz():\n return 'ok'\n\n\[email protected]('/alive')\ndef alive():\n return 'ok'\n\n\[email protected]('/hello')\ndef hello():\n myhost = os.uname()[1]\n body = 'V1 - Hello World! - %s' % myhost\n return body\n\n\nif __name__ == '__main__':\n from waitress import serve\n serve(app, host='0.0.0.0', port=80)\n", "step-5": "from flask import Flask\nimport os\n\napp = Flask(__name__)\n\n\[email protected](\"/healthz\")\ndef healthz():\n return \"ok\"\n\n\[email protected](\"/alive\")\ndef alive():\n return \"ok\"\n\n\[email protected](\"/hello\")\n# def healthz(): # introduces application crash bug\ndef hello():\n myhost = os.uname()[1]\n body = (\"V1 - Hello World! - %s\" % myhost)\n # body = (\"V2 - Hello World! - %s\" % myhost)\n return body\n\n\nif __name__ == \"__main__\":\n from waitress import serve\n serve(app, host=\"0.0.0.0\", port=80)\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
# -*- coding:utf-8 -*- from spider.driver.spider.base.spider import * class LvmamaHotelSpider(Spider): def get_comment_info2(self,shop_data): params_list_comment1 = self.params_dict.get(ParamType.COMMENT_INFO_1) comment_len = shop_data.get(FieldName.SHOP_COMMENT_NUM) while(True): comments_list_len = self.until_presence_of_all_elements_located_by_css_selector( css_selector=params_list_comment1.list_css_selector) if comments_list_len < comment_len*0.7: self.driver.refresh() time.sleep(0.5) else: break self.ismore_by_scroll_page_judge_by_len(css_selector=params_list_comment1.list_css_selector,comment_len=comment_len) try: for each in self.until_presence_of_all_elements_located_by_css_selector( css_selector=params_list_comment1.list_css_selector+' > div.arrow'): self.until_click_by_vertical_scroll_page_down(click_ele=each) except Exception as e: self.error_log(e=e) #上面在下拉加载页面 external_key={ FieldName.SHOP_URL : shop_data.get(FieldName.SHOP_URL), FieldName.SHOP_ID : shop_data.get(FieldName.SHOP_ID), FieldName.SHOP_NAME : shop_data.get(FieldName.SHOP_NAME), } self.get_spider_data_list(params_list=params_list_comment1,is_save=True,external_key=external_key,target=self.comments) def get_comment_info(self): for shop_data in self.get_current_data_list_from_db(self.shops): url = shop_data.get(FieldName.COMMENT_URL) if url: self.run_new_tab_task(func=self.get_comment_info2,url=url,shop_data=shop_data) def get_shop_info(self): self.info_log(data='进入驴妈妈移动版主页...') self.driver.get('https://m.lvmama.com') time.sleep(1.5) self.until_click_by_css_selector(css_selector='#content > div.index-header > a.search.cmAddClick > p') time.sleep(1) self.until_send_text_by_css_selector(css_selector='#keyword',text=self.data_region) self.info_log(data='输入%s...'%self.data_region) self.until_send_enter_by_css_selector(css_selector='#keyword') self.info_log(data='搜索%s...'%self.data_region) time.sleep(1) self.until_click_by_css_selector(css_selector='#tab_hotel > a') self.info_log(data='点击%s...'%self.data_source) time.sleep(3) params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1) self.until_ismore_by_send_key_arrow_down_judge_by_len( list_css_selector=params_list_shop1.list_css_selector,ele_css_selector='#tab_hotel > a', min_frequency=100,max_frequency=500,timeout=1) self.info_log(data='shopinfo') params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1) # 获取爬虫数据列表的样式信息 shop_data_list = self.get_spider_data_list(params_list=params_list_shop1,end=18) params_shop2 = self.params_dict.get(ParamType.SHOP_INFO_2) shop_data_list = self.add_spider_data_to_data_list(data_list=shop_data_list, isnewtab=True, params=params_shop2, url_name=FieldName.SHOP_URL,pause_time=1) for shop_data in shop_data_list: key = { FieldName.SHOP_URL: shop_data.get(FieldName.SHOP_URL), FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID), FieldName.SHOP_NAME : shop_data.get(FieldName.SHOP_NAME), } self.save_data_to_db(target=self.shops,key=key,data=shop_data) def run_spider(self): self.get_shop_info() # self.get_comment_info()
normal
{ "blob_id": "931e73ffce6d24dbfb92501670245e20fc403a7a", "index": 7969, "step-1": "<mask token>\n\n\nclass LvmamaHotelSpider(Spider):\n\n def get_comment_info2(self, shop_data):\n params_list_comment1 = self.params_dict.get(ParamType.COMMENT_INFO_1)\n comment_len = shop_data.get(FieldName.SHOP_COMMENT_NUM)\n while True:\n comments_list_len = (self.\n until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector))\n if comments_list_len < comment_len * 0.7:\n self.driver.refresh()\n time.sleep(0.5)\n else:\n break\n self.ismore_by_scroll_page_judge_by_len(css_selector=\n params_list_comment1.list_css_selector, comment_len=comment_len)\n try:\n for each in self.until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector +\n ' > div.arrow'):\n self.until_click_by_vertical_scroll_page_down(click_ele=each)\n except Exception as e:\n self.error_log(e=e)\n external_key = {FieldName.SHOP_URL: shop_data.get(FieldName.\n SHOP_URL), FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME: shop_data.get(FieldName.SHOP_NAME)}\n self.get_spider_data_list(params_list=params_list_comment1, is_save\n =True, external_key=external_key, target=self.comments)\n <mask token>\n <mask token>\n\n def run_spider(self):\n self.get_shop_info()\n", "step-2": "<mask token>\n\n\nclass LvmamaHotelSpider(Spider):\n\n def get_comment_info2(self, shop_data):\n params_list_comment1 = self.params_dict.get(ParamType.COMMENT_INFO_1)\n comment_len = shop_data.get(FieldName.SHOP_COMMENT_NUM)\n while True:\n comments_list_len = (self.\n until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector))\n if comments_list_len < comment_len * 0.7:\n self.driver.refresh()\n time.sleep(0.5)\n else:\n break\n self.ismore_by_scroll_page_judge_by_len(css_selector=\n params_list_comment1.list_css_selector, comment_len=comment_len)\n try:\n for each in self.until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector +\n ' > div.arrow'):\n self.until_click_by_vertical_scroll_page_down(click_ele=each)\n except Exception as e:\n self.error_log(e=e)\n external_key = {FieldName.SHOP_URL: shop_data.get(FieldName.\n SHOP_URL), FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME: shop_data.get(FieldName.SHOP_NAME)}\n self.get_spider_data_list(params_list=params_list_comment1, is_save\n =True, external_key=external_key, target=self.comments)\n <mask token>\n\n def get_shop_info(self):\n self.info_log(data='进入驴妈妈移动版主页...')\n self.driver.get('https://m.lvmama.com')\n time.sleep(1.5)\n self.until_click_by_css_selector(css_selector=\n '#content > div.index-header > a.search.cmAddClick > p')\n time.sleep(1)\n self.until_send_text_by_css_selector(css_selector='#keyword', text=\n self.data_region)\n self.info_log(data='输入%s...' % self.data_region)\n self.until_send_enter_by_css_selector(css_selector='#keyword')\n self.info_log(data='搜索%s...' % self.data_region)\n time.sleep(1)\n self.until_click_by_css_selector(css_selector='#tab_hotel > a')\n self.info_log(data='点击%s...' % self.data_source)\n time.sleep(3)\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1)\n self.until_ismore_by_send_key_arrow_down_judge_by_len(list_css_selector\n =params_list_shop1.list_css_selector, ele_css_selector=\n '#tab_hotel > a', min_frequency=100, max_frequency=500, timeout=1)\n self.info_log(data='shopinfo')\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1)\n shop_data_list = self.get_spider_data_list(params_list=\n params_list_shop1, end=18)\n params_shop2 = self.params_dict.get(ParamType.SHOP_INFO_2)\n shop_data_list = self.add_spider_data_to_data_list(data_list=\n shop_data_list, isnewtab=True, params=params_shop2, url_name=\n FieldName.SHOP_URL, pause_time=1)\n for shop_data in shop_data_list:\n key = {FieldName.SHOP_URL: shop_data.get(FieldName.SHOP_URL),\n FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME: shop_data.get(FieldName.SHOP_NAME)}\n self.save_data_to_db(target=self.shops, key=key, data=shop_data)\n\n def run_spider(self):\n self.get_shop_info()\n", "step-3": "<mask token>\n\n\nclass LvmamaHotelSpider(Spider):\n\n def get_comment_info2(self, shop_data):\n params_list_comment1 = self.params_dict.get(ParamType.COMMENT_INFO_1)\n comment_len = shop_data.get(FieldName.SHOP_COMMENT_NUM)\n while True:\n comments_list_len = (self.\n until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector))\n if comments_list_len < comment_len * 0.7:\n self.driver.refresh()\n time.sleep(0.5)\n else:\n break\n self.ismore_by_scroll_page_judge_by_len(css_selector=\n params_list_comment1.list_css_selector, comment_len=comment_len)\n try:\n for each in self.until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector +\n ' > div.arrow'):\n self.until_click_by_vertical_scroll_page_down(click_ele=each)\n except Exception as e:\n self.error_log(e=e)\n external_key = {FieldName.SHOP_URL: shop_data.get(FieldName.\n SHOP_URL), FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME: shop_data.get(FieldName.SHOP_NAME)}\n self.get_spider_data_list(params_list=params_list_comment1, is_save\n =True, external_key=external_key, target=self.comments)\n\n def get_comment_info(self):\n for shop_data in self.get_current_data_list_from_db(self.shops):\n url = shop_data.get(FieldName.COMMENT_URL)\n if url:\n self.run_new_tab_task(func=self.get_comment_info2, url=url,\n shop_data=shop_data)\n\n def get_shop_info(self):\n self.info_log(data='进入驴妈妈移动版主页...')\n self.driver.get('https://m.lvmama.com')\n time.sleep(1.5)\n self.until_click_by_css_selector(css_selector=\n '#content > div.index-header > a.search.cmAddClick > p')\n time.sleep(1)\n self.until_send_text_by_css_selector(css_selector='#keyword', text=\n self.data_region)\n self.info_log(data='输入%s...' % self.data_region)\n self.until_send_enter_by_css_selector(css_selector='#keyword')\n self.info_log(data='搜索%s...' % self.data_region)\n time.sleep(1)\n self.until_click_by_css_selector(css_selector='#tab_hotel > a')\n self.info_log(data='点击%s...' % self.data_source)\n time.sleep(3)\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1)\n self.until_ismore_by_send_key_arrow_down_judge_by_len(list_css_selector\n =params_list_shop1.list_css_selector, ele_css_selector=\n '#tab_hotel > a', min_frequency=100, max_frequency=500, timeout=1)\n self.info_log(data='shopinfo')\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1)\n shop_data_list = self.get_spider_data_list(params_list=\n params_list_shop1, end=18)\n params_shop2 = self.params_dict.get(ParamType.SHOP_INFO_2)\n shop_data_list = self.add_spider_data_to_data_list(data_list=\n shop_data_list, isnewtab=True, params=params_shop2, url_name=\n FieldName.SHOP_URL, pause_time=1)\n for shop_data in shop_data_list:\n key = {FieldName.SHOP_URL: shop_data.get(FieldName.SHOP_URL),\n FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME: shop_data.get(FieldName.SHOP_NAME)}\n self.save_data_to_db(target=self.shops, key=key, data=shop_data)\n\n def run_spider(self):\n self.get_shop_info()\n", "step-4": "from spider.driver.spider.base.spider import *\n\n\nclass LvmamaHotelSpider(Spider):\n\n def get_comment_info2(self, shop_data):\n params_list_comment1 = self.params_dict.get(ParamType.COMMENT_INFO_1)\n comment_len = shop_data.get(FieldName.SHOP_COMMENT_NUM)\n while True:\n comments_list_len = (self.\n until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector))\n if comments_list_len < comment_len * 0.7:\n self.driver.refresh()\n time.sleep(0.5)\n else:\n break\n self.ismore_by_scroll_page_judge_by_len(css_selector=\n params_list_comment1.list_css_selector, comment_len=comment_len)\n try:\n for each in self.until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector +\n ' > div.arrow'):\n self.until_click_by_vertical_scroll_page_down(click_ele=each)\n except Exception as e:\n self.error_log(e=e)\n external_key = {FieldName.SHOP_URL: shop_data.get(FieldName.\n SHOP_URL), FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME: shop_data.get(FieldName.SHOP_NAME)}\n self.get_spider_data_list(params_list=params_list_comment1, is_save\n =True, external_key=external_key, target=self.comments)\n\n def get_comment_info(self):\n for shop_data in self.get_current_data_list_from_db(self.shops):\n url = shop_data.get(FieldName.COMMENT_URL)\n if url:\n self.run_new_tab_task(func=self.get_comment_info2, url=url,\n shop_data=shop_data)\n\n def get_shop_info(self):\n self.info_log(data='进入驴妈妈移动版主页...')\n self.driver.get('https://m.lvmama.com')\n time.sleep(1.5)\n self.until_click_by_css_selector(css_selector=\n '#content > div.index-header > a.search.cmAddClick > p')\n time.sleep(1)\n self.until_send_text_by_css_selector(css_selector='#keyword', text=\n self.data_region)\n self.info_log(data='输入%s...' % self.data_region)\n self.until_send_enter_by_css_selector(css_selector='#keyword')\n self.info_log(data='搜索%s...' % self.data_region)\n time.sleep(1)\n self.until_click_by_css_selector(css_selector='#tab_hotel > a')\n self.info_log(data='点击%s...' % self.data_source)\n time.sleep(3)\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1)\n self.until_ismore_by_send_key_arrow_down_judge_by_len(list_css_selector\n =params_list_shop1.list_css_selector, ele_css_selector=\n '#tab_hotel > a', min_frequency=100, max_frequency=500, timeout=1)\n self.info_log(data='shopinfo')\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1)\n shop_data_list = self.get_spider_data_list(params_list=\n params_list_shop1, end=18)\n params_shop2 = self.params_dict.get(ParamType.SHOP_INFO_2)\n shop_data_list = self.add_spider_data_to_data_list(data_list=\n shop_data_list, isnewtab=True, params=params_shop2, url_name=\n FieldName.SHOP_URL, pause_time=1)\n for shop_data in shop_data_list:\n key = {FieldName.SHOP_URL: shop_data.get(FieldName.SHOP_URL),\n FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME: shop_data.get(FieldName.SHOP_NAME)}\n self.save_data_to_db(target=self.shops, key=key, data=shop_data)\n\n def run_spider(self):\n self.get_shop_info()\n", "step-5": "# -*- coding:utf-8 -*-\nfrom spider.driver.spider.base.spider import *\n\nclass LvmamaHotelSpider(Spider):\n def get_comment_info2(self,shop_data):\n params_list_comment1 = self.params_dict.get(ParamType.COMMENT_INFO_1)\n comment_len = shop_data.get(FieldName.SHOP_COMMENT_NUM)\n while(True):\n comments_list_len = self.until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector)\n if comments_list_len < comment_len*0.7:\n self.driver.refresh()\n time.sleep(0.5)\n else:\n break\n self.ismore_by_scroll_page_judge_by_len(css_selector=params_list_comment1.list_css_selector,comment_len=comment_len)\n try:\n for each in self.until_presence_of_all_elements_located_by_css_selector(\n css_selector=params_list_comment1.list_css_selector+' > div.arrow'):\n self.until_click_by_vertical_scroll_page_down(click_ele=each)\n except Exception as e:\n self.error_log(e=e)\n #上面在下拉加载页面\n external_key={\n FieldName.SHOP_URL : shop_data.get(FieldName.SHOP_URL),\n FieldName.SHOP_ID : shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME : shop_data.get(FieldName.SHOP_NAME),\n }\n self.get_spider_data_list(params_list=params_list_comment1,is_save=True,external_key=external_key,target=self.comments)\n\n def get_comment_info(self):\n for shop_data in self.get_current_data_list_from_db(self.shops):\n url = shop_data.get(FieldName.COMMENT_URL)\n if url:\n self.run_new_tab_task(func=self.get_comment_info2,url=url,shop_data=shop_data)\n\n def get_shop_info(self):\n self.info_log(data='进入驴妈妈移动版主页...')\n self.driver.get('https://m.lvmama.com')\n time.sleep(1.5)\n self.until_click_by_css_selector(css_selector='#content > div.index-header > a.search.cmAddClick > p')\n time.sleep(1)\n self.until_send_text_by_css_selector(css_selector='#keyword',text=self.data_region)\n self.info_log(data='输入%s...'%self.data_region)\n self.until_send_enter_by_css_selector(css_selector='#keyword')\n self.info_log(data='搜索%s...'%self.data_region)\n time.sleep(1)\n self.until_click_by_css_selector(css_selector='#tab_hotel > a')\n self.info_log(data='点击%s...'%self.data_source)\n time.sleep(3)\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1)\n self.until_ismore_by_send_key_arrow_down_judge_by_len(\n list_css_selector=params_list_shop1.list_css_selector,ele_css_selector='#tab_hotel > a',\n min_frequency=100,max_frequency=500,timeout=1)\n\n self.info_log(data='shopinfo')\n params_list_shop1 = self.params_dict.get(ParamType.SHOP_INFO_1) # 获取爬虫数据列表的样式信息\n shop_data_list = self.get_spider_data_list(params_list=params_list_shop1,end=18)\n params_shop2 = self.params_dict.get(ParamType.SHOP_INFO_2)\n shop_data_list = self.add_spider_data_to_data_list(data_list=shop_data_list, isnewtab=True, params=params_shop2,\n url_name=FieldName.SHOP_URL,pause_time=1)\n for shop_data in shop_data_list:\n key = {\n FieldName.SHOP_URL: shop_data.get(FieldName.SHOP_URL),\n FieldName.SHOP_ID: shop_data.get(FieldName.SHOP_ID),\n FieldName.SHOP_NAME : shop_data.get(FieldName.SHOP_NAME),\n }\n self.save_data_to_db(target=self.shops,key=key,data=shop_data)\n\n def run_spider(self):\n self.get_shop_info()\n # self.get_comment_info()", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> class Event(object): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Event(object): <|reserved_special_token_0|> def to_dict(self): d = {} for item in self.__dict__: val = getattr(self, item) if val != None: d[item] = val return d <|reserved_special_token_1|> <|reserved_special_token_0|> class Event(object): def __init__(self): self.id = None self.raw = None self.create_dt = datetime.datetime.now() self.device_id = None self.collector_id = None self.device_hostname = None self.device_domain_name = None self.device_ip_address = None self.types = [] def to_dict(self): d = {} for item in self.__dict__: val = getattr(self, item) if val != None: d[item] = val return d <|reserved_special_token_1|> import datetime class Event(object): def __init__(self): self.id = None self.raw = None self.create_dt = datetime.datetime.now() self.device_id = None self.collector_id = None self.device_hostname = None self.device_domain_name = None self.device_ip_address = None self.types = [] def to_dict(self): d = {} for item in self.__dict__: val = getattr(self, item) if val != None: d[item] = val return d
flexible
{ "blob_id": "7554b00f8c4d40f1d3ee2341f118048ca7ad10ea", "index": 709, "step-1": "<mask token>\n\n\nclass Event(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Event(object):\n <mask token>\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n val = getattr(self, item)\n if val != None:\n d[item] = val\n return d\n", "step-3": "<mask token>\n\n\nclass Event(object):\n\n def __init__(self):\n self.id = None\n self.raw = None\n self.create_dt = datetime.datetime.now()\n self.device_id = None\n self.collector_id = None\n self.device_hostname = None\n self.device_domain_name = None\n self.device_ip_address = None\n self.types = []\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n val = getattr(self, item)\n if val != None:\n d[item] = val\n return d\n", "step-4": "import datetime\n\n\nclass Event(object):\n\n def __init__(self):\n self.id = None\n self.raw = None\n self.create_dt = datetime.datetime.now()\n self.device_id = None\n self.collector_id = None\n self.device_hostname = None\n self.device_domain_name = None\n self.device_ip_address = None\n self.types = []\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n val = getattr(self, item)\n if val != None:\n d[item] = val\n return d\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
from __future__ import print_function import os from twisted.internet.task import react from twisted.internet.defer import Deferred, inlineCallbacks from twisted.internet.protocol import Factory from twisted.internet.protocol import Protocol from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol from twisted.protocols.basic import LineReceiver import msgpack class ChatClient(Protocol): def __init__(self, done): self.done = done self.unpacker = msgpack.Unpacker() def connectionLost(self, reason): print(reason.getErrorMessage()) self.done.callback(reason) def sendMessage(self, nick, msg): print("sending", nick, msg) data = msgpack.packb([nick, msg]) self.transport.write(data) def dataReceived(self, data): # ditto to server: go over what about "burst" messages? # (and do "original" code here at first: msg = msgpack.unpack(data) self.unpacker.feed(data) for msg in self.unpacker: print("{}: {}".format(*msg)) class StdIOFactory(Factory): def __init__(self, nick, proto): self.nick = nick self.proto = proto def buildProtocol(self, addr): return StandardInput(self.nick, self.proto) from twisted.internet.stdio import StandardIO class StandardInput(LineReceiver, StandardIO): ''' Reads stdin and writes every line received as a message to the server. No fancy editing or anything, simple pipe. ''' delimiter = os.linesep def lineReceived(self, line): return self.protocol.sendMessage(self.nick, line) def __init__(self, nick, proto): self.nick = nick self.protocol = proto def connectionLost(self, reason): self.protocol.transport.loseConnection()
normal
{ "blob_id": "532bcf8ae0ee40dc3eb4bd7170acfcb5d21cc4b9", "index": 1984, "step-1": "<mask token>\n\n\nclass StdIOFactory(Factory):\n <mask token>\n <mask token>\n\n\n<mask token>\n\n\nclass StandardInput(LineReceiver, StandardIO):\n \"\"\"\n Reads stdin and writes every line received as a message to the\n server. No fancy editing or anything, simple pipe.\n \"\"\"\n delimiter = os.linesep\n\n def lineReceived(self, line):\n return self.protocol.sendMessage(self.nick, line)\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.protocol = proto\n\n def connectionLost(self, reason):\n self.protocol.transport.loseConnection()\n", "step-2": "<mask token>\n\n\nclass ChatClient(Protocol):\n\n def __init__(self, done):\n self.done = done\n self.unpacker = msgpack.Unpacker()\n\n def connectionLost(self, reason):\n print(reason.getErrorMessage())\n self.done.callback(reason)\n <mask token>\n <mask token>\n\n\nclass StdIOFactory(Factory):\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.proto = proto\n\n def buildProtocol(self, addr):\n return StandardInput(self.nick, self.proto)\n\n\n<mask token>\n\n\nclass StandardInput(LineReceiver, StandardIO):\n \"\"\"\n Reads stdin and writes every line received as a message to the\n server. No fancy editing or anything, simple pipe.\n \"\"\"\n delimiter = os.linesep\n\n def lineReceived(self, line):\n return self.protocol.sendMessage(self.nick, line)\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.protocol = proto\n\n def connectionLost(self, reason):\n self.protocol.transport.loseConnection()\n", "step-3": "<mask token>\n\n\nclass ChatClient(Protocol):\n\n def __init__(self, done):\n self.done = done\n self.unpacker = msgpack.Unpacker()\n\n def connectionLost(self, reason):\n print(reason.getErrorMessage())\n self.done.callback(reason)\n\n def sendMessage(self, nick, msg):\n print('sending', nick, msg)\n data = msgpack.packb([nick, msg])\n self.transport.write(data)\n <mask token>\n\n\nclass StdIOFactory(Factory):\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.proto = proto\n\n def buildProtocol(self, addr):\n return StandardInput(self.nick, self.proto)\n\n\n<mask token>\n\n\nclass StandardInput(LineReceiver, StandardIO):\n \"\"\"\n Reads stdin and writes every line received as a message to the\n server. No fancy editing or anything, simple pipe.\n \"\"\"\n delimiter = os.linesep\n\n def lineReceived(self, line):\n return self.protocol.sendMessage(self.nick, line)\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.protocol = proto\n\n def connectionLost(self, reason):\n self.protocol.transport.loseConnection()\n", "step-4": "<mask token>\n\n\nclass ChatClient(Protocol):\n\n def __init__(self, done):\n self.done = done\n self.unpacker = msgpack.Unpacker()\n\n def connectionLost(self, reason):\n print(reason.getErrorMessage())\n self.done.callback(reason)\n\n def sendMessage(self, nick, msg):\n print('sending', nick, msg)\n data = msgpack.packb([nick, msg])\n self.transport.write(data)\n\n def dataReceived(self, data):\n self.unpacker.feed(data)\n for msg in self.unpacker:\n print('{}: {}'.format(*msg))\n\n\nclass StdIOFactory(Factory):\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.proto = proto\n\n def buildProtocol(self, addr):\n return StandardInput(self.nick, self.proto)\n\n\n<mask token>\n\n\nclass StandardInput(LineReceiver, StandardIO):\n \"\"\"\n Reads stdin and writes every line received as a message to the\n server. No fancy editing or anything, simple pipe.\n \"\"\"\n delimiter = os.linesep\n\n def lineReceived(self, line):\n return self.protocol.sendMessage(self.nick, line)\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.protocol = proto\n\n def connectionLost(self, reason):\n self.protocol.transport.loseConnection()\n", "step-5": "from __future__ import print_function\nimport os\n\nfrom twisted.internet.task import react\nfrom twisted.internet.defer import Deferred, inlineCallbacks\n\nfrom twisted.internet.protocol import Factory\nfrom twisted.internet.protocol import Protocol\nfrom twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol\nfrom twisted.protocols.basic import LineReceiver\n\nimport msgpack\n\n\nclass ChatClient(Protocol):\n def __init__(self, done):\n self.done = done\n self.unpacker = msgpack.Unpacker()\n\n def connectionLost(self, reason):\n print(reason.getErrorMessage())\n self.done.callback(reason)\n\n def sendMessage(self, nick, msg):\n print(\"sending\", nick, msg)\n data = msgpack.packb([nick, msg])\n self.transport.write(data)\n\n def dataReceived(self, data):\n # ditto to server: go over what about \"burst\" messages?\n # (and do \"original\" code here at first: msg = msgpack.unpack(data)\n self.unpacker.feed(data)\n for msg in self.unpacker:\n print(\"{}: {}\".format(*msg))\n\n\nclass StdIOFactory(Factory):\n def __init__(self, nick, proto):\n self.nick = nick\n self.proto = proto\n\n def buildProtocol(self, addr):\n return StandardInput(self.nick, self.proto)\n\n\nfrom twisted.internet.stdio import StandardIO\nclass StandardInput(LineReceiver, StandardIO):\n '''\n Reads stdin and writes every line received as a message to the\n server. No fancy editing or anything, simple pipe.\n '''\n delimiter = os.linesep\n\n def lineReceived(self, line):\n return self.protocol.sendMessage(self.nick, line)\n\n def __init__(self, nick, proto):\n self.nick = nick\n self.protocol = proto\n\n def connectionLost(self, reason):\n self.protocol.transport.loseConnection()\n", "step-ids": [ 7, 12, 13, 14, 16 ] }
[ 7, 12, 13, 14, 16 ]
<|reserved_special_token_0|> def checkuser(username, password, cursor, user_db): cursor.execute('select * from %s WHERE username = %d AND password = %d' % (user_db, int(username), int(password))) return cursor.fetchall() def tcplink(sock, addr): conn = pymysql.connect() cursor = conn.cursor() while True: bytedata = sock.recv(1024) data = eval(bytedata.decode()) sleep(1) if data: if 'username' and 'password' and 'login_mode' in data.keys(): if checkuser(data['username'], data['password'], cursor= cursor, user_db=usermode[data[login_mode]]): sock.send(b'Login success') else: sock.send(b'Error') else: break sock.close() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def checkuser(username, password, cursor, user_db): cursor.execute('select * from %s WHERE username = %d AND password = %d' % (user_db, int(username), int(password))) return cursor.fetchall() def tcplink(sock, addr): conn = pymysql.connect() cursor = conn.cursor() while True: bytedata = sock.recv(1024) data = eval(bytedata.decode()) sleep(1) if data: if 'username' and 'password' and 'login_mode' in data.keys(): if checkuser(data['username'], data['password'], cursor= cursor, user_db=usermode[data[login_mode]]): sock.send(b'Login success') else: sock.send(b'Error') else: break sock.close() if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(address) s.listen(10) while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) <|reserved_special_token_1|> <|reserved_special_token_0|> address = '127.0.0.1', 20176 usermode = {(1): 'Wangcz_Students', (2): 'Wangcz_Teachers', (3): 'Wangcz_Admin' } def checkuser(username, password, cursor, user_db): cursor.execute('select * from %s WHERE username = %d AND password = %d' % (user_db, int(username), int(password))) return cursor.fetchall() def tcplink(sock, addr): conn = pymysql.connect() cursor = conn.cursor() while True: bytedata = sock.recv(1024) data = eval(bytedata.decode()) sleep(1) if data: if 'username' and 'password' and 'login_mode' in data.keys(): if checkuser(data['username'], data['password'], cursor= cursor, user_db=usermode[data[login_mode]]): sock.send(b'Login success') else: sock.send(b'Error') else: break sock.close() if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(address) s.listen(10) while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) <|reserved_special_token_1|> import pymysql import pymssql import socket import threading from time import sleep address = '127.0.0.1', 20176 usermode = {(1): 'Wangcz_Students', (2): 'Wangcz_Teachers', (3): 'Wangcz_Admin' } def checkuser(username, password, cursor, user_db): cursor.execute('select * from %s WHERE username = %d AND password = %d' % (user_db, int(username), int(password))) return cursor.fetchall() def tcplink(sock, addr): conn = pymysql.connect() cursor = conn.cursor() while True: bytedata = sock.recv(1024) data = eval(bytedata.decode()) sleep(1) if data: if 'username' and 'password' and 'login_mode' in data.keys(): if checkuser(data['username'], data['password'], cursor= cursor, user_db=usermode[data[login_mode]]): sock.send(b'Login success') else: sock.send(b'Error') else: break sock.close() if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(address) s.listen(10) while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) <|reserved_special_token_1|> import pymysql import pymssql import socket import threading from time import sleep address = ('127.0.0.1', 20176) usermode = {1: 'Wangcz_Students', 2: 'Wangcz_Teachers', 3: 'Wangcz_Admin' } def checkuser(username, password, cursor, user_db): cursor.execute('''select * from %s WHERE username = %d AND password = %d''' % (user_db, int(username), int(password))) return cursor.fetchall() def tcplink(sock, addr): conn = pymysql.connect() cursor = conn.cursor() while True: bytedata = sock.recv(1024) data = eval(bytedata.decode()) sleep(1) if data: if 'username' and 'password' and 'login_mode' in data.keys(): if checkuser(data['username'],data['password'],cursor=cursor, user_db=usermode[data[login_mode]]): sock.send(b'Login success')#登陆成功 else: sock.send(b'Error')#发送错误消息 else: break sock.close() if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(address) s.listen(10) while True: sock,addr = s.accept() t = threading.Thread(target=tcplink,args=(sock,addr))
flexible
{ "blob_id": "758e5b9a65132c4bdee4600e79c27f9c0f272312", "index": 8308, "step-1": "<mask token>\n\n\ndef checkuser(username, password, cursor, user_db):\n cursor.execute('select * from %s WHERE username = %d AND password = %d' %\n (user_db, int(username), int(password)))\n return cursor.fetchall()\n\n\ndef tcplink(sock, addr):\n conn = pymysql.connect()\n cursor = conn.cursor()\n while True:\n bytedata = sock.recv(1024)\n data = eval(bytedata.decode())\n sleep(1)\n if data:\n if 'username' and 'password' and 'login_mode' in data.keys():\n if checkuser(data['username'], data['password'], cursor=\n cursor, user_db=usermode[data[login_mode]]):\n sock.send(b'Login success')\n else:\n sock.send(b'Error')\n else:\n break\n sock.close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef checkuser(username, password, cursor, user_db):\n cursor.execute('select * from %s WHERE username = %d AND password = %d' %\n (user_db, int(username), int(password)))\n return cursor.fetchall()\n\n\ndef tcplink(sock, addr):\n conn = pymysql.connect()\n cursor = conn.cursor()\n while True:\n bytedata = sock.recv(1024)\n data = eval(bytedata.decode())\n sleep(1)\n if data:\n if 'username' and 'password' and 'login_mode' in data.keys():\n if checkuser(data['username'], data['password'], cursor=\n cursor, user_db=usermode[data[login_mode]]):\n sock.send(b'Login success')\n else:\n sock.send(b'Error')\n else:\n break\n sock.close()\n\n\nif __name__ == '__main__':\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(address)\n s.listen(10)\n while True:\n sock, addr = s.accept()\n t = threading.Thread(target=tcplink, args=(sock, addr))\n", "step-3": "<mask token>\naddress = '127.0.0.1', 20176\nusermode = {(1): 'Wangcz_Students', (2): 'Wangcz_Teachers', (3): 'Wangcz_Admin'\n }\n\n\ndef checkuser(username, password, cursor, user_db):\n cursor.execute('select * from %s WHERE username = %d AND password = %d' %\n (user_db, int(username), int(password)))\n return cursor.fetchall()\n\n\ndef tcplink(sock, addr):\n conn = pymysql.connect()\n cursor = conn.cursor()\n while True:\n bytedata = sock.recv(1024)\n data = eval(bytedata.decode())\n sleep(1)\n if data:\n if 'username' and 'password' and 'login_mode' in data.keys():\n if checkuser(data['username'], data['password'], cursor=\n cursor, user_db=usermode[data[login_mode]]):\n sock.send(b'Login success')\n else:\n sock.send(b'Error')\n else:\n break\n sock.close()\n\n\nif __name__ == '__main__':\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(address)\n s.listen(10)\n while True:\n sock, addr = s.accept()\n t = threading.Thread(target=tcplink, args=(sock, addr))\n", "step-4": "import pymysql\nimport pymssql\nimport socket\nimport threading\nfrom time import sleep\naddress = '127.0.0.1', 20176\nusermode = {(1): 'Wangcz_Students', (2): 'Wangcz_Teachers', (3): 'Wangcz_Admin'\n }\n\n\ndef checkuser(username, password, cursor, user_db):\n cursor.execute('select * from %s WHERE username = %d AND password = %d' %\n (user_db, int(username), int(password)))\n return cursor.fetchall()\n\n\ndef tcplink(sock, addr):\n conn = pymysql.connect()\n cursor = conn.cursor()\n while True:\n bytedata = sock.recv(1024)\n data = eval(bytedata.decode())\n sleep(1)\n if data:\n if 'username' and 'password' and 'login_mode' in data.keys():\n if checkuser(data['username'], data['password'], cursor=\n cursor, user_db=usermode[data[login_mode]]):\n sock.send(b'Login success')\n else:\n sock.send(b'Error')\n else:\n break\n sock.close()\n\n\nif __name__ == '__main__':\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(address)\n s.listen(10)\n while True:\n sock, addr = s.accept()\n t = threading.Thread(target=tcplink, args=(sock, addr))\n", "step-5": "import pymysql\nimport pymssql\nimport socket\nimport threading\nfrom time import sleep\n\naddress = ('127.0.0.1', 20176)\nusermode = {1: 'Wangcz_Students',\n 2: 'Wangcz_Teachers',\n 3: 'Wangcz_Admin'\n }\n\ndef checkuser(username, password, cursor, user_db):\n\n cursor.execute('''select * from %s WHERE username = %d AND password = %d''' % (user_db, int(username), int(password)))\n return cursor.fetchall()\n\n\ndef tcplink(sock, addr):\n conn = pymysql.connect()\n cursor = conn.cursor()\n while True:\n bytedata = sock.recv(1024)\n data = eval(bytedata.decode())\n sleep(1)\n if data:\n if 'username' and 'password' and 'login_mode' in data.keys():\n if checkuser(data['username'],data['password'],cursor=cursor, user_db=usermode[data[login_mode]]):\n sock.send(b'Login success')#登陆成功\n else:\n sock.send(b'Error')#发送错误消息\n else:\n break\n\n sock.close()\n\nif __name__ == '__main__':\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(address)\n s.listen(10)\n while True:\n sock,addr = s.accept()\n t = threading.Thread(target=tcplink,args=(sock,addr))", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
import requests import re from bs4 import BeautifulSoup r = requests.get("https://terraria.fandom.com/wiki/Banners_(enemy)") soup = BeautifulSoup(r.text, 'html.parser') list_of_banners = soup.find_all('span', {'id': re.compile(r'_Banner')}) x_count = 1 y_count = 1 for banner_span in list_of_banners: print(f"{banner_span['id']}, {x_count}, {y_count}") x_count += 1 if x_count == 51: x_count = 1 y_count += 1 print("\n\n-----------------")
normal
{ "blob_id": "e60d57e8884cba8ce50a571e3bd0affcd4dcaf68", "index": 4056, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print('\\n\\n-----------------')\n", "step-3": "<mask token>\nr = requests.get('https://terraria.fandom.com/wiki/Banners_(enemy)')\nsoup = BeautifulSoup(r.text, 'html.parser')\nlist_of_banners = soup.find_all('span', {'id': re.compile('_Banner')})\nx_count = 1\ny_count = 1\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print('\\n\\n-----------------')\n", "step-4": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nr = requests.get('https://terraria.fandom.com/wiki/Banners_(enemy)')\nsoup = BeautifulSoup(r.text, 'html.parser')\nlist_of_banners = soup.find_all('span', {'id': re.compile('_Banner')})\nx_count = 1\ny_count = 1\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print('\\n\\n-----------------')\n", "step-5": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nr = requests.get(\"https://terraria.fandom.com/wiki/Banners_(enemy)\")\nsoup = BeautifulSoup(r.text, 'html.parser')\nlist_of_banners = soup.find_all('span', {'id': re.compile(r'_Banner')})\nx_count = 1\ny_count = 1\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print(\"\\n\\n-----------------\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
def guguPrint(n): print('*' * 30) for i in range(1, 10): print('{} X {} = {}'.format(n, i, n * i)) if __name__ =="__main__": print('Main으로 실행되었음')
normal
{ "blob_id": "aa2e24d80789f2a6ebd63ec42a17499f1e79ca49", "index": 5237, "step-1": "<mask token>\n", "step-2": "def guguPrint(n):\n print('*' * 30)\n for i in range(1, 10):\n print('{} X {} = {}'.format(n, i, n * i))\n\n\n<mask token>\n", "step-3": "def guguPrint(n):\n print('*' * 30)\n for i in range(1, 10):\n print('{} X {} = {}'.format(n, i, n * i))\n\n\nif __name__ == '__main__':\n print('Main으로 실행되었음')\n", "step-4": "def guguPrint(n):\n print('*' * 30)\n for i in range(1, 10):\n print('{} X {} = {}'.format(n, i, n * i))\n \nif __name__ ==\"__main__\":\n print('Main으로 실행되었음')", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class Sender: def __init__(self, reverseMap, info): self.reverseMap = reverseMap self.info = info def sendMessage(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': self. info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get ('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(message.toUsername) worker = SenderWorker(addr, msg) worker.start() <|reserved_special_token_0|> def sendMessageGroup(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': message. groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': True, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() <|reserved_special_token_0|> def sendGroupAcknowledgeRequest(self, request): body = b'' header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() <|reserved_special_token_0|> def sendGroupBroadcast(self): data = self.info body = json.dumps(data).encode('utf-8') header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': True, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() class SenderWorker(threading.Thread): def __init__(self, addr, msg): threading.Thread.__init__(self) self.addr = addr self.packageHash = bytes.fromhex(format(random.getrandbits(256), 'x').zfill(64)) self.msg = self.packageHash + msg self.sock = None def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) start = time.time() logger.debug( f'On thread #{threading.get_ident()}, start connection attempt') while True: iStart = time.time() if type(self.msg) not in [str, bytearray, bytes]: print('Sender worker msg: ', self.msg) if type(self.addr) not in [str, bytearray, bytes]: print('SenderWorker addr: ', self.addr, 'type: ', type(self .addr)) self.addr = self.addr[0] self.sock.sendto(self.msg, (self.addr, 8421)) if time.time() - iStart > 0.3: break logger.debug(f'Send complete using {time.time() - start} seconds') self.sock.close() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Sender: def __init__(self, reverseMap, info): self.reverseMap = reverseMap self.info = info def sendMessage(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': self. info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get ('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(message.toUsername) worker = SenderWorker(addr, msg) worker.start() def sendMessageBroadcast(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': self. info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get ('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendMessageGroup(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': message. groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': True, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupJoinRequest(self, request): data = {'message': request.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': request.fromUsername, 'srcGroup': self. info['groupID'], 'desGroup': request.groupID, 'admin': self. info.get('isAdmin', ''), 'member': self.info.get('isMember', '' ), 'broadcast': True, 'groupBroadcast': False, 'memberRq': True, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupAcknowledgeRequest(self, request): body = b'' header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupDenyRequest(self, request): body = b'' header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': True, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupBroadcast(self): data = self.info body = json.dumps(data).encode('utf-8') header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': True, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() class SenderWorker(threading.Thread): def __init__(self, addr, msg): threading.Thread.__init__(self) self.addr = addr self.packageHash = bytes.fromhex(format(random.getrandbits(256), 'x').zfill(64)) self.msg = self.packageHash + msg self.sock = None def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) start = time.time() logger.debug( f'On thread #{threading.get_ident()}, start connection attempt') while True: iStart = time.time() if type(self.msg) not in [str, bytearray, bytes]: print('Sender worker msg: ', self.msg) if type(self.addr) not in [str, bytearray, bytes]: print('SenderWorker addr: ', self.addr, 'type: ', type(self .addr)) self.addr = self.addr[0] self.sock.sendto(self.msg, (self.addr, 8421)) if time.time() - iStart > 0.3: break logger.debug(f'Send complete using {time.time() - start} seconds') self.sock.close() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Sender: def __init__(self, reverseMap, info): self.reverseMap = reverseMap self.info = info def sendMessage(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': self. info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get ('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(message.toUsername) worker = SenderWorker(addr, msg) worker.start() def sendMessageBroadcast(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': self. info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get ('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendMessageGroup(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': message. groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': True, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupJoinRequest(self, request): data = {'message': request.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': request.fromUsername, 'srcGroup': self. info['groupID'], 'desGroup': request.groupID, 'admin': self. info.get('isAdmin', ''), 'member': self.info.get('isMember', '' ), 'broadcast': True, 'groupBroadcast': False, 'memberRq': True, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupAcknowledgeRequest(self, request): body = b'' header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupDenyRequest(self, request): body = b'' header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': True, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupBroadcast(self): data = self.info body = json.dumps(data).encode('utf-8') header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': True, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() class SenderWorker(threading.Thread): def __init__(self, addr, msg): threading.Thread.__init__(self) self.addr = addr self.packageHash = bytes.fromhex(format(random.getrandbits(256), 'x').zfill(64)) self.msg = self.packageHash + msg self.sock = None def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) start = time.time() logger.debug( f'On thread #{threading.get_ident()}, start connection attempt') while True: iStart = time.time() if type(self.msg) not in [str, bytearray, bytes]: print('Sender worker msg: ', self.msg) if type(self.addr) not in [str, bytearray, bytes]: print('SenderWorker addr: ', self.addr, 'type: ', type(self .addr)) self.addr = self.addr[0] self.sock.sendto(self.msg, (self.addr, 8421)) if time.time() - iStart > 0.3: break logger.debug(f'Send complete using {time.time() - start} seconds') self.sock.close() <|reserved_special_token_0|> logger.setLevel(logging.DEBUG) <|reserved_special_token_0|> ch.setFormatter(formatter) <|reserved_special_token_0|> fh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) <|reserved_special_token_1|> from network.utility import * from entities.message import Message, BroadcastMessage, GroupMessage from entities.node import Node from entities.group import GroupBroadcast from entities.request import Request import threading import time import logging import random import json import socket from services.user import UserService class Sender: def __init__(self, reverseMap, info): self.reverseMap = reverseMap self.info = info def sendMessage(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': self. info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get ('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(message.toUsername) worker = SenderWorker(addr, msg) worker.start() def sendMessageBroadcast(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': self. info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get ('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendMessageGroup(self, message): data = {'timestamp': message.timestamp, 'message': message.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': message.fromUsername, 'srcGroup': message. groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': True, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupJoinRequest(self, request): data = {'message': request.message} body = json.dumps(data).encode('utf-8') header = {'srcUsername': request.fromUsername, 'srcGroup': self. info['groupID'], 'desGroup': request.groupID, 'admin': self. info.get('isAdmin', ''), 'member': self.info.get('isMember', '' ), 'broadcast': True, 'groupBroadcast': False, 'memberRq': True, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupAcknowledgeRequest(self, request): body = b'' header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupDenyRequest(self, request): body = b'' header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': False, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': True, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': False, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupBroadcast(self): data = self.info body = json.dumps(data).encode('utf-8') header = {'srcUsername': self.info['username'], 'srcGroup': self. info['groupID'], 'desGroup': '', 'admin': self.info.get( 'isAdmin', ''), 'member': self.info.get('isMember', ''), 'broadcast': True, 'groupBroadcast': False, 'memberRq': False, 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': False, 'nodeRep': True, 'contentLength': len(body)} packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() class SenderWorker(threading.Thread): def __init__(self, addr, msg): threading.Thread.__init__(self) self.addr = addr self.packageHash = bytes.fromhex(format(random.getrandbits(256), 'x').zfill(64)) self.msg = self.packageHash + msg self.sock = None def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) start = time.time() logger.debug( f'On thread #{threading.get_ident()}, start connection attempt') while True: iStart = time.time() if type(self.msg) not in [str, bytearray, bytes]: print('Sender worker msg: ', self.msg) if type(self.addr) not in [str, bytearray, bytes]: print('SenderWorker addr: ', self.addr, 'type: ', type(self .addr)) self.addr = self.addr[0] self.sock.sendto(self.msg, (self.addr, 8421)) if time.time() - iStart > 0.3: break logger.debug(f'Send complete using {time.time() - start} seconds') self.sock.close() logger = logging.getLogger('Sender') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh = logging.FileHandler('applog.log') fh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) <|reserved_special_token_1|> from network.utility import * from entities.message import Message, BroadcastMessage, GroupMessage from entities.node import Node from entities.group import GroupBroadcast from entities.request import Request import threading import time import logging import random import json import socket from services.user import UserService class Sender: def __init__(self, reverseMap, info): self.reverseMap = reverseMap self.info = info def sendMessage(self, message): data = {"timestamp": message.timestamp, "message": message.message} body = json.dumps(data).encode('utf-8') header = { "srcUsername": message.fromUsername, "srcGroup": self.info.get("groupID", ""), "desGroup": "", "admin": self.info.get("isAdmin", ""), "member": self.info.get("isMember", ""), "broadcast": False, "groupBroadcast": False, "memberRq": False, "ackRq": False, "denyRq": False, "leaveRq": False, "nodeRq": False, "big": False, "nodeRep": False, "contentLength": len(body), } packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(message.toUsername) worker = SenderWorker(addr, msg) worker.start() def sendMessageBroadcast(self, message): data = {"timestamp": message.timestamp, "message": message.message} body = json.dumps(data).encode('utf-8') header = { "srcUsername": message.fromUsername, "srcGroup": self.info.get("groupID", ""), "desGroup": "", "admin": self.info.get("isAdmin", ""), "member": self.info.get("isMember", ""), "broadcast": True, "groupBroadcast": False, "memberRq": False, "ackRq": False, "denyRq": False, "leaveRq": False, "nodeRq": False, "big": False, "nodeRep": False, "contentLength": len(body), } packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendMessageGroup(self, message): data = {"timestamp": message.timestamp, "message": message.message} body = json.dumps(data).encode('utf-8') header = { "srcUsername": message.fromUsername, "srcGroup": message.groupID, "desGroup": "", "admin": self.info.get("isAdmin", ""), "member": self.info.get("isMember", ""), "broadcast": True, "groupBroadcast": True, "memberRq": False, "ackRq": False, "denyRq": False, "leaveRq": False, "nodeRq": False, "big": False, "nodeRep": False, "contentLength": len(body), } packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupJoinRequest(self, request): data = {"message": request.message} body = json.dumps(data).encode('utf-8') header = { "srcUsername": request.fromUsername, "srcGroup": self.info["groupID"], "desGroup": request.groupID, "admin": self.info.get("isAdmin", ""), "member": self.info.get("isMember", ""), "broadcast": True, "groupBroadcast": False, "memberRq": True, "ackRq": False, "denyRq": False, "leaveRq": False, "nodeRq": False, "big": False, "nodeRep": False, "contentLength": len(body), } packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() def sendGroupAcknowledgeRequest(self, request): body = b"" header = { "srcUsername": self.info["username"], "srcGroup": self.info["groupID"], "desGroup": "", "admin": self.info.get("isAdmin", ""), "member": self.info.get("isMember", ""), "broadcast": False, "groupBroadcast": False, "memberRq": False, "ackRq": True, "denyRq": False, "leaveRq": False, "nodeRq": False, "big": False, "nodeRep": False, "contentLength": len(body), } packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupDenyRequest(self, request): body = b"" header = { "srcUsername": self.info["username"], "srcGroup": self.info["groupID"], "desGroup": "", "admin": self.info.get("isAdmin", ""), "member": self.info.get("isMember", ""), "broadcast": False, "groupBroadcast": False, "memberRq": False, "ackRq": False, "denyRq": True, "leaveRq": False, "nodeRq": False, "big": False, "nodeRep": False, "contentLength": len(body), } packedHeader = packHeader(header) msg = packedHeader + body addr = self.reverseMap.get(request.fromUsername) worker = SenderWorker(addr, msg) worker.start() def sendGroupBroadcast(self): data = self.info body = json.dumps(data).encode('utf-8') header = { "srcUsername": self.info["username"], "srcGroup": self.info["groupID"], "desGroup": "", "admin": self.info.get("isAdmin", ""), "member": self.info.get("isMember", ""), "broadcast": True, "groupBroadcast": False, "memberRq": False, "ackRq": False, "denyRq": False, "leaveRq": False, "nodeRq": False, "big": False, "nodeRep": True, "contentLength": len(body), } packedHeader = packHeader(header) msg = packedHeader + body for addr in self.reverseMap.values(): worker = SenderWorker(addr, msg) worker.start() class SenderWorker(threading.Thread): def __init__(self, addr, msg): threading.Thread.__init__(self) self.addr = addr self.packageHash = bytes.fromhex( format(random.getrandbits(256), "x").zfill(64)) self.msg = self.packageHash+msg self.sock = None def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) start = time.time() logger.debug( f"On thread #{threading.get_ident()}, start connection attempt") while True: iStart = time.time() if type(self.msg) not in [str, bytearray, bytes]: print('Sender worker msg: ', self.msg) if type(self.addr) not in [str, bytearray, bytes]: print('SenderWorker addr: ', self.addr, 'type: ', type(self.addr)) self.addr = self.addr[0] self.sock.sendto(self.msg, (self.addr, 8421,)) if time.time() - iStart > 0.3: break logger.debug(f"Send complete using {time.time()-start} seconds") self.sock.close() logger = logging.getLogger('Sender') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh = logging.FileHandler("applog.log") fh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch)
flexible
{ "blob_id": "67446f50d1c062eddcad282d3bf508967c5192fc", "index": 4905, "step-1": "<mask token>\n\n\nclass Sender:\n\n def __init__(self, reverseMap, info):\n self.reverseMap = reverseMap\n self.info = info\n\n def sendMessage(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': self.\n info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get\n ('isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(message.toUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n <mask token>\n\n def sendMessageGroup(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': message.\n groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''),\n 'member': self.info.get('isMember', ''), 'broadcast': True,\n 'groupBroadcast': True, 'memberRq': False, 'ackRq': False,\n 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': \n False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n <mask token>\n\n def sendGroupAcknowledgeRequest(self, request):\n body = b''\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n <mask token>\n\n def sendGroupBroadcast(self):\n data = self.info\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': True, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': True, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n\nclass SenderWorker(threading.Thread):\n\n def __init__(self, addr, msg):\n threading.Thread.__init__(self)\n self.addr = addr\n self.packageHash = bytes.fromhex(format(random.getrandbits(256),\n 'x').zfill(64))\n self.msg = self.packageHash + msg\n self.sock = None\n\n def run(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n start = time.time()\n logger.debug(\n f'On thread #{threading.get_ident()}, start connection attempt')\n while True:\n iStart = time.time()\n if type(self.msg) not in [str, bytearray, bytes]:\n print('Sender worker msg: ', self.msg)\n if type(self.addr) not in [str, bytearray, bytes]:\n print('SenderWorker addr: ', self.addr, 'type: ', type(self\n .addr))\n self.addr = self.addr[0]\n self.sock.sendto(self.msg, (self.addr, 8421))\n if time.time() - iStart > 0.3:\n break\n logger.debug(f'Send complete using {time.time() - start} seconds')\n self.sock.close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Sender:\n\n def __init__(self, reverseMap, info):\n self.reverseMap = reverseMap\n self.info = info\n\n def sendMessage(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': self.\n info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get\n ('isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(message.toUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageBroadcast(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': self.\n info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get\n ('isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': True, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageGroup(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': message.\n groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''),\n 'member': self.info.get('isMember', ''), 'broadcast': True,\n 'groupBroadcast': True, 'memberRq': False, 'ackRq': False,\n 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': \n False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupJoinRequest(self, request):\n data = {'message': request.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': request.fromUsername, 'srcGroup': self.\n info['groupID'], 'desGroup': request.groupID, 'admin': self.\n info.get('isAdmin', ''), 'member': self.info.get('isMember', ''\n ), 'broadcast': True, 'groupBroadcast': False, 'memberRq': True,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupAcknowledgeRequest(self, request):\n body = b''\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupDenyRequest(self, request):\n body = b''\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': True, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupBroadcast(self):\n data = self.info\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': True, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': True, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n\nclass SenderWorker(threading.Thread):\n\n def __init__(self, addr, msg):\n threading.Thread.__init__(self)\n self.addr = addr\n self.packageHash = bytes.fromhex(format(random.getrandbits(256),\n 'x').zfill(64))\n self.msg = self.packageHash + msg\n self.sock = None\n\n def run(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n start = time.time()\n logger.debug(\n f'On thread #{threading.get_ident()}, start connection attempt')\n while True:\n iStart = time.time()\n if type(self.msg) not in [str, bytearray, bytes]:\n print('Sender worker msg: ', self.msg)\n if type(self.addr) not in [str, bytearray, bytes]:\n print('SenderWorker addr: ', self.addr, 'type: ', type(self\n .addr))\n self.addr = self.addr[0]\n self.sock.sendto(self.msg, (self.addr, 8421))\n if time.time() - iStart > 0.3:\n break\n logger.debug(f'Send complete using {time.time() - start} seconds')\n self.sock.close()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Sender:\n\n def __init__(self, reverseMap, info):\n self.reverseMap = reverseMap\n self.info = info\n\n def sendMessage(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': self.\n info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get\n ('isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(message.toUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageBroadcast(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': self.\n info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get\n ('isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': True, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageGroup(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': message.\n groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''),\n 'member': self.info.get('isMember', ''), 'broadcast': True,\n 'groupBroadcast': True, 'memberRq': False, 'ackRq': False,\n 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': \n False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupJoinRequest(self, request):\n data = {'message': request.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': request.fromUsername, 'srcGroup': self.\n info['groupID'], 'desGroup': request.groupID, 'admin': self.\n info.get('isAdmin', ''), 'member': self.info.get('isMember', ''\n ), 'broadcast': True, 'groupBroadcast': False, 'memberRq': True,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupAcknowledgeRequest(self, request):\n body = b''\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupDenyRequest(self, request):\n body = b''\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': True, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupBroadcast(self):\n data = self.info\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': True, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': True, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n\nclass SenderWorker(threading.Thread):\n\n def __init__(self, addr, msg):\n threading.Thread.__init__(self)\n self.addr = addr\n self.packageHash = bytes.fromhex(format(random.getrandbits(256),\n 'x').zfill(64))\n self.msg = self.packageHash + msg\n self.sock = None\n\n def run(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n start = time.time()\n logger.debug(\n f'On thread #{threading.get_ident()}, start connection attempt')\n while True:\n iStart = time.time()\n if type(self.msg) not in [str, bytearray, bytes]:\n print('Sender worker msg: ', self.msg)\n if type(self.addr) not in [str, bytearray, bytes]:\n print('SenderWorker addr: ', self.addr, 'type: ', type(self\n .addr))\n self.addr = self.addr[0]\n self.sock.sendto(self.msg, (self.addr, 8421))\n if time.time() - iStart > 0.3:\n break\n logger.debug(f'Send complete using {time.time() - start} seconds')\n self.sock.close()\n\n\n<mask token>\nlogger.setLevel(logging.DEBUG)\n<mask token>\nch.setFormatter(formatter)\n<mask token>\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n", "step-4": "from network.utility import *\nfrom entities.message import Message, BroadcastMessage, GroupMessage\nfrom entities.node import Node\nfrom entities.group import GroupBroadcast\nfrom entities.request import Request\nimport threading\nimport time\nimport logging\nimport random\nimport json\nimport socket\nfrom services.user import UserService\n\n\nclass Sender:\n\n def __init__(self, reverseMap, info):\n self.reverseMap = reverseMap\n self.info = info\n\n def sendMessage(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': self.\n info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get\n ('isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(message.toUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageBroadcast(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': self.\n info.get('groupID', ''), 'desGroup': '', 'admin': self.info.get\n ('isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': True, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageGroup(self, message):\n data = {'timestamp': message.timestamp, 'message': message.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': message.fromUsername, 'srcGroup': message.\n groupID, 'desGroup': '', 'admin': self.info.get('isAdmin', ''),\n 'member': self.info.get('isMember', ''), 'broadcast': True,\n 'groupBroadcast': True, 'memberRq': False, 'ackRq': False,\n 'denyRq': False, 'leaveRq': False, 'nodeRq': False, 'big': \n False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupJoinRequest(self, request):\n data = {'message': request.message}\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': request.fromUsername, 'srcGroup': self.\n info['groupID'], 'desGroup': request.groupID, 'admin': self.\n info.get('isAdmin', ''), 'member': self.info.get('isMember', ''\n ), 'broadcast': True, 'groupBroadcast': False, 'memberRq': True,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupAcknowledgeRequest(self, request):\n body = b''\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': True, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupDenyRequest(self, request):\n body = b''\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': False, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': True, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': False, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupBroadcast(self):\n data = self.info\n body = json.dumps(data).encode('utf-8')\n header = {'srcUsername': self.info['username'], 'srcGroup': self.\n info['groupID'], 'desGroup': '', 'admin': self.info.get(\n 'isAdmin', ''), 'member': self.info.get('isMember', ''),\n 'broadcast': True, 'groupBroadcast': False, 'memberRq': False,\n 'ackRq': False, 'denyRq': False, 'leaveRq': False, 'nodeRq': \n False, 'big': False, 'nodeRep': True, 'contentLength': len(body)}\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n\nclass SenderWorker(threading.Thread):\n\n def __init__(self, addr, msg):\n threading.Thread.__init__(self)\n self.addr = addr\n self.packageHash = bytes.fromhex(format(random.getrandbits(256),\n 'x').zfill(64))\n self.msg = self.packageHash + msg\n self.sock = None\n\n def run(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n start = time.time()\n logger.debug(\n f'On thread #{threading.get_ident()}, start connection attempt')\n while True:\n iStart = time.time()\n if type(self.msg) not in [str, bytearray, bytes]:\n print('Sender worker msg: ', self.msg)\n if type(self.addr) not in [str, bytearray, bytes]:\n print('SenderWorker addr: ', self.addr, 'type: ', type(self\n .addr))\n self.addr = self.addr[0]\n self.sock.sendto(self.msg, (self.addr, 8421))\n if time.time() - iStart > 0.3:\n break\n logger.debug(f'Send complete using {time.time() - start} seconds')\n self.sock.close()\n\n\nlogger = logging.getLogger('Sender')\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nformatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nfh = logging.FileHandler('applog.log')\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n", "step-5": "from network.utility import *\nfrom entities.message import Message, BroadcastMessage, GroupMessage\nfrom entities.node import Node\nfrom entities.group import GroupBroadcast\nfrom entities.request import Request\nimport threading\nimport time\nimport logging\nimport random\nimport json\nimport socket\nfrom services.user import UserService\n\n\nclass Sender:\n\n def __init__(self, reverseMap, info):\n self.reverseMap = reverseMap\n self.info = info\n\n def sendMessage(self, message):\n data = {\"timestamp\": message.timestamp, \"message\": message.message}\n body = json.dumps(data).encode('utf-8')\n header = {\n \"srcUsername\": message.fromUsername,\n \"srcGroup\": self.info.get(\"groupID\", \"\"),\n \"desGroup\": \"\",\n \"admin\": self.info.get(\"isAdmin\", \"\"),\n \"member\": self.info.get(\"isMember\", \"\"),\n \"broadcast\": False,\n \"groupBroadcast\": False,\n \"memberRq\": False,\n \"ackRq\": False,\n \"denyRq\": False,\n \"leaveRq\": False,\n \"nodeRq\": False,\n \"big\": False,\n \"nodeRep\": False,\n \"contentLength\": len(body),\n }\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(message.toUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageBroadcast(self, message):\n data = {\"timestamp\": message.timestamp, \"message\": message.message}\n body = json.dumps(data).encode('utf-8')\n header = {\n \"srcUsername\": message.fromUsername,\n \"srcGroup\": self.info.get(\"groupID\", \"\"),\n \"desGroup\": \"\",\n \"admin\": self.info.get(\"isAdmin\", \"\"),\n \"member\": self.info.get(\"isMember\", \"\"),\n \"broadcast\": True,\n \"groupBroadcast\": False,\n \"memberRq\": False,\n \"ackRq\": False,\n \"denyRq\": False,\n \"leaveRq\": False,\n \"nodeRq\": False,\n \"big\": False,\n \"nodeRep\": False,\n \"contentLength\": len(body),\n }\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendMessageGroup(self, message):\n data = {\"timestamp\": message.timestamp, \"message\": message.message}\n body = json.dumps(data).encode('utf-8')\n header = {\n \"srcUsername\": message.fromUsername,\n \"srcGroup\": message.groupID,\n \"desGroup\": \"\",\n \"admin\": self.info.get(\"isAdmin\", \"\"),\n \"member\": self.info.get(\"isMember\", \"\"),\n \"broadcast\": True,\n \"groupBroadcast\": True,\n \"memberRq\": False,\n \"ackRq\": False,\n \"denyRq\": False,\n \"leaveRq\": False,\n \"nodeRq\": False,\n \"big\": False,\n \"nodeRep\": False,\n \"contentLength\": len(body),\n }\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupJoinRequest(self, request):\n data = {\"message\": request.message}\n body = json.dumps(data).encode('utf-8')\n header = {\n \"srcUsername\": request.fromUsername,\n \"srcGroup\": self.info[\"groupID\"],\n \"desGroup\": request.groupID,\n \"admin\": self.info.get(\"isAdmin\", \"\"),\n \"member\": self.info.get(\"isMember\", \"\"),\n \"broadcast\": True,\n \"groupBroadcast\": False,\n \"memberRq\": True,\n \"ackRq\": False,\n \"denyRq\": False,\n \"leaveRq\": False,\n \"nodeRq\": False,\n \"big\": False,\n \"nodeRep\": False,\n \"contentLength\": len(body),\n }\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupAcknowledgeRequest(self, request):\n body = b\"\"\n header = {\n \"srcUsername\": self.info[\"username\"],\n \"srcGroup\": self.info[\"groupID\"],\n \"desGroup\": \"\",\n \"admin\": self.info.get(\"isAdmin\", \"\"),\n \"member\": self.info.get(\"isMember\", \"\"),\n \"broadcast\": False,\n \"groupBroadcast\": False,\n \"memberRq\": False,\n \"ackRq\": True,\n \"denyRq\": False,\n \"leaveRq\": False,\n \"nodeRq\": False,\n \"big\": False,\n \"nodeRep\": False,\n \"contentLength\": len(body),\n }\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupDenyRequest(self, request):\n body = b\"\"\n header = {\n \"srcUsername\": self.info[\"username\"],\n \"srcGroup\": self.info[\"groupID\"],\n \"desGroup\": \"\",\n \"admin\": self.info.get(\"isAdmin\", \"\"),\n \"member\": self.info.get(\"isMember\", \"\"),\n \"broadcast\": False,\n \"groupBroadcast\": False,\n \"memberRq\": False,\n \"ackRq\": False,\n \"denyRq\": True,\n \"leaveRq\": False,\n \"nodeRq\": False,\n \"big\": False,\n \"nodeRep\": False,\n \"contentLength\": len(body),\n }\n packedHeader = packHeader(header)\n msg = packedHeader + body\n addr = self.reverseMap.get(request.fromUsername)\n worker = SenderWorker(addr, msg)\n worker.start()\n\n def sendGroupBroadcast(self):\n data = self.info\n body = json.dumps(data).encode('utf-8')\n header = {\n \"srcUsername\": self.info[\"username\"],\n \"srcGroup\": self.info[\"groupID\"],\n \"desGroup\": \"\",\n \"admin\": self.info.get(\"isAdmin\", \"\"),\n \"member\": self.info.get(\"isMember\", \"\"),\n \"broadcast\": True,\n \"groupBroadcast\": False,\n \"memberRq\": False,\n \"ackRq\": False,\n \"denyRq\": False,\n \"leaveRq\": False,\n \"nodeRq\": False,\n \"big\": False,\n \"nodeRep\": True,\n \"contentLength\": len(body),\n }\n packedHeader = packHeader(header)\n msg = packedHeader + body\n for addr in self.reverseMap.values():\n worker = SenderWorker(addr, msg)\n worker.start()\n\n\nclass SenderWorker(threading.Thread):\n\n def __init__(self, addr, msg):\n threading.Thread.__init__(self)\n self.addr = addr\n self.packageHash = bytes.fromhex(\n format(random.getrandbits(256), \"x\").zfill(64))\n self.msg = self.packageHash+msg\n self.sock = None\n\n def run(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n start = time.time()\n logger.debug(\n f\"On thread #{threading.get_ident()}, start connection attempt\")\n while True:\n iStart = time.time()\n if type(self.msg) not in [str, bytearray, bytes]:\n print('Sender worker msg: ', self.msg)\n if type(self.addr) not in [str, bytearray, bytes]:\n print('SenderWorker addr: ', self.addr,\n 'type: ', type(self.addr))\n self.addr = self.addr[0]\n self.sock.sendto(self.msg, (self.addr, 8421,))\n if time.time() - iStart > 0.3:\n break\n logger.debug(f\"Send complete using {time.time()-start} seconds\")\n self.sock.close()\n\n\nlogger = logging.getLogger('Sender')\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nfh = logging.FileHandler(\"applog.log\")\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n", "step-ids": [ 9, 12, 13, 15, 16 ] }
[ 9, 12, 13, 15, 16 ]
class Solution: def minRemoveToMakeValid(self, s: str) -> str: bracketsToRemove = set() stack = [] for i, c in enumerate(s): if c not in '()': continue if c == '(': stack.append(i) elif not stack: bracketsToRemove.add(i) else: stack.pop() bracketsToRemove = bracketsToRemove.union(set(stack)) stringBuilder = [] for i,c in enumerate(s): if i not in bracketsToRemove: stringBuilder.append(c) return "".join(stringBuilder) Solution().minRemoveToMakeValid('L(ee)(t(()coe')
normal
{ "blob_id": "1bab6b039462bb5762aa588d5ba7c3e74362d0a7", "index": 823, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n\n\n<mask token>\n", "step-3": "class Solution:\n\n def minRemoveToMakeValid(self, s: str) ->str:\n bracketsToRemove = set()\n stack = []\n for i, c in enumerate(s):\n if c not in '()':\n continue\n if c == '(':\n stack.append(i)\n elif not stack:\n bracketsToRemove.add(i)\n else:\n stack.pop()\n bracketsToRemove = bracketsToRemove.union(set(stack))\n stringBuilder = []\n for i, c in enumerate(s):\n if i not in bracketsToRemove:\n stringBuilder.append(c)\n return ''.join(stringBuilder)\n\n\n<mask token>\n", "step-4": "class Solution:\n\n def minRemoveToMakeValid(self, s: str) ->str:\n bracketsToRemove = set()\n stack = []\n for i, c in enumerate(s):\n if c not in '()':\n continue\n if c == '(':\n stack.append(i)\n elif not stack:\n bracketsToRemove.add(i)\n else:\n stack.pop()\n bracketsToRemove = bracketsToRemove.union(set(stack))\n stringBuilder = []\n for i, c in enumerate(s):\n if i not in bracketsToRemove:\n stringBuilder.append(c)\n return ''.join(stringBuilder)\n\n\nSolution().minRemoveToMakeValid('L(ee)(t(()coe')\n", "step-5": "class Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n bracketsToRemove = set()\n stack = []\n \n for i, c in enumerate(s):\n \n if c not in '()':\n continue\n if c == '(':\n stack.append(i)\n elif not stack:\n bracketsToRemove.add(i)\n else:\n stack.pop()\n \n bracketsToRemove = bracketsToRemove.union(set(stack))\n stringBuilder = []\n for i,c in enumerate(s):\n if i not in bracketsToRemove:\n stringBuilder.append(c)\n \n return \"\".join(stringBuilder)\n\n\nSolution().minRemoveToMakeValid('L(ee)(t(()coe')\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import inspect import json import socket import sys import execnet import logging from remoto.process import check class BaseConnection(object): """ Base class for Connection objects. Provides a generic interface to execnet for setting up the connection """ executable = '' remote_import_system = 'legacy' def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=True, detect_sudo=False, use_ssh=False, interpreter=None, ssh_options=None): self.sudo = sudo self.hostname = hostname self.ssh_options = ssh_options self.logger = logger or basic_remote_logger() self.remote_module = None self.channel = None self.use_ssh = use_ssh self.global_timeout = None # wait for ever self.interpreter = interpreter or 'python%s' % sys.version_info[0] if eager: try: if detect_sudo: self.sudo = self._detect_sudo() self.gateway = self._make_gateway(hostname) except OSError: self.logger.error( "Can't communicate with remote host, possibly because " "%s is not installed there" % self.interpreter ) raise def _make_gateway(self, hostname): self.group = execnet.Group() gateway = self.group.makegateway( self._make_connection_string(hostname) ) gateway.reconfigure(py2str_as_py3str=False, py3str_as_py2str=False) return gateway def _detect_sudo(self, _execnet=None): """ ``sudo`` detection has to create a different connection to the remote host so that we can reliably ensure that ``getuser()`` will return the right information. After getting the user info it closes the connection and returns a boolean """ exc = _execnet or execnet gw = exc.makegateway( self._make_connection_string(self.hostname, use_sudo=False) ) channel = gw.remote_exec( 'import getpass; channel.send(getpass.getuser())' ) result = channel.receive() gw.exit() if result == 'root': return False self.logger.debug('connection detected need for sudo') return True def _make_connection_string(self, hostname, _needs_ssh=None, use_sudo=None): _needs_ssh = _needs_ssh or needs_ssh interpreter = self.interpreter if use_sudo is not None: if use_sudo: interpreter = 'sudo ' + interpreter elif self.sudo: interpreter = 'sudo ' + interpreter if _needs_ssh(hostname) or self.use_ssh: if self.ssh_options: return 'ssh=%s %s//python=%s' % ( self.ssh_options, hostname, interpreter ) else: return 'ssh=%s//python=%s' % (hostname, interpreter) return 'popen//python=%s' % interpreter def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.group.terminate(timeout=1.0) return False def cmd(self, cmd): """ In the base connection class, this method just returns the ``cmd`` as-is. Other implementations will end up doing transformations to the command by prefixing it with other flags needed. See :class:`KubernetesConnection` for an example """ return cmd def execute(self, function, **kw): return self.gateway.remote_exec(function, **kw) def exit(self): self.group.terminate(timeout=1.0) def import_module(self, module, python_executable=None): """ Allows remote execution of a local module. Depending on the ``remote_import_system`` attribute it may use execnet's implementation or remoto's own based on JSON. .. note:: It is not possible to use execnet's remote execution model on connections that aren't SSH or Local. """ if self.remote_import_system is not None: if self.remote_import_system == 'json': self.remote_module = JsonModuleExecute(self, module, self.logger, python_executable=python_executable) else: self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger) else: self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger) return self.remote_module def has_connection(self): if self.gateway: return self.gateway.hasreceiver() return False class LegacyModuleExecute(object): """ This (now legacy) class, is the way ``execnet`` does its remote module execution: it sends it over a channel, and does a send/receive for exchanging information. This only works when there is native support in execnet for a given connection. This currently means it would only work for ssh and local (Popen) connections, and will not work for anything like kubernetes or containers. """ def __init__(self, gateway, module, logger=None): self.channel = gateway.remote_exec(module) self.module = module self.logger = logger def __getattr__(self, name): if not hasattr(self.module, name): msg = "module %s does not have attribute %s" % (str(self.module), name) raise AttributeError(msg) docstring = self._get_func_doc(getattr(self.module, name)) def wrapper(*args): arguments = self._convert_args(args) if docstring: self.logger.debug(docstring) self.channel.send("%s(%s)" % (name, arguments)) try: return self.channel.receive() except Exception as error: # Error will come as a string of a traceback, remove everything # up to the actual exception since we do get garbage otherwise # that points to non-existent lines in the compiled code exc_line = str(error) for tb_line in reversed(str(error).split('\n')): if tb_line: exc_line = tb_line break raise RuntimeError(exc_line) return wrapper def _get_func_doc(self, func): try: return getattr(func, 'func_doc').strip() except AttributeError: return '' def _convert_args(self, args): if args: if len(args) > 1: arguments = str(args).rstrip(')').lstrip('(') else: arguments = str(args).rstrip(',)').lstrip('(') else: arguments = '' return arguments dump_template = """ if __name__ == '__main__': import json, traceback obj = {'return': None, 'exception': None} try: obj['return'] = %s%s except Exception: obj['exception'] = traceback.format_exc() try: print(json.dumps(obj).decode('utf-8')) except AttributeError: print(json.dumps(obj)) """ class JsonModuleExecute(object): """ This remote execution class allows to ship Python code over to the remote node, load it via ``stdin`` and call any function with arguments. The resulting response is dumped over JSON so that it can get printed to ``stdout``, then captured locally, loaded into regular Python and returned. If the remote end generates an exception with a traceback, that is captured as well and raised accordingly. """ def __init__(self, conn, module, logger=None, python_executable=None): self.conn = conn self.module = module self._module_source = inspect.getsource(module) self.logger = logger self.python_executable = python_executable def __getattr__(self, name): if not hasattr(self.module, name): msg = "module %s does not have attribute %s" % (str(self.module), name) raise AttributeError(msg) docstring = self._get_func_doc(getattr(self.module, name)) def wrapper(*args): if docstring: self.logger.debug(docstring) if len(args): source = self._module_source + dump_template % (name, repr(args)) else: source = self._module_source + dump_template % (name, '()') # check python interpreter if self.python_executable is None: self.python_executable = get_python_executable(self.conn) out, err, code = check(self.conn, [self.python_executable], stdin=source.encode('utf-8')) if not out: if not err: err = [ 'Traceback (most recent call last):', ' File "<stdin>", in <module>', 'Exception: error calling "%s"' % name ] if code: raise Exception('Unexpected remote exception: \n%s\n%s' % ('\n'.join(out), '\n'.join(err))) # at this point, there was no stdout, and the exit code was 0, # we must return so that we don't fail trying to serialize back # the JSON return response = json.loads(out[0]) if response['exception']: raise Exception(response['exception']) return response['return'] return wrapper def _get_func_doc(self, func): try: return getattr(func, 'func_doc').strip() except AttributeError: return '' def basic_remote_logger(): logging.basicConfig() logger = logging.getLogger(socket.gethostname()) logger.setLevel(logging.DEBUG) return logger def needs_ssh(hostname, _socket=None): """ Obtains remote hostname of the socket and cuts off the domain part of its FQDN. """ if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']: return False _socket = _socket or socket fqdn = _socket.getfqdn() if hostname == fqdn: return False local_hostname = _socket.gethostname() local_short_hostname = local_hostname.split('.')[0] if local_hostname == hostname or local_short_hostname == hostname: return False return True def get_python_executable(conn): """ Try to determine the remote Python version so that it can be used when executing. Avoids the problem of different Python versions, or distros that do not use ``python`` but do ``python3`` """ # executables in order of preference: executables = ['python3', 'python', 'python2.7'] for executable in executables: conn.logger.debug('trying to determine remote python executable with %s' % executable) out, err, code = check(conn, ['which', executable]) if code: conn.logger.warning('skipping %s, was not found in path' % executable) else: try: return out[0].strip() except IndexError: conn.logger.warning('could not parse stdout: %s' % out) # if all fails, we just return whatever the main connection had conn.logger.info('Falling back to using interpreter: %s' % conn.interpreter) return conn.interpreter
normal
{ "blob_id": "ae38995d153deed2e6049b7b65fb5f28dfcef470", "index": 1442, "step-1": "<mask token>\n\n\nclass BaseConnection(object):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=\n True, detect_sudo=False, use_ssh=False, interpreter=None,\n ssh_options=None):\n self.sudo = sudo\n self.hostname = hostname\n self.ssh_options = ssh_options\n self.logger = logger or basic_remote_logger()\n self.remote_module = None\n self.channel = None\n self.use_ssh = use_ssh\n self.global_timeout = None\n self.interpreter = interpreter or 'python%s' % sys.version_info[0]\n if eager:\n try:\n if detect_sudo:\n self.sudo = self._detect_sudo()\n self.gateway = self._make_gateway(hostname)\n except OSError:\n self.logger.error(\n \"Can't communicate with remote host, possibly because %s is not installed there\"\n % self.interpreter)\n raise\n <mask token>\n\n def _detect_sudo(self, _execnet=None):\n \"\"\"\n ``sudo`` detection has to create a different connection to the remote\n host so that we can reliably ensure that ``getuser()`` will return the\n right information.\n\n After getting the user info it closes the connection and returns\n a boolean\n \"\"\"\n exc = _execnet or execnet\n gw = exc.makegateway(self._make_connection_string(self.hostname,\n use_sudo=False))\n channel = gw.remote_exec(\n 'import getpass; channel.send(getpass.getuser())')\n result = channel.receive()\n gw.exit()\n if result == 'root':\n return False\n self.logger.debug('connection detected need for sudo')\n return True\n <mask token>\n\n def __enter__(self):\n return self\n <mask token>\n <mask token>\n\n def execute(self, function, **kw):\n return self.gateway.remote_exec(function, **kw)\n\n def exit(self):\n self.group.terminate(timeout=1.0)\n\n def import_module(self, module, python_executable=None):\n \"\"\"\n Allows remote execution of a local module. Depending on the\n ``remote_import_system`` attribute it may use execnet's implementation\n or remoto's own based on JSON.\n\n .. note:: It is not possible to use execnet's remote execution model on\n connections that aren't SSH or Local.\n \"\"\"\n if self.remote_import_system is not None:\n if self.remote_import_system == 'json':\n self.remote_module = JsonModuleExecute(self, module, self.\n logger, python_executable=python_executable)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway,\n module, self.logger)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway, module,\n self.logger)\n return self.remote_module\n\n def has_connection(self):\n if self.gateway:\n return self.gateway.hasreceiver()\n return False\n\n\nclass LegacyModuleExecute(object):\n \"\"\"\n This (now legacy) class, is the way ``execnet`` does its remote module\n execution: it sends it over a channel, and does a send/receive for\n exchanging information. This only works when there is native support in\n execnet for a given connection. This currently means it would only work for\n ssh and local (Popen) connections, and will not work for anything like\n kubernetes or containers.\n \"\"\"\n\n def __init__(self, gateway, module, logger=None):\n self.channel = gateway.remote_exec(module)\n self.module = module\n self.logger = logger\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n arguments = self._convert_args(args)\n if docstring:\n self.logger.debug(docstring)\n self.channel.send('%s(%s)' % (name, arguments))\n try:\n return self.channel.receive()\n except Exception as error:\n exc_line = str(error)\n for tb_line in reversed(str(error).split('\\n')):\n if tb_line:\n exc_line = tb_line\n break\n raise RuntimeError(exc_line)\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n def _convert_args(self, args):\n if args:\n if len(args) > 1:\n arguments = str(args).rstrip(')').lstrip('(')\n else:\n arguments = str(args).rstrip(',)').lstrip('(')\n else:\n arguments = ''\n return arguments\n\n\n<mask token>\n\n\nclass JsonModuleExecute(object):\n \"\"\"\n This remote execution class allows to ship Python code over to the remote\n node, load it via ``stdin`` and call any function with arguments. The\n resulting response is dumped over JSON so that it can get printed to\n ``stdout``, then captured locally, loaded into regular Python and returned.\n\n If the remote end generates an exception with a traceback, that is captured\n as well and raised accordingly.\n \"\"\"\n\n def __init__(self, conn, module, logger=None, python_executable=None):\n self.conn = conn\n self.module = module\n self._module_source = inspect.getsource(module)\n self.logger = logger\n self.python_executable = python_executable\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n if docstring:\n self.logger.debug(docstring)\n if len(args):\n source = self._module_source + dump_template % (name, repr(\n args))\n else:\n source = self._module_source + dump_template % (name, '()')\n if self.python_executable is None:\n self.python_executable = get_python_executable(self.conn)\n out, err, code = check(self.conn, [self.python_executable],\n stdin=source.encode('utf-8'))\n if not out:\n if not err:\n err = ['Traceback (most recent call last):',\n ' File \"<stdin>\", in <module>', \n 'Exception: error calling \"%s\"' % name]\n if code:\n raise Exception('Unexpected remote exception: \\n%s\\n%s' %\n ('\\n'.join(out), '\\n'.join(err)))\n return\n response = json.loads(out[0])\n if response['exception']:\n raise Exception(response['exception'])\n return response['return']\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass BaseConnection(object):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=\n True, detect_sudo=False, use_ssh=False, interpreter=None,\n ssh_options=None):\n self.sudo = sudo\n self.hostname = hostname\n self.ssh_options = ssh_options\n self.logger = logger or basic_remote_logger()\n self.remote_module = None\n self.channel = None\n self.use_ssh = use_ssh\n self.global_timeout = None\n self.interpreter = interpreter or 'python%s' % sys.version_info[0]\n if eager:\n try:\n if detect_sudo:\n self.sudo = self._detect_sudo()\n self.gateway = self._make_gateway(hostname)\n except OSError:\n self.logger.error(\n \"Can't communicate with remote host, possibly because %s is not installed there\"\n % self.interpreter)\n raise\n\n def _make_gateway(self, hostname):\n self.group = execnet.Group()\n gateway = self.group.makegateway(self._make_connection_string(hostname)\n )\n gateway.reconfigure(py2str_as_py3str=False, py3str_as_py2str=False)\n return gateway\n\n def _detect_sudo(self, _execnet=None):\n \"\"\"\n ``sudo`` detection has to create a different connection to the remote\n host so that we can reliably ensure that ``getuser()`` will return the\n right information.\n\n After getting the user info it closes the connection and returns\n a boolean\n \"\"\"\n exc = _execnet or execnet\n gw = exc.makegateway(self._make_connection_string(self.hostname,\n use_sudo=False))\n channel = gw.remote_exec(\n 'import getpass; channel.send(getpass.getuser())')\n result = channel.receive()\n gw.exit()\n if result == 'root':\n return False\n self.logger.debug('connection detected need for sudo')\n return True\n\n def _make_connection_string(self, hostname, _needs_ssh=None, use_sudo=None\n ):\n _needs_ssh = _needs_ssh or needs_ssh\n interpreter = self.interpreter\n if use_sudo is not None:\n if use_sudo:\n interpreter = 'sudo ' + interpreter\n elif self.sudo:\n interpreter = 'sudo ' + interpreter\n if _needs_ssh(hostname) or self.use_ssh:\n if self.ssh_options:\n return 'ssh=%s %s//python=%s' % (self.ssh_options, hostname,\n interpreter)\n else:\n return 'ssh=%s//python=%s' % (hostname, interpreter)\n return 'popen//python=%s' % interpreter\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.group.terminate(timeout=1.0)\n return False\n\n def cmd(self, cmd):\n \"\"\"\n In the base connection class, this method just returns the ``cmd``\n as-is. Other implementations will end up doing transformations to the\n command by prefixing it with other flags needed. See\n :class:`KubernetesConnection` for an example\n \"\"\"\n return cmd\n\n def execute(self, function, **kw):\n return self.gateway.remote_exec(function, **kw)\n\n def exit(self):\n self.group.terminate(timeout=1.0)\n\n def import_module(self, module, python_executable=None):\n \"\"\"\n Allows remote execution of a local module. Depending on the\n ``remote_import_system`` attribute it may use execnet's implementation\n or remoto's own based on JSON.\n\n .. note:: It is not possible to use execnet's remote execution model on\n connections that aren't SSH or Local.\n \"\"\"\n if self.remote_import_system is not None:\n if self.remote_import_system == 'json':\n self.remote_module = JsonModuleExecute(self, module, self.\n logger, python_executable=python_executable)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway,\n module, self.logger)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway, module,\n self.logger)\n return self.remote_module\n\n def has_connection(self):\n if self.gateway:\n return self.gateway.hasreceiver()\n return False\n\n\nclass LegacyModuleExecute(object):\n \"\"\"\n This (now legacy) class, is the way ``execnet`` does its remote module\n execution: it sends it over a channel, and does a send/receive for\n exchanging information. This only works when there is native support in\n execnet for a given connection. This currently means it would only work for\n ssh and local (Popen) connections, and will not work for anything like\n kubernetes or containers.\n \"\"\"\n\n def __init__(self, gateway, module, logger=None):\n self.channel = gateway.remote_exec(module)\n self.module = module\n self.logger = logger\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n arguments = self._convert_args(args)\n if docstring:\n self.logger.debug(docstring)\n self.channel.send('%s(%s)' % (name, arguments))\n try:\n return self.channel.receive()\n except Exception as error:\n exc_line = str(error)\n for tb_line in reversed(str(error).split('\\n')):\n if tb_line:\n exc_line = tb_line\n break\n raise RuntimeError(exc_line)\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n def _convert_args(self, args):\n if args:\n if len(args) > 1:\n arguments = str(args).rstrip(')').lstrip('(')\n else:\n arguments = str(args).rstrip(',)').lstrip('(')\n else:\n arguments = ''\n return arguments\n\n\n<mask token>\n\n\nclass JsonModuleExecute(object):\n \"\"\"\n This remote execution class allows to ship Python code over to the remote\n node, load it via ``stdin`` and call any function with arguments. The\n resulting response is dumped over JSON so that it can get printed to\n ``stdout``, then captured locally, loaded into regular Python and returned.\n\n If the remote end generates an exception with a traceback, that is captured\n as well and raised accordingly.\n \"\"\"\n\n def __init__(self, conn, module, logger=None, python_executable=None):\n self.conn = conn\n self.module = module\n self._module_source = inspect.getsource(module)\n self.logger = logger\n self.python_executable = python_executable\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n if docstring:\n self.logger.debug(docstring)\n if len(args):\n source = self._module_source + dump_template % (name, repr(\n args))\n else:\n source = self._module_source + dump_template % (name, '()')\n if self.python_executable is None:\n self.python_executable = get_python_executable(self.conn)\n out, err, code = check(self.conn, [self.python_executable],\n stdin=source.encode('utf-8'))\n if not out:\n if not err:\n err = ['Traceback (most recent call last):',\n ' File \"<stdin>\", in <module>', \n 'Exception: error calling \"%s\"' % name]\n if code:\n raise Exception('Unexpected remote exception: \\n%s\\n%s' %\n ('\\n'.join(out), '\\n'.join(err)))\n return\n response = json.loads(out[0])\n if response['exception']:\n raise Exception(response['exception'])\n return response['return']\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass BaseConnection(object):\n \"\"\"\n Base class for Connection objects. Provides a generic interface to execnet\n for setting up the connection\n \"\"\"\n executable = ''\n remote_import_system = 'legacy'\n\n def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=\n True, detect_sudo=False, use_ssh=False, interpreter=None,\n ssh_options=None):\n self.sudo = sudo\n self.hostname = hostname\n self.ssh_options = ssh_options\n self.logger = logger or basic_remote_logger()\n self.remote_module = None\n self.channel = None\n self.use_ssh = use_ssh\n self.global_timeout = None\n self.interpreter = interpreter or 'python%s' % sys.version_info[0]\n if eager:\n try:\n if detect_sudo:\n self.sudo = self._detect_sudo()\n self.gateway = self._make_gateway(hostname)\n except OSError:\n self.logger.error(\n \"Can't communicate with remote host, possibly because %s is not installed there\"\n % self.interpreter)\n raise\n\n def _make_gateway(self, hostname):\n self.group = execnet.Group()\n gateway = self.group.makegateway(self._make_connection_string(hostname)\n )\n gateway.reconfigure(py2str_as_py3str=False, py3str_as_py2str=False)\n return gateway\n\n def _detect_sudo(self, _execnet=None):\n \"\"\"\n ``sudo`` detection has to create a different connection to the remote\n host so that we can reliably ensure that ``getuser()`` will return the\n right information.\n\n After getting the user info it closes the connection and returns\n a boolean\n \"\"\"\n exc = _execnet or execnet\n gw = exc.makegateway(self._make_connection_string(self.hostname,\n use_sudo=False))\n channel = gw.remote_exec(\n 'import getpass; channel.send(getpass.getuser())')\n result = channel.receive()\n gw.exit()\n if result == 'root':\n return False\n self.logger.debug('connection detected need for sudo')\n return True\n\n def _make_connection_string(self, hostname, _needs_ssh=None, use_sudo=None\n ):\n _needs_ssh = _needs_ssh or needs_ssh\n interpreter = self.interpreter\n if use_sudo is not None:\n if use_sudo:\n interpreter = 'sudo ' + interpreter\n elif self.sudo:\n interpreter = 'sudo ' + interpreter\n if _needs_ssh(hostname) or self.use_ssh:\n if self.ssh_options:\n return 'ssh=%s %s//python=%s' % (self.ssh_options, hostname,\n interpreter)\n else:\n return 'ssh=%s//python=%s' % (hostname, interpreter)\n return 'popen//python=%s' % interpreter\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.group.terminate(timeout=1.0)\n return False\n\n def cmd(self, cmd):\n \"\"\"\n In the base connection class, this method just returns the ``cmd``\n as-is. Other implementations will end up doing transformations to the\n command by prefixing it with other flags needed. See\n :class:`KubernetesConnection` for an example\n \"\"\"\n return cmd\n\n def execute(self, function, **kw):\n return self.gateway.remote_exec(function, **kw)\n\n def exit(self):\n self.group.terminate(timeout=1.0)\n\n def import_module(self, module, python_executable=None):\n \"\"\"\n Allows remote execution of a local module. Depending on the\n ``remote_import_system`` attribute it may use execnet's implementation\n or remoto's own based on JSON.\n\n .. note:: It is not possible to use execnet's remote execution model on\n connections that aren't SSH or Local.\n \"\"\"\n if self.remote_import_system is not None:\n if self.remote_import_system == 'json':\n self.remote_module = JsonModuleExecute(self, module, self.\n logger, python_executable=python_executable)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway,\n module, self.logger)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway, module,\n self.logger)\n return self.remote_module\n\n def has_connection(self):\n if self.gateway:\n return self.gateway.hasreceiver()\n return False\n\n\nclass LegacyModuleExecute(object):\n \"\"\"\n This (now legacy) class, is the way ``execnet`` does its remote module\n execution: it sends it over a channel, and does a send/receive for\n exchanging information. This only works when there is native support in\n execnet for a given connection. This currently means it would only work for\n ssh and local (Popen) connections, and will not work for anything like\n kubernetes or containers.\n \"\"\"\n\n def __init__(self, gateway, module, logger=None):\n self.channel = gateway.remote_exec(module)\n self.module = module\n self.logger = logger\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n arguments = self._convert_args(args)\n if docstring:\n self.logger.debug(docstring)\n self.channel.send('%s(%s)' % (name, arguments))\n try:\n return self.channel.receive()\n except Exception as error:\n exc_line = str(error)\n for tb_line in reversed(str(error).split('\\n')):\n if tb_line:\n exc_line = tb_line\n break\n raise RuntimeError(exc_line)\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n def _convert_args(self, args):\n if args:\n if len(args) > 1:\n arguments = str(args).rstrip(')').lstrip('(')\n else:\n arguments = str(args).rstrip(',)').lstrip('(')\n else:\n arguments = ''\n return arguments\n\n\n<mask token>\n\n\nclass JsonModuleExecute(object):\n \"\"\"\n This remote execution class allows to ship Python code over to the remote\n node, load it via ``stdin`` and call any function with arguments. The\n resulting response is dumped over JSON so that it can get printed to\n ``stdout``, then captured locally, loaded into regular Python and returned.\n\n If the remote end generates an exception with a traceback, that is captured\n as well and raised accordingly.\n \"\"\"\n\n def __init__(self, conn, module, logger=None, python_executable=None):\n self.conn = conn\n self.module = module\n self._module_source = inspect.getsource(module)\n self.logger = logger\n self.python_executable = python_executable\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n if docstring:\n self.logger.debug(docstring)\n if len(args):\n source = self._module_source + dump_template % (name, repr(\n args))\n else:\n source = self._module_source + dump_template % (name, '()')\n if self.python_executable is None:\n self.python_executable = get_python_executable(self.conn)\n out, err, code = check(self.conn, [self.python_executable],\n stdin=source.encode('utf-8'))\n if not out:\n if not err:\n err = ['Traceback (most recent call last):',\n ' File \"<stdin>\", in <module>', \n 'Exception: error calling \"%s\"' % name]\n if code:\n raise Exception('Unexpected remote exception: \\n%s\\n%s' %\n ('\\n'.join(out), '\\n'.join(err)))\n return\n response = json.loads(out[0])\n if response['exception']:\n raise Exception(response['exception'])\n return response['return']\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n\ndef basic_remote_logger():\n logging.basicConfig()\n logger = logging.getLogger(socket.gethostname())\n logger.setLevel(logging.DEBUG)\n return logger\n\n\ndef needs_ssh(hostname, _socket=None):\n \"\"\"\n Obtains remote hostname of the socket and cuts off the domain part\n of its FQDN.\n \"\"\"\n if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:\n return False\n _socket = _socket or socket\n fqdn = _socket.getfqdn()\n if hostname == fqdn:\n return False\n local_hostname = _socket.gethostname()\n local_short_hostname = local_hostname.split('.')[0]\n if local_hostname == hostname or local_short_hostname == hostname:\n return False\n return True\n\n\n<mask token>\n", "step-4": "import inspect\nimport json\nimport socket\nimport sys\nimport execnet\nimport logging\nfrom remoto.process import check\n\n\nclass BaseConnection(object):\n \"\"\"\n Base class for Connection objects. Provides a generic interface to execnet\n for setting up the connection\n \"\"\"\n executable = ''\n remote_import_system = 'legacy'\n\n def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=\n True, detect_sudo=False, use_ssh=False, interpreter=None,\n ssh_options=None):\n self.sudo = sudo\n self.hostname = hostname\n self.ssh_options = ssh_options\n self.logger = logger or basic_remote_logger()\n self.remote_module = None\n self.channel = None\n self.use_ssh = use_ssh\n self.global_timeout = None\n self.interpreter = interpreter or 'python%s' % sys.version_info[0]\n if eager:\n try:\n if detect_sudo:\n self.sudo = self._detect_sudo()\n self.gateway = self._make_gateway(hostname)\n except OSError:\n self.logger.error(\n \"Can't communicate with remote host, possibly because %s is not installed there\"\n % self.interpreter)\n raise\n\n def _make_gateway(self, hostname):\n self.group = execnet.Group()\n gateway = self.group.makegateway(self._make_connection_string(hostname)\n )\n gateway.reconfigure(py2str_as_py3str=False, py3str_as_py2str=False)\n return gateway\n\n def _detect_sudo(self, _execnet=None):\n \"\"\"\n ``sudo`` detection has to create a different connection to the remote\n host so that we can reliably ensure that ``getuser()`` will return the\n right information.\n\n After getting the user info it closes the connection and returns\n a boolean\n \"\"\"\n exc = _execnet or execnet\n gw = exc.makegateway(self._make_connection_string(self.hostname,\n use_sudo=False))\n channel = gw.remote_exec(\n 'import getpass; channel.send(getpass.getuser())')\n result = channel.receive()\n gw.exit()\n if result == 'root':\n return False\n self.logger.debug('connection detected need for sudo')\n return True\n\n def _make_connection_string(self, hostname, _needs_ssh=None, use_sudo=None\n ):\n _needs_ssh = _needs_ssh or needs_ssh\n interpreter = self.interpreter\n if use_sudo is not None:\n if use_sudo:\n interpreter = 'sudo ' + interpreter\n elif self.sudo:\n interpreter = 'sudo ' + interpreter\n if _needs_ssh(hostname) or self.use_ssh:\n if self.ssh_options:\n return 'ssh=%s %s//python=%s' % (self.ssh_options, hostname,\n interpreter)\n else:\n return 'ssh=%s//python=%s' % (hostname, interpreter)\n return 'popen//python=%s' % interpreter\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.group.terminate(timeout=1.0)\n return False\n\n def cmd(self, cmd):\n \"\"\"\n In the base connection class, this method just returns the ``cmd``\n as-is. Other implementations will end up doing transformations to the\n command by prefixing it with other flags needed. See\n :class:`KubernetesConnection` for an example\n \"\"\"\n return cmd\n\n def execute(self, function, **kw):\n return self.gateway.remote_exec(function, **kw)\n\n def exit(self):\n self.group.terminate(timeout=1.0)\n\n def import_module(self, module, python_executable=None):\n \"\"\"\n Allows remote execution of a local module. Depending on the\n ``remote_import_system`` attribute it may use execnet's implementation\n or remoto's own based on JSON.\n\n .. note:: It is not possible to use execnet's remote execution model on\n connections that aren't SSH or Local.\n \"\"\"\n if self.remote_import_system is not None:\n if self.remote_import_system == 'json':\n self.remote_module = JsonModuleExecute(self, module, self.\n logger, python_executable=python_executable)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway,\n module, self.logger)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway, module,\n self.logger)\n return self.remote_module\n\n def has_connection(self):\n if self.gateway:\n return self.gateway.hasreceiver()\n return False\n\n\nclass LegacyModuleExecute(object):\n \"\"\"\n This (now legacy) class, is the way ``execnet`` does its remote module\n execution: it sends it over a channel, and does a send/receive for\n exchanging information. This only works when there is native support in\n execnet for a given connection. This currently means it would only work for\n ssh and local (Popen) connections, and will not work for anything like\n kubernetes or containers.\n \"\"\"\n\n def __init__(self, gateway, module, logger=None):\n self.channel = gateway.remote_exec(module)\n self.module = module\n self.logger = logger\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n arguments = self._convert_args(args)\n if docstring:\n self.logger.debug(docstring)\n self.channel.send('%s(%s)' % (name, arguments))\n try:\n return self.channel.receive()\n except Exception as error:\n exc_line = str(error)\n for tb_line in reversed(str(error).split('\\n')):\n if tb_line:\n exc_line = tb_line\n break\n raise RuntimeError(exc_line)\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n def _convert_args(self, args):\n if args:\n if len(args) > 1:\n arguments = str(args).rstrip(')').lstrip('(')\n else:\n arguments = str(args).rstrip(',)').lstrip('(')\n else:\n arguments = ''\n return arguments\n\n\ndump_template = \"\"\"\nif __name__ == '__main__':\n import json, traceback\n obj = {'return': None, 'exception': None}\n try:\n obj['return'] = %s%s\n except Exception:\n obj['exception'] = traceback.format_exc()\n try:\n print(json.dumps(obj).decode('utf-8'))\n except AttributeError:\n print(json.dumps(obj))\n\"\"\"\n\n\nclass JsonModuleExecute(object):\n \"\"\"\n This remote execution class allows to ship Python code over to the remote\n node, load it via ``stdin`` and call any function with arguments. The\n resulting response is dumped over JSON so that it can get printed to\n ``stdout``, then captured locally, loaded into regular Python and returned.\n\n If the remote end generates an exception with a traceback, that is captured\n as well and raised accordingly.\n \"\"\"\n\n def __init__(self, conn, module, logger=None, python_executable=None):\n self.conn = conn\n self.module = module\n self._module_source = inspect.getsource(module)\n self.logger = logger\n self.python_executable = python_executable\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = 'module %s does not have attribute %s' % (str(self.module\n ), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n if docstring:\n self.logger.debug(docstring)\n if len(args):\n source = self._module_source + dump_template % (name, repr(\n args))\n else:\n source = self._module_source + dump_template % (name, '()')\n if self.python_executable is None:\n self.python_executable = get_python_executable(self.conn)\n out, err, code = check(self.conn, [self.python_executable],\n stdin=source.encode('utf-8'))\n if not out:\n if not err:\n err = ['Traceback (most recent call last):',\n ' File \"<stdin>\", in <module>', \n 'Exception: error calling \"%s\"' % name]\n if code:\n raise Exception('Unexpected remote exception: \\n%s\\n%s' %\n ('\\n'.join(out), '\\n'.join(err)))\n return\n response = json.loads(out[0])\n if response['exception']:\n raise Exception(response['exception'])\n return response['return']\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n\ndef basic_remote_logger():\n logging.basicConfig()\n logger = logging.getLogger(socket.gethostname())\n logger.setLevel(logging.DEBUG)\n return logger\n\n\ndef needs_ssh(hostname, _socket=None):\n \"\"\"\n Obtains remote hostname of the socket and cuts off the domain part\n of its FQDN.\n \"\"\"\n if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:\n return False\n _socket = _socket or socket\n fqdn = _socket.getfqdn()\n if hostname == fqdn:\n return False\n local_hostname = _socket.gethostname()\n local_short_hostname = local_hostname.split('.')[0]\n if local_hostname == hostname or local_short_hostname == hostname:\n return False\n return True\n\n\ndef get_python_executable(conn):\n \"\"\"\n Try to determine the remote Python version so that it can be used\n when executing. Avoids the problem of different Python versions, or distros\n that do not use ``python`` but do ``python3``\n \"\"\"\n executables = ['python3', 'python', 'python2.7']\n for executable in executables:\n conn.logger.debug(\n 'trying to determine remote python executable with %s' % executable\n )\n out, err, code = check(conn, ['which', executable])\n if code:\n conn.logger.warning('skipping %s, was not found in path' %\n executable)\n else:\n try:\n return out[0].strip()\n except IndexError:\n conn.logger.warning('could not parse stdout: %s' % out)\n conn.logger.info('Falling back to using interpreter: %s' % conn.interpreter\n )\n return conn.interpreter\n", "step-5": "import inspect\nimport json\nimport socket\nimport sys\nimport execnet\nimport logging\nfrom remoto.process import check\n\n\nclass BaseConnection(object):\n \"\"\"\n Base class for Connection objects. Provides a generic interface to execnet\n for setting up the connection\n \"\"\"\n executable = ''\n remote_import_system = 'legacy'\n\n def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=True,\n detect_sudo=False, use_ssh=False, interpreter=None, ssh_options=None):\n self.sudo = sudo\n self.hostname = hostname\n self.ssh_options = ssh_options\n self.logger = logger or basic_remote_logger()\n self.remote_module = None\n self.channel = None\n self.use_ssh = use_ssh\n self.global_timeout = None # wait for ever\n\n self.interpreter = interpreter or 'python%s' % sys.version_info[0]\n\n if eager:\n try:\n if detect_sudo:\n self.sudo = self._detect_sudo()\n self.gateway = self._make_gateway(hostname)\n except OSError:\n self.logger.error(\n \"Can't communicate with remote host, possibly because \"\n \"%s is not installed there\" % self.interpreter\n )\n raise\n\n def _make_gateway(self, hostname):\n self.group = execnet.Group()\n gateway = self.group.makegateway(\n self._make_connection_string(hostname)\n )\n gateway.reconfigure(py2str_as_py3str=False, py3str_as_py2str=False)\n return gateway\n\n def _detect_sudo(self, _execnet=None):\n \"\"\"\n ``sudo`` detection has to create a different connection to the remote\n host so that we can reliably ensure that ``getuser()`` will return the\n right information.\n\n After getting the user info it closes the connection and returns\n a boolean\n \"\"\"\n exc = _execnet or execnet\n gw = exc.makegateway(\n self._make_connection_string(self.hostname, use_sudo=False)\n )\n\n channel = gw.remote_exec(\n 'import getpass; channel.send(getpass.getuser())'\n )\n\n result = channel.receive()\n gw.exit()\n\n if result == 'root':\n return False\n self.logger.debug('connection detected need for sudo')\n return True\n\n def _make_connection_string(self, hostname, _needs_ssh=None, use_sudo=None):\n _needs_ssh = _needs_ssh or needs_ssh\n interpreter = self.interpreter\n if use_sudo is not None:\n if use_sudo:\n interpreter = 'sudo ' + interpreter\n elif self.sudo:\n interpreter = 'sudo ' + interpreter\n\n if _needs_ssh(hostname) or self.use_ssh:\n if self.ssh_options:\n return 'ssh=%s %s//python=%s' % (\n self.ssh_options, hostname, interpreter\n )\n else:\n return 'ssh=%s//python=%s' % (hostname, interpreter)\n return 'popen//python=%s' % interpreter\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.group.terminate(timeout=1.0)\n return False\n\n def cmd(self, cmd):\n \"\"\"\n In the base connection class, this method just returns the ``cmd``\n as-is. Other implementations will end up doing transformations to the\n command by prefixing it with other flags needed. See\n :class:`KubernetesConnection` for an example\n \"\"\"\n return cmd\n\n def execute(self, function, **kw):\n return self.gateway.remote_exec(function, **kw)\n\n def exit(self):\n self.group.terminate(timeout=1.0)\n\n def import_module(self, module, python_executable=None):\n \"\"\"\n Allows remote execution of a local module. Depending on the\n ``remote_import_system`` attribute it may use execnet's implementation\n or remoto's own based on JSON.\n\n .. note:: It is not possible to use execnet's remote execution model on\n connections that aren't SSH or Local.\n \"\"\"\n if self.remote_import_system is not None:\n if self.remote_import_system == 'json':\n self.remote_module = JsonModuleExecute(self, module, self.logger,\n python_executable=python_executable)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger)\n else:\n self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger)\n return self.remote_module\n\n def has_connection(self):\n if self.gateway:\n return self.gateway.hasreceiver()\n return False\n\n\nclass LegacyModuleExecute(object):\n \"\"\"\n This (now legacy) class, is the way ``execnet`` does its remote module\n execution: it sends it over a channel, and does a send/receive for\n exchanging information. This only works when there is native support in\n execnet for a given connection. This currently means it would only work for\n ssh and local (Popen) connections, and will not work for anything like\n kubernetes or containers.\n \"\"\"\n\n def __init__(self, gateway, module, logger=None):\n self.channel = gateway.remote_exec(module)\n self.module = module\n self.logger = logger\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = \"module %s does not have attribute %s\" % (str(self.module), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n arguments = self._convert_args(args)\n if docstring:\n self.logger.debug(docstring)\n self.channel.send(\"%s(%s)\" % (name, arguments))\n try:\n return self.channel.receive()\n except Exception as error:\n # Error will come as a string of a traceback, remove everything\n # up to the actual exception since we do get garbage otherwise\n # that points to non-existent lines in the compiled code\n exc_line = str(error)\n for tb_line in reversed(str(error).split('\\n')):\n if tb_line:\n exc_line = tb_line\n break\n raise RuntimeError(exc_line)\n\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n def _convert_args(self, args):\n if args:\n if len(args) > 1:\n arguments = str(args).rstrip(')').lstrip('(')\n else:\n arguments = str(args).rstrip(',)').lstrip('(')\n else:\n arguments = ''\n return arguments\n\n\ndump_template = \"\"\"\nif __name__ == '__main__':\n import json, traceback\n obj = {'return': None, 'exception': None}\n try:\n obj['return'] = %s%s\n except Exception:\n obj['exception'] = traceback.format_exc()\n try:\n print(json.dumps(obj).decode('utf-8'))\n except AttributeError:\n print(json.dumps(obj))\n\"\"\"\n\n\nclass JsonModuleExecute(object):\n \"\"\"\n This remote execution class allows to ship Python code over to the remote\n node, load it via ``stdin`` and call any function with arguments. The\n resulting response is dumped over JSON so that it can get printed to\n ``stdout``, then captured locally, loaded into regular Python and returned.\n\n If the remote end generates an exception with a traceback, that is captured\n as well and raised accordingly.\n \"\"\"\n\n def __init__(self, conn, module, logger=None, python_executable=None):\n self.conn = conn\n self.module = module\n self._module_source = inspect.getsource(module)\n self.logger = logger\n self.python_executable = python_executable\n\n def __getattr__(self, name):\n if not hasattr(self.module, name):\n msg = \"module %s does not have attribute %s\" % (str(self.module), name)\n raise AttributeError(msg)\n docstring = self._get_func_doc(getattr(self.module, name))\n\n def wrapper(*args):\n if docstring:\n self.logger.debug(docstring)\n if len(args):\n source = self._module_source + dump_template % (name, repr(args))\n else:\n source = self._module_source + dump_template % (name, '()')\n\n # check python interpreter\n if self.python_executable is None:\n self.python_executable = get_python_executable(self.conn)\n\n out, err, code = check(self.conn, [self.python_executable], stdin=source.encode('utf-8'))\n if not out:\n if not err:\n err = [\n 'Traceback (most recent call last):',\n ' File \"<stdin>\", in <module>',\n 'Exception: error calling \"%s\"' % name\n ]\n if code:\n raise Exception('Unexpected remote exception: \\n%s\\n%s' % ('\\n'.join(out), '\\n'.join(err)))\n # at this point, there was no stdout, and the exit code was 0,\n # we must return so that we don't fail trying to serialize back\n # the JSON\n return\n response = json.loads(out[0])\n if response['exception']:\n raise Exception(response['exception'])\n return response['return']\n\n return wrapper\n\n def _get_func_doc(self, func):\n try:\n return getattr(func, 'func_doc').strip()\n except AttributeError:\n return ''\n\n\ndef basic_remote_logger():\n logging.basicConfig()\n logger = logging.getLogger(socket.gethostname())\n logger.setLevel(logging.DEBUG)\n return logger\n\n\ndef needs_ssh(hostname, _socket=None):\n \"\"\"\n Obtains remote hostname of the socket and cuts off the domain part\n of its FQDN.\n \"\"\"\n if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:\n return False\n _socket = _socket or socket\n fqdn = _socket.getfqdn()\n if hostname == fqdn:\n return False\n local_hostname = _socket.gethostname()\n local_short_hostname = local_hostname.split('.')[0]\n if local_hostname == hostname or local_short_hostname == hostname:\n return False\n return True\n\n\ndef get_python_executable(conn):\n \"\"\"\n Try to determine the remote Python version so that it can be used\n when executing. Avoids the problem of different Python versions, or distros\n that do not use ``python`` but do ``python3``\n \"\"\"\n # executables in order of preference:\n executables = ['python3', 'python', 'python2.7']\n for executable in executables:\n conn.logger.debug('trying to determine remote python executable with %s' % executable)\n out, err, code = check(conn, ['which', executable])\n if code:\n conn.logger.warning('skipping %s, was not found in path' % executable)\n else:\n try:\n return out[0].strip()\n except IndexError:\n conn.logger.warning('could not parse stdout: %s' % out)\n\n # if all fails, we just return whatever the main connection had\n conn.logger.info('Falling back to using interpreter: %s' % conn.interpreter)\n return conn.interpreter\n", "step-ids": [ 19, 23, 27, 30, 31 ] }
[ 19, 23, 27, 30, 31 ]
<|reserved_special_token_0|> class CifarResNeXt(nn.Module): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ResNeXtBottleneck(nn.Module): <|reserved_special_token_0|> def __init__(self, in_channels, out_channels, stride, cardinality, widen_factor): """ Constructor Args: in_channels: input channel dimensionality out_channels: output channel dimensionality stride: conv stride. Replaces pooling layer. cardinality: num of convolution groups. widen_factor: factor to reduce the input dimensionality before convolution. """ super(ResNeXtBottleneck, self).__init__() D = cardinality * out_channels // widen_factor self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride= 1, padding=0, bias=False) self.bn_reduce = nn.BatchNorm2d(D) self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False) self.bn = nn.BatchNorm2d(D) self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride =1, padding=0, bias=False) self.bn_expand = nn.BatchNorm2d(out_channels) self.shortcut = nn.Sequential() if in_channels != out_channels: self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0, bias =False)) self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d( out_channels)) def forward(self, x): bottleneck = self.conv_reduce.forward(x) bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True) bottleneck = self.conv_conv.forward(bottleneck) bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True) bottleneck = self.conv_expand.forward(bottleneck) bottleneck = self.bn_expand.forward(bottleneck) residual = self.shortcut.forward(x) return F.relu(residual + bottleneck, inplace=True) class CifarResNeXt(nn.Module): """ ResNext optimized for the Cifar dataset, as specified in https://arxiv.org/pdf/1611.05431.pdf """ def __init__(self, cardinality, depth, num_classes, widen_factor=4, dropRate=0): """ Constructor Args: cardinality: number of convolution groups. depth: number of layers. num_classes: number of classes widen_factor: factor to adjust the channel dimensionality """ super(CifarResNeXt, self).__init__() self.cardinality = cardinality self.depth = depth self.block_depth = (self.depth - 2) // 9 self.widen_factor = widen_factor self.num_classes = num_classes self.output_size = 64 self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor, 256 * self.widen_factor] self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False) self.bn_1 = nn.BatchNorm2d(64) self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1) self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2) self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2) self.classifier = nn.Linear(1024, num_classes) self.stage_att = self.block('stage_att', self.stages[2], self. stages[3], 1) self.bn_att = nn.BatchNorm2d(self.stages[3]) self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size= 1, padding=0, bias=False) self.bn_att2 = nn.BatchNorm2d(num_classes) self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1, padding=0, bias=False) self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1, bias=False) self.bn_att3 = nn.BatchNorm2d(1) self.att_gap = nn.AvgPool2d(16) self.sigmoid = nn.Sigmoid() self.relu = nn.ReLU(inplace=True) init.kaiming_normal(self.classifier.weight) for key in self.state_dict(): if key.split('.')[-1] == 'weight': if 'conv' in key: init.kaiming_normal(self.state_dict()[key], mode='fan_out') if 'bn' in key: self.state_dict()[key][...] = 1 elif key.split('.')[-1] == 'bias': self.state_dict()[key][...] = 0 def block(self, name, in_channels, out_channels, pool_stride=2): """ Stack n bottleneck modules where n is inferred from the depth of the network. Args: name: string name of the current block. in_channels: number of input channels out_channels: number of output channels pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block. Returns: a Module consisting of n sequential bottlenecks. """ block = nn.Sequential() for bottleneck in range(self.block_depth): name_ = '%s_bottleneck_%d' % (name, bottleneck) if bottleneck == 0: block.add_module(name_, ResNeXtBottleneck(in_channels, out_channels, pool_stride, self.cardinality, self. widen_factor)) else: block.add_module(name_, ResNeXtBottleneck(out_channels, out_channels, 1, self.cardinality, self.widen_factor)) return block def forward(self, x): x = self.conv_1_3x3.forward(x) x = F.relu(self.bn_1.forward(x), inplace=True) x = self.stage_1.forward(x) x = self.stage_2.forward(x) ax = self.stage_att(x) ax = self.relu(self.bn_att2(self.att_conv(ax))) bs, cs, ys, xs = ax.shape self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax))) ax = self.att_conv2(ax) ax = self.att_gap(ax) ax = ax.view(ax.size(0), -1) rx = x * self.att rx = rx + x rx = self.stage_3.forward(rx) rx = F.avg_pool2d(rx, 8, 1) rx = rx.view(-1, 1024) rx = self.classifier(rx) return ax, rx, self.att <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ResNeXtBottleneck(nn.Module): """ RexNeXt bottleneck type C (https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua) """ def __init__(self, in_channels, out_channels, stride, cardinality, widen_factor): """ Constructor Args: in_channels: input channel dimensionality out_channels: output channel dimensionality stride: conv stride. Replaces pooling layer. cardinality: num of convolution groups. widen_factor: factor to reduce the input dimensionality before convolution. """ super(ResNeXtBottleneck, self).__init__() D = cardinality * out_channels // widen_factor self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride= 1, padding=0, bias=False) self.bn_reduce = nn.BatchNorm2d(D) self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False) self.bn = nn.BatchNorm2d(D) self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride =1, padding=0, bias=False) self.bn_expand = nn.BatchNorm2d(out_channels) self.shortcut = nn.Sequential() if in_channels != out_channels: self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0, bias =False)) self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d( out_channels)) def forward(self, x): bottleneck = self.conv_reduce.forward(x) bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True) bottleneck = self.conv_conv.forward(bottleneck) bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True) bottleneck = self.conv_expand.forward(bottleneck) bottleneck = self.bn_expand.forward(bottleneck) residual = self.shortcut.forward(x) return F.relu(residual + bottleneck, inplace=True) class CifarResNeXt(nn.Module): """ ResNext optimized for the Cifar dataset, as specified in https://arxiv.org/pdf/1611.05431.pdf """ def __init__(self, cardinality, depth, num_classes, widen_factor=4, dropRate=0): """ Constructor Args: cardinality: number of convolution groups. depth: number of layers. num_classes: number of classes widen_factor: factor to adjust the channel dimensionality """ super(CifarResNeXt, self).__init__() self.cardinality = cardinality self.depth = depth self.block_depth = (self.depth - 2) // 9 self.widen_factor = widen_factor self.num_classes = num_classes self.output_size = 64 self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor, 256 * self.widen_factor] self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False) self.bn_1 = nn.BatchNorm2d(64) self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1) self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2) self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2) self.classifier = nn.Linear(1024, num_classes) self.stage_att = self.block('stage_att', self.stages[2], self. stages[3], 1) self.bn_att = nn.BatchNorm2d(self.stages[3]) self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size= 1, padding=0, bias=False) self.bn_att2 = nn.BatchNorm2d(num_classes) self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1, padding=0, bias=False) self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1, bias=False) self.bn_att3 = nn.BatchNorm2d(1) self.att_gap = nn.AvgPool2d(16) self.sigmoid = nn.Sigmoid() self.relu = nn.ReLU(inplace=True) init.kaiming_normal(self.classifier.weight) for key in self.state_dict(): if key.split('.')[-1] == 'weight': if 'conv' in key: init.kaiming_normal(self.state_dict()[key], mode='fan_out') if 'bn' in key: self.state_dict()[key][...] = 1 elif key.split('.')[-1] == 'bias': self.state_dict()[key][...] = 0 def block(self, name, in_channels, out_channels, pool_stride=2): """ Stack n bottleneck modules where n is inferred from the depth of the network. Args: name: string name of the current block. in_channels: number of input channels out_channels: number of output channels pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block. Returns: a Module consisting of n sequential bottlenecks. """ block = nn.Sequential() for bottleneck in range(self.block_depth): name_ = '%s_bottleneck_%d' % (name, bottleneck) if bottleneck == 0: block.add_module(name_, ResNeXtBottleneck(in_channels, out_channels, pool_stride, self.cardinality, self. widen_factor)) else: block.add_module(name_, ResNeXtBottleneck(out_channels, out_channels, 1, self.cardinality, self.widen_factor)) return block def forward(self, x): x = self.conv_1_3x3.forward(x) x = F.relu(self.bn_1.forward(x), inplace=True) x = self.stage_1.forward(x) x = self.stage_2.forward(x) ax = self.stage_att(x) ax = self.relu(self.bn_att2(self.att_conv(ax))) bs, cs, ys, xs = ax.shape self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax))) ax = self.att_conv2(ax) ax = self.att_gap(ax) ax = ax.view(ax.size(0), -1) rx = x * self.att rx = rx + x rx = self.stage_3.forward(rx) rx = F.avg_pool2d(rx, 8, 1) rx = rx.view(-1, 1024) rx = self.classifier(rx) return ax, rx, self.att def resnext(**kwargs): """Constructs a ResNeXt. """ model = CifarResNeXt(**kwargs) return model <|reserved_special_token_1|> <|reserved_special_token_0|> __all__ = ['resnext'] class ResNeXtBottleneck(nn.Module): """ RexNeXt bottleneck type C (https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua) """ def __init__(self, in_channels, out_channels, stride, cardinality, widen_factor): """ Constructor Args: in_channels: input channel dimensionality out_channels: output channel dimensionality stride: conv stride. Replaces pooling layer. cardinality: num of convolution groups. widen_factor: factor to reduce the input dimensionality before convolution. """ super(ResNeXtBottleneck, self).__init__() D = cardinality * out_channels // widen_factor self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride= 1, padding=0, bias=False) self.bn_reduce = nn.BatchNorm2d(D) self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False) self.bn = nn.BatchNorm2d(D) self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride =1, padding=0, bias=False) self.bn_expand = nn.BatchNorm2d(out_channels) self.shortcut = nn.Sequential() if in_channels != out_channels: self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0, bias =False)) self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d( out_channels)) def forward(self, x): bottleneck = self.conv_reduce.forward(x) bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True) bottleneck = self.conv_conv.forward(bottleneck) bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True) bottleneck = self.conv_expand.forward(bottleneck) bottleneck = self.bn_expand.forward(bottleneck) residual = self.shortcut.forward(x) return F.relu(residual + bottleneck, inplace=True) class CifarResNeXt(nn.Module): """ ResNext optimized for the Cifar dataset, as specified in https://arxiv.org/pdf/1611.05431.pdf """ def __init__(self, cardinality, depth, num_classes, widen_factor=4, dropRate=0): """ Constructor Args: cardinality: number of convolution groups. depth: number of layers. num_classes: number of classes widen_factor: factor to adjust the channel dimensionality """ super(CifarResNeXt, self).__init__() self.cardinality = cardinality self.depth = depth self.block_depth = (self.depth - 2) // 9 self.widen_factor = widen_factor self.num_classes = num_classes self.output_size = 64 self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor, 256 * self.widen_factor] self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False) self.bn_1 = nn.BatchNorm2d(64) self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1) self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2) self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2) self.classifier = nn.Linear(1024, num_classes) self.stage_att = self.block('stage_att', self.stages[2], self. stages[3], 1) self.bn_att = nn.BatchNorm2d(self.stages[3]) self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size= 1, padding=0, bias=False) self.bn_att2 = nn.BatchNorm2d(num_classes) self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1, padding=0, bias=False) self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1, bias=False) self.bn_att3 = nn.BatchNorm2d(1) self.att_gap = nn.AvgPool2d(16) self.sigmoid = nn.Sigmoid() self.relu = nn.ReLU(inplace=True) init.kaiming_normal(self.classifier.weight) for key in self.state_dict(): if key.split('.')[-1] == 'weight': if 'conv' in key: init.kaiming_normal(self.state_dict()[key], mode='fan_out') if 'bn' in key: self.state_dict()[key][...] = 1 elif key.split('.')[-1] == 'bias': self.state_dict()[key][...] = 0 def block(self, name, in_channels, out_channels, pool_stride=2): """ Stack n bottleneck modules where n is inferred from the depth of the network. Args: name: string name of the current block. in_channels: number of input channels out_channels: number of output channels pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block. Returns: a Module consisting of n sequential bottlenecks. """ block = nn.Sequential() for bottleneck in range(self.block_depth): name_ = '%s_bottleneck_%d' % (name, bottleneck) if bottleneck == 0: block.add_module(name_, ResNeXtBottleneck(in_channels, out_channels, pool_stride, self.cardinality, self. widen_factor)) else: block.add_module(name_, ResNeXtBottleneck(out_channels, out_channels, 1, self.cardinality, self.widen_factor)) return block def forward(self, x): x = self.conv_1_3x3.forward(x) x = F.relu(self.bn_1.forward(x), inplace=True) x = self.stage_1.forward(x) x = self.stage_2.forward(x) ax = self.stage_att(x) ax = self.relu(self.bn_att2(self.att_conv(ax))) bs, cs, ys, xs = ax.shape self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax))) ax = self.att_conv2(ax) ax = self.att_gap(ax) ax = ax.view(ax.size(0), -1) rx = x * self.att rx = rx + x rx = self.stage_3.forward(rx) rx = F.avg_pool2d(rx, 8, 1) rx = rx.view(-1, 1024) rx = self.classifier(rx) return ax, rx, self.att def resnext(**kwargs): """Constructs a ResNeXt. """ model = CifarResNeXt(**kwargs) return model <|reserved_special_token_1|> """ Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py """ import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init __all__ = ['resnext'] class ResNeXtBottleneck(nn.Module): """ RexNeXt bottleneck type C (https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua) """ def __init__(self, in_channels, out_channels, stride, cardinality, widen_factor): """ Constructor Args: in_channels: input channel dimensionality out_channels: output channel dimensionality stride: conv stride. Replaces pooling layer. cardinality: num of convolution groups. widen_factor: factor to reduce the input dimensionality before convolution. """ super(ResNeXtBottleneck, self).__init__() D = cardinality * out_channels // widen_factor self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False) self.bn_reduce = nn.BatchNorm2d(D) self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False) self.bn = nn.BatchNorm2d(D) self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride=1, padding=0, bias=False) self.bn_expand = nn.BatchNorm2d(out_channels) self.shortcut = nn.Sequential() if in_channels != out_channels: self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0, bias=False)) self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d(out_channels)) def forward(self, x): bottleneck = self.conv_reduce.forward(x) bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True) bottleneck = self.conv_conv.forward(bottleneck) bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True) bottleneck = self.conv_expand.forward(bottleneck) bottleneck = self.bn_expand.forward(bottleneck) residual = self.shortcut.forward(x) return F.relu(residual + bottleneck, inplace=True) class CifarResNeXt(nn.Module): """ ResNext optimized for the Cifar dataset, as specified in https://arxiv.org/pdf/1611.05431.pdf """ def __init__(self, cardinality, depth, num_classes, widen_factor=4, dropRate=0): """ Constructor Args: cardinality: number of convolution groups. depth: number of layers. num_classes: number of classes widen_factor: factor to adjust the channel dimensionality """ super(CifarResNeXt, self).__init__() self.cardinality = cardinality self.depth = depth self.block_depth = (self.depth - 2) // 9 self.widen_factor = widen_factor self.num_classes = num_classes self.output_size = 64 self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor, 256 * self.widen_factor] self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False) self.bn_1 = nn.BatchNorm2d(64) self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1) self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2) self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2) self.classifier = nn.Linear(1024, num_classes) self.stage_att = self.block('stage_att', self.stages[2], self.stages[3], 1) self.bn_att = nn.BatchNorm2d(self.stages[3]) self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size=1, padding=0, bias=False) self.bn_att2 = nn.BatchNorm2d(num_classes) self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1, padding=0, bias=False) self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1, bias=False) self.bn_att3 = nn.BatchNorm2d(1) self.att_gap = nn.AvgPool2d(16) self.sigmoid = nn.Sigmoid() self.relu = nn.ReLU(inplace=True) init.kaiming_normal(self.classifier.weight) for key in self.state_dict(): if key.split('.')[-1] == 'weight': if 'conv' in key: init.kaiming_normal(self.state_dict()[key], mode='fan_out') if 'bn' in key: self.state_dict()[key][...] = 1 elif key.split('.')[-1] == 'bias': self.state_dict()[key][...] = 0 def block(self, name, in_channels, out_channels, pool_stride=2): """ Stack n bottleneck modules where n is inferred from the depth of the network. Args: name: string name of the current block. in_channels: number of input channels out_channels: number of output channels pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block. Returns: a Module consisting of n sequential bottlenecks. """ block = nn.Sequential() for bottleneck in range(self.block_depth): name_ = '%s_bottleneck_%d' % (name, bottleneck) if bottleneck == 0: block.add_module(name_, ResNeXtBottleneck(in_channels, out_channels, pool_stride, self.cardinality, self.widen_factor)) else: block.add_module(name_, ResNeXtBottleneck(out_channels, out_channels, 1, self.cardinality, self.widen_factor)) return block def forward(self, x): x = self.conv_1_3x3.forward(x) x = F.relu(self.bn_1.forward(x), inplace=True) x = self.stage_1.forward(x) x = self.stage_2.forward(x) ax = self.stage_att(x) ax = self.relu(self.bn_att2(self.att_conv(ax))) bs, cs, ys, xs = ax.shape self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax))) # self.att = self.att.view(bs, 1, ys, xs) ax = self.att_conv2(ax) ax = self.att_gap(ax) ax = ax.view(ax.size(0), -1) rx = x * self.att rx = rx + x rx = self.stage_3.forward(rx) rx = F.avg_pool2d(rx, 8, 1) rx = rx.view(-1, 1024) rx = self.classifier(rx) return ax, rx, self.att def resnext(**kwargs): """Constructs a ResNeXt. """ model = CifarResNeXt(**kwargs) return model # """ # resneXt for cifar with pytorch # Reference: # [1] S. Xie, G. Ross, P. Dollar, Z. Tu and K. He Aggregated residual transformations for deep neural networks. In CVPR, 2017 # """ # # import torch # import torch.nn as nn # import math # # # class Bottleneck(nn.Module): # expansion = 4 # # def __init__(self, inplanes, planes, cardinality, baseWidth, stride=1, downsample=None): # super(Bottleneck, self).__init__() # D = int(planes * (baseWidth / 64.)) # C = cardinality # self.conv1 = nn.Conv2d(inplanes, D * C, kernel_size=1, bias=False) # self.bn1 = nn.BatchNorm2d(D * C) # self.conv2 = nn.Conv2d(D * C, D * C, kernel_size=3, stride=stride, padding=1, groups=C, bias=False) # self.bn2 = nn.BatchNorm2d(D * C) # self.conv3 = nn.Conv2d(D * C, planes * 4, kernel_size=1, bias=False) # self.bn3 = nn.BatchNorm2d(planes * 4) # self.relu = nn.ReLU(inplace=True) # self.downsample = downsample # self.stride = stride # # def forward(self, x): # residual = x # # out = self.conv1(x) # out = self.bn1(out) # out = self.relu(out) # # out = self.conv2(out) # out = self.bn2(out) # out = self.relu(out) # # out = self.conv3(out) # out = self.bn3(out) # # if self.downsample is not None: # residual = self.downsample(x) # # if residual.size() != out.size(): # print(out.size(), residual.size()) # out += residual # out = self.relu(out) # # return out # # # class ResNeXt_Cifar(nn.Module): # # def __init__(self, block, layers, cardinality, baseWidth, num_classes=10): # super(ResNeXt_Cifar, self).__init__() # self.inplanes = 64 # self.cardinality = cardinality # self.baseWidth = baseWidth # self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) # self.bn1 = nn.BatchNorm2d(64) # self.relu = nn.ReLU(inplace=True) # self.layer1 = self._make_layer(block, 64, layers[0]) # self.layer2 = self._make_layer(block, 128, layers[1], stride=2) # self.layer3 = self._make_layer(block, 256, layers[2], stride=2) # self.avgpool = nn.AvgPool2d(8, stride=1) # self.fc = nn.Linear(256 * block.expansion, num_classes) # # for m in self.modules(): # if isinstance(m, nn.Conv2d): # n = m.kernel_size[0] * m.kernel_size[1] * 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 _make_layer(self, block, planes, blocks, stride=1): # downsample = None # if stride != 1 or self.inplanes != planes * block.expansion: # downsample = nn.Sequential( # nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), # nn.BatchNorm2d(planes * block.expansion) # ) # # layers = [] # layers.append(block(self.inplanes, planes, self.cardinality, self.baseWidth, stride, downsample)) # self.inplanes = planes * block.expansion # for _ in range(1, blocks): # layers.append(block(self.inplanes, planes, self.cardinality, self.baseWidth)) # # return nn.Sequential(*layers) # # def forward(self, x): # x = self.conv1(x) # x = self.bn1(x) # x = self.relu(x) # # x = self.layer1(x) # x = self.layer2(x) # x = self.layer3(x) # # x = self.avgpool(x) # x = x.view(x.size(0), -1) # x = self.fc(x) # # return x # # # def resneXt_cifar(depth, cardinality, baseWidth, **kwargs): # assert (depth - 2) % 9 == 0 # n = int((depth - 2) / 9) # model = ResNeXt_Cifar(Bottleneck, [n, n, n], cardinality, baseWidth, **kwargs) # return model # if __name__ == '__main__': # net = resneXt_cifar(29, 16, 64) # y = net(torch.randn(1, 3, 32, 32)) # print(net) # print(y.size())
flexible
{ "blob_id": "50ed1512b0e6ff8e01f5d4aa034406fa78850176", "index": 2293, "step-1": "<mask token>\n\n\nclass CifarResNeXt(nn.Module):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass ResNeXtBottleneck(nn.Module):\n <mask token>\n\n def __init__(self, in_channels, out_channels, stride, cardinality,\n widen_factor):\n \"\"\" Constructor\n Args:\n in_channels: input channel dimensionality\n out_channels: output channel dimensionality\n stride: conv stride. Replaces pooling layer.\n cardinality: num of convolution groups.\n widen_factor: factor to reduce the input dimensionality before convolution.\n \"\"\"\n super(ResNeXtBottleneck, self).__init__()\n D = cardinality * out_channels // widen_factor\n self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=\n 1, padding=0, bias=False)\n self.bn_reduce = nn.BatchNorm2d(D)\n self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride,\n padding=1, groups=cardinality, bias=False)\n self.bn = nn.BatchNorm2d(D)\n self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride\n =1, padding=0, bias=False)\n self.bn_expand = nn.BatchNorm2d(out_channels)\n self.shortcut = nn.Sequential()\n if in_channels != out_channels:\n self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels,\n out_channels, kernel_size=1, stride=stride, padding=0, bias\n =False))\n self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d(\n out_channels))\n\n def forward(self, x):\n bottleneck = self.conv_reduce.forward(x)\n bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True)\n bottleneck = self.conv_conv.forward(bottleneck)\n bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True)\n bottleneck = self.conv_expand.forward(bottleneck)\n bottleneck = self.bn_expand.forward(bottleneck)\n residual = self.shortcut.forward(x)\n return F.relu(residual + bottleneck, inplace=True)\n\n\nclass CifarResNeXt(nn.Module):\n \"\"\"\n ResNext optimized for the Cifar dataset, as specified in\n https://arxiv.org/pdf/1611.05431.pdf\n \"\"\"\n\n def __init__(self, cardinality, depth, num_classes, widen_factor=4,\n dropRate=0):\n \"\"\" Constructor\n Args:\n cardinality: number of convolution groups.\n depth: number of layers.\n num_classes: number of classes\n widen_factor: factor to adjust the channel dimensionality\n \"\"\"\n super(CifarResNeXt, self).__init__()\n self.cardinality = cardinality\n self.depth = depth\n self.block_depth = (self.depth - 2) // 9\n self.widen_factor = widen_factor\n self.num_classes = num_classes\n self.output_size = 64\n self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor,\n 256 * self.widen_factor]\n self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)\n self.bn_1 = nn.BatchNorm2d(64)\n self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1)\n self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2)\n self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2)\n self.classifier = nn.Linear(1024, num_classes)\n self.stage_att = self.block('stage_att', self.stages[2], self.\n stages[3], 1)\n self.bn_att = nn.BatchNorm2d(self.stages[3])\n self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size=\n 1, padding=0, bias=False)\n self.bn_att2 = nn.BatchNorm2d(num_classes)\n self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1,\n padding=0, bias=False)\n self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1,\n bias=False)\n self.bn_att3 = nn.BatchNorm2d(1)\n self.att_gap = nn.AvgPool2d(16)\n self.sigmoid = nn.Sigmoid()\n self.relu = nn.ReLU(inplace=True)\n init.kaiming_normal(self.classifier.weight)\n for key in self.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key:\n init.kaiming_normal(self.state_dict()[key], mode='fan_out')\n if 'bn' in key:\n self.state_dict()[key][...] = 1\n elif key.split('.')[-1] == 'bias':\n self.state_dict()[key][...] = 0\n\n def block(self, name, in_channels, out_channels, pool_stride=2):\n \"\"\" Stack n bottleneck modules where n is inferred from the depth of the network.\n Args:\n name: string name of the current block.\n in_channels: number of input channels\n out_channels: number of output channels\n pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block.\n Returns: a Module consisting of n sequential bottlenecks.\n \"\"\"\n block = nn.Sequential()\n for bottleneck in range(self.block_depth):\n name_ = '%s_bottleneck_%d' % (name, bottleneck)\n if bottleneck == 0:\n block.add_module(name_, ResNeXtBottleneck(in_channels,\n out_channels, pool_stride, self.cardinality, self.\n widen_factor))\n else:\n block.add_module(name_, ResNeXtBottleneck(out_channels,\n out_channels, 1, self.cardinality, self.widen_factor))\n return block\n\n def forward(self, x):\n x = self.conv_1_3x3.forward(x)\n x = F.relu(self.bn_1.forward(x), inplace=True)\n x = self.stage_1.forward(x)\n x = self.stage_2.forward(x)\n ax = self.stage_att(x)\n ax = self.relu(self.bn_att2(self.att_conv(ax)))\n bs, cs, ys, xs = ax.shape\n self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax)))\n ax = self.att_conv2(ax)\n ax = self.att_gap(ax)\n ax = ax.view(ax.size(0), -1)\n rx = x * self.att\n rx = rx + x\n rx = self.stage_3.forward(rx)\n rx = F.avg_pool2d(rx, 8, 1)\n rx = rx.view(-1, 1024)\n rx = self.classifier(rx)\n return ax, rx, self.att\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass ResNeXtBottleneck(nn.Module):\n \"\"\"\n RexNeXt bottleneck type C (https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua)\n \"\"\"\n\n def __init__(self, in_channels, out_channels, stride, cardinality,\n widen_factor):\n \"\"\" Constructor\n Args:\n in_channels: input channel dimensionality\n out_channels: output channel dimensionality\n stride: conv stride. Replaces pooling layer.\n cardinality: num of convolution groups.\n widen_factor: factor to reduce the input dimensionality before convolution.\n \"\"\"\n super(ResNeXtBottleneck, self).__init__()\n D = cardinality * out_channels // widen_factor\n self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=\n 1, padding=0, bias=False)\n self.bn_reduce = nn.BatchNorm2d(D)\n self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride,\n padding=1, groups=cardinality, bias=False)\n self.bn = nn.BatchNorm2d(D)\n self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride\n =1, padding=0, bias=False)\n self.bn_expand = nn.BatchNorm2d(out_channels)\n self.shortcut = nn.Sequential()\n if in_channels != out_channels:\n self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels,\n out_channels, kernel_size=1, stride=stride, padding=0, bias\n =False))\n self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d(\n out_channels))\n\n def forward(self, x):\n bottleneck = self.conv_reduce.forward(x)\n bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True)\n bottleneck = self.conv_conv.forward(bottleneck)\n bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True)\n bottleneck = self.conv_expand.forward(bottleneck)\n bottleneck = self.bn_expand.forward(bottleneck)\n residual = self.shortcut.forward(x)\n return F.relu(residual + bottleneck, inplace=True)\n\n\nclass CifarResNeXt(nn.Module):\n \"\"\"\n ResNext optimized for the Cifar dataset, as specified in\n https://arxiv.org/pdf/1611.05431.pdf\n \"\"\"\n\n def __init__(self, cardinality, depth, num_classes, widen_factor=4,\n dropRate=0):\n \"\"\" Constructor\n Args:\n cardinality: number of convolution groups.\n depth: number of layers.\n num_classes: number of classes\n widen_factor: factor to adjust the channel dimensionality\n \"\"\"\n super(CifarResNeXt, self).__init__()\n self.cardinality = cardinality\n self.depth = depth\n self.block_depth = (self.depth - 2) // 9\n self.widen_factor = widen_factor\n self.num_classes = num_classes\n self.output_size = 64\n self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor,\n 256 * self.widen_factor]\n self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)\n self.bn_1 = nn.BatchNorm2d(64)\n self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1)\n self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2)\n self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2)\n self.classifier = nn.Linear(1024, num_classes)\n self.stage_att = self.block('stage_att', self.stages[2], self.\n stages[3], 1)\n self.bn_att = nn.BatchNorm2d(self.stages[3])\n self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size=\n 1, padding=0, bias=False)\n self.bn_att2 = nn.BatchNorm2d(num_classes)\n self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1,\n padding=0, bias=False)\n self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1,\n bias=False)\n self.bn_att3 = nn.BatchNorm2d(1)\n self.att_gap = nn.AvgPool2d(16)\n self.sigmoid = nn.Sigmoid()\n self.relu = nn.ReLU(inplace=True)\n init.kaiming_normal(self.classifier.weight)\n for key in self.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key:\n init.kaiming_normal(self.state_dict()[key], mode='fan_out')\n if 'bn' in key:\n self.state_dict()[key][...] = 1\n elif key.split('.')[-1] == 'bias':\n self.state_dict()[key][...] = 0\n\n def block(self, name, in_channels, out_channels, pool_stride=2):\n \"\"\" Stack n bottleneck modules where n is inferred from the depth of the network.\n Args:\n name: string name of the current block.\n in_channels: number of input channels\n out_channels: number of output channels\n pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block.\n Returns: a Module consisting of n sequential bottlenecks.\n \"\"\"\n block = nn.Sequential()\n for bottleneck in range(self.block_depth):\n name_ = '%s_bottleneck_%d' % (name, bottleneck)\n if bottleneck == 0:\n block.add_module(name_, ResNeXtBottleneck(in_channels,\n out_channels, pool_stride, self.cardinality, self.\n widen_factor))\n else:\n block.add_module(name_, ResNeXtBottleneck(out_channels,\n out_channels, 1, self.cardinality, self.widen_factor))\n return block\n\n def forward(self, x):\n x = self.conv_1_3x3.forward(x)\n x = F.relu(self.bn_1.forward(x), inplace=True)\n x = self.stage_1.forward(x)\n x = self.stage_2.forward(x)\n ax = self.stage_att(x)\n ax = self.relu(self.bn_att2(self.att_conv(ax)))\n bs, cs, ys, xs = ax.shape\n self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax)))\n ax = self.att_conv2(ax)\n ax = self.att_gap(ax)\n ax = ax.view(ax.size(0), -1)\n rx = x * self.att\n rx = rx + x\n rx = self.stage_3.forward(rx)\n rx = F.avg_pool2d(rx, 8, 1)\n rx = rx.view(-1, 1024)\n rx = self.classifier(rx)\n return ax, rx, self.att\n\n\ndef resnext(**kwargs):\n \"\"\"Constructs a ResNeXt.\n \"\"\"\n model = CifarResNeXt(**kwargs)\n return model\n", "step-4": "<mask token>\n__all__ = ['resnext']\n\n\nclass ResNeXtBottleneck(nn.Module):\n \"\"\"\n RexNeXt bottleneck type C (https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua)\n \"\"\"\n\n def __init__(self, in_channels, out_channels, stride, cardinality,\n widen_factor):\n \"\"\" Constructor\n Args:\n in_channels: input channel dimensionality\n out_channels: output channel dimensionality\n stride: conv stride. Replaces pooling layer.\n cardinality: num of convolution groups.\n widen_factor: factor to reduce the input dimensionality before convolution.\n \"\"\"\n super(ResNeXtBottleneck, self).__init__()\n D = cardinality * out_channels // widen_factor\n self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=\n 1, padding=0, bias=False)\n self.bn_reduce = nn.BatchNorm2d(D)\n self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride,\n padding=1, groups=cardinality, bias=False)\n self.bn = nn.BatchNorm2d(D)\n self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride\n =1, padding=0, bias=False)\n self.bn_expand = nn.BatchNorm2d(out_channels)\n self.shortcut = nn.Sequential()\n if in_channels != out_channels:\n self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels,\n out_channels, kernel_size=1, stride=stride, padding=0, bias\n =False))\n self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d(\n out_channels))\n\n def forward(self, x):\n bottleneck = self.conv_reduce.forward(x)\n bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True)\n bottleneck = self.conv_conv.forward(bottleneck)\n bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True)\n bottleneck = self.conv_expand.forward(bottleneck)\n bottleneck = self.bn_expand.forward(bottleneck)\n residual = self.shortcut.forward(x)\n return F.relu(residual + bottleneck, inplace=True)\n\n\nclass CifarResNeXt(nn.Module):\n \"\"\"\n ResNext optimized for the Cifar dataset, as specified in\n https://arxiv.org/pdf/1611.05431.pdf\n \"\"\"\n\n def __init__(self, cardinality, depth, num_classes, widen_factor=4,\n dropRate=0):\n \"\"\" Constructor\n Args:\n cardinality: number of convolution groups.\n depth: number of layers.\n num_classes: number of classes\n widen_factor: factor to adjust the channel dimensionality\n \"\"\"\n super(CifarResNeXt, self).__init__()\n self.cardinality = cardinality\n self.depth = depth\n self.block_depth = (self.depth - 2) // 9\n self.widen_factor = widen_factor\n self.num_classes = num_classes\n self.output_size = 64\n self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor,\n 256 * self.widen_factor]\n self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)\n self.bn_1 = nn.BatchNorm2d(64)\n self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1)\n self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2)\n self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2)\n self.classifier = nn.Linear(1024, num_classes)\n self.stage_att = self.block('stage_att', self.stages[2], self.\n stages[3], 1)\n self.bn_att = nn.BatchNorm2d(self.stages[3])\n self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size=\n 1, padding=0, bias=False)\n self.bn_att2 = nn.BatchNorm2d(num_classes)\n self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1,\n padding=0, bias=False)\n self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1,\n bias=False)\n self.bn_att3 = nn.BatchNorm2d(1)\n self.att_gap = nn.AvgPool2d(16)\n self.sigmoid = nn.Sigmoid()\n self.relu = nn.ReLU(inplace=True)\n init.kaiming_normal(self.classifier.weight)\n for key in self.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key:\n init.kaiming_normal(self.state_dict()[key], mode='fan_out')\n if 'bn' in key:\n self.state_dict()[key][...] = 1\n elif key.split('.')[-1] == 'bias':\n self.state_dict()[key][...] = 0\n\n def block(self, name, in_channels, out_channels, pool_stride=2):\n \"\"\" Stack n bottleneck modules where n is inferred from the depth of the network.\n Args:\n name: string name of the current block.\n in_channels: number of input channels\n out_channels: number of output channels\n pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block.\n Returns: a Module consisting of n sequential bottlenecks.\n \"\"\"\n block = nn.Sequential()\n for bottleneck in range(self.block_depth):\n name_ = '%s_bottleneck_%d' % (name, bottleneck)\n if bottleneck == 0:\n block.add_module(name_, ResNeXtBottleneck(in_channels,\n out_channels, pool_stride, self.cardinality, self.\n widen_factor))\n else:\n block.add_module(name_, ResNeXtBottleneck(out_channels,\n out_channels, 1, self.cardinality, self.widen_factor))\n return block\n\n def forward(self, x):\n x = self.conv_1_3x3.forward(x)\n x = F.relu(self.bn_1.forward(x), inplace=True)\n x = self.stage_1.forward(x)\n x = self.stage_2.forward(x)\n ax = self.stage_att(x)\n ax = self.relu(self.bn_att2(self.att_conv(ax)))\n bs, cs, ys, xs = ax.shape\n self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax)))\n ax = self.att_conv2(ax)\n ax = self.att_gap(ax)\n ax = ax.view(ax.size(0), -1)\n rx = x * self.att\n rx = rx + x\n rx = self.stage_3.forward(rx)\n rx = F.avg_pool2d(rx, 8, 1)\n rx = rx.view(-1, 1024)\n rx = self.classifier(rx)\n return ax, rx, self.att\n\n\ndef resnext(**kwargs):\n \"\"\"Constructs a ResNeXt.\n \"\"\"\n model = CifarResNeXt(**kwargs)\n return model\n", "step-5": "\n\"\"\"\nCreates a ResNeXt Model as defined in:\nXie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016).\nAggregated residual transformations for deep neural networks.\narXiv preprint arXiv:1611.05431.\nimport from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import init\n\n__all__ = ['resnext']\n\nclass ResNeXtBottleneck(nn.Module):\n \"\"\"\n RexNeXt bottleneck type C (https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua)\n \"\"\"\n def __init__(self, in_channels, out_channels, stride, cardinality, widen_factor):\n \"\"\" Constructor\n Args:\n in_channels: input channel dimensionality\n out_channels: output channel dimensionality\n stride: conv stride. Replaces pooling layer.\n cardinality: num of convolution groups.\n widen_factor: factor to reduce the input dimensionality before convolution.\n \"\"\"\n super(ResNeXtBottleneck, self).__init__()\n D = cardinality * out_channels // widen_factor\n self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False)\n self.bn_reduce = nn.BatchNorm2d(D)\n self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False)\n self.bn = nn.BatchNorm2d(D)\n self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\n self.bn_expand = nn.BatchNorm2d(out_channels)\n\n self.shortcut = nn.Sequential()\n if in_channels != out_channels:\n self.shortcut.add_module('shortcut_conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0, bias=False))\n self.shortcut.add_module('shortcut_bn', nn.BatchNorm2d(out_channels))\n\n def forward(self, x):\n bottleneck = self.conv_reduce.forward(x)\n bottleneck = F.relu(self.bn_reduce.forward(bottleneck), inplace=True)\n bottleneck = self.conv_conv.forward(bottleneck)\n bottleneck = F.relu(self.bn.forward(bottleneck), inplace=True)\n bottleneck = self.conv_expand.forward(bottleneck)\n bottleneck = self.bn_expand.forward(bottleneck)\n residual = self.shortcut.forward(x)\n return F.relu(residual + bottleneck, inplace=True)\n\n\nclass CifarResNeXt(nn.Module):\n \"\"\"\n ResNext optimized for the Cifar dataset, as specified in\n https://arxiv.org/pdf/1611.05431.pdf\n \"\"\"\n def __init__(self, cardinality, depth, num_classes, widen_factor=4, dropRate=0):\n \"\"\" Constructor\n Args:\n cardinality: number of convolution groups.\n depth: number of layers.\n num_classes: number of classes\n widen_factor: factor to adjust the channel dimensionality\n \"\"\"\n super(CifarResNeXt, self).__init__()\n self.cardinality = cardinality\n self.depth = depth\n self.block_depth = (self.depth - 2) // 9\n self.widen_factor = widen_factor\n self.num_classes = num_classes\n self.output_size = 64\n self.stages = [64, 64 * self.widen_factor, 128 * self.widen_factor, 256 * self.widen_factor]\n\n self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)\n self.bn_1 = nn.BatchNorm2d(64)\n self.stage_1 = self.block('stage_1', self.stages[0], self.stages[1], 1)\n self.stage_2 = self.block('stage_2', self.stages[1], self.stages[2], 2)\n self.stage_3 = self.block('stage_3', self.stages[2], self.stages[3], 2)\n self.classifier = nn.Linear(1024, num_classes)\n\n self.stage_att = self.block('stage_att', self.stages[2], self.stages[3], 1)\n self.bn_att = nn.BatchNorm2d(self.stages[3])\n self.att_conv = nn.Conv2d(self.stages[3], num_classes, kernel_size=1, padding=0,\n bias=False)\n self.bn_att2 = nn.BatchNorm2d(num_classes)\n self.att_conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1, padding=0,\n bias=False)\n self.att_conv3 = nn.Conv2d(num_classes, 1, kernel_size=3, padding=1,\n bias=False)\n self.bn_att3 = nn.BatchNorm2d(1)\n self.att_gap = nn.AvgPool2d(16)\n self.sigmoid = nn.Sigmoid()\n self.relu = nn.ReLU(inplace=True)\n\n init.kaiming_normal(self.classifier.weight)\n\n for key in self.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key:\n init.kaiming_normal(self.state_dict()[key], mode='fan_out')\n if 'bn' in key:\n self.state_dict()[key][...] = 1\n elif key.split('.')[-1] == 'bias':\n self.state_dict()[key][...] = 0\n\n def block(self, name, in_channels, out_channels, pool_stride=2):\n \"\"\" Stack n bottleneck modules where n is inferred from the depth of the network.\n Args:\n name: string name of the current block.\n in_channels: number of input channels\n out_channels: number of output channels\n pool_stride: factor to reduce the spatial dimensionality in the first bottleneck of the block.\n Returns: a Module consisting of n sequential bottlenecks.\n \"\"\"\n block = nn.Sequential()\n for bottleneck in range(self.block_depth):\n name_ = '%s_bottleneck_%d' % (name, bottleneck)\n if bottleneck == 0:\n block.add_module(name_, ResNeXtBottleneck(in_channels, out_channels, pool_stride, self.cardinality,\n self.widen_factor))\n else:\n block.add_module(name_,\n ResNeXtBottleneck(out_channels, out_channels, 1, self.cardinality, self.widen_factor))\n return block\n\n def forward(self, x):\n x = self.conv_1_3x3.forward(x)\n x = F.relu(self.bn_1.forward(x), inplace=True)\n x = self.stage_1.forward(x)\n x = self.stage_2.forward(x)\n\n ax = self.stage_att(x)\n ax = self.relu(self.bn_att2(self.att_conv(ax)))\n bs, cs, ys, xs = ax.shape\n self.att = self.sigmoid(self.bn_att3(self.att_conv3(ax)))\n # self.att = self.att.view(bs, 1, ys, xs)\n ax = self.att_conv2(ax)\n ax = self.att_gap(ax)\n ax = ax.view(ax.size(0), -1)\n\n rx = x * self.att\n rx = rx + x\n rx = self.stage_3.forward(rx)\n rx = F.avg_pool2d(rx, 8, 1)\n rx = rx.view(-1, 1024)\n rx = self.classifier(rx)\n\n return ax, rx, self.att\n\ndef resnext(**kwargs):\n \"\"\"Constructs a ResNeXt.\n \"\"\"\n model = CifarResNeXt(**kwargs)\n return model\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# \"\"\"\n# resneXt for cifar with pytorch\n# Reference:\n# [1] S. Xie, G. Ross, P. Dollar, Z. Tu and K. He Aggregated residual transformations for deep neural networks. In CVPR, 2017\n# \"\"\"\n#\n# import torch\n# import torch.nn as nn\n# import math\n#\n#\n# class Bottleneck(nn.Module):\n# expansion = 4\n#\n# def __init__(self, inplanes, planes, cardinality, baseWidth, stride=1, downsample=None):\n# super(Bottleneck, self).__init__()\n# D = int(planes * (baseWidth / 64.))\n# C = cardinality\n# self.conv1 = nn.Conv2d(inplanes, D * C, kernel_size=1, bias=False)\n# self.bn1 = nn.BatchNorm2d(D * C)\n# self.conv2 = nn.Conv2d(D * C, D * C, kernel_size=3, stride=stride, padding=1, groups=C, bias=False)\n# self.bn2 = nn.BatchNorm2d(D * C)\n# self.conv3 = nn.Conv2d(D * C, planes * 4, kernel_size=1, bias=False)\n# self.bn3 = nn.BatchNorm2d(planes * 4)\n# self.relu = nn.ReLU(inplace=True)\n# self.downsample = downsample\n# self.stride = stride\n#\n# def forward(self, x):\n# residual = x\n#\n# out = self.conv1(x)\n# out = self.bn1(out)\n# out = self.relu(out)\n#\n# out = self.conv2(out)\n# out = self.bn2(out)\n# out = self.relu(out)\n#\n# out = self.conv3(out)\n# out = self.bn3(out)\n#\n# if self.downsample is not None:\n# residual = self.downsample(x)\n#\n# if residual.size() != out.size():\n# print(out.size(), residual.size())\n# out += residual\n# out = self.relu(out)\n#\n# return out\n#\n#\n# class ResNeXt_Cifar(nn.Module):\n#\n# def __init__(self, block, layers, cardinality, baseWidth, num_classes=10):\n# super(ResNeXt_Cifar, self).__init__()\n# self.inplanes = 64\n# self.cardinality = cardinality\n# self.baseWidth = baseWidth\n# self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n# self.bn1 = nn.BatchNorm2d(64)\n# self.relu = nn.ReLU(inplace=True)\n# self.layer1 = self._make_layer(block, 64, layers[0])\n# self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n# self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n# self.avgpool = nn.AvgPool2d(8, stride=1)\n# self.fc = nn.Linear(256 * block.expansion, num_classes)\n#\n# for m in self.modules():\n# if isinstance(m, nn.Conv2d):\n# n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n# m.weight.data.normal_(0, math.sqrt(2. / n))\n# elif isinstance(m, nn.BatchNorm2d):\n# m.weight.data.fill_(1)\n# m.bias.data.zero_()\n#\n# def _make_layer(self, block, planes, blocks, stride=1):\n# downsample = None\n# if stride != 1 or self.inplanes != planes * block.expansion:\n# downsample = nn.Sequential(\n# nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),\n# nn.BatchNorm2d(planes * block.expansion)\n# )\n#\n# layers = []\n# layers.append(block(self.inplanes, planes, self.cardinality, self.baseWidth, stride, downsample))\n# self.inplanes = planes * block.expansion\n# for _ in range(1, blocks):\n# layers.append(block(self.inplanes, planes, self.cardinality, self.baseWidth))\n#\n# return nn.Sequential(*layers)\n#\n# def forward(self, x):\n# x = self.conv1(x)\n# x = self.bn1(x)\n# x = self.relu(x)\n#\n# x = self.layer1(x)\n# x = self.layer2(x)\n# x = self.layer3(x)\n#\n# x = self.avgpool(x)\n# x = x.view(x.size(0), -1)\n# x = self.fc(x)\n#\n# return x\n#\n#\n# def resneXt_cifar(depth, cardinality, baseWidth, **kwargs):\n# assert (depth - 2) % 9 == 0\n# n = int((depth - 2) / 9)\n# model = ResNeXt_Cifar(Bottleneck, [n, n, n], cardinality, baseWidth, **kwargs)\n# return model\n\n\n# if __name__ == '__main__':\n# net = resneXt_cifar(29, 16, 64)\n# y = net(torch.randn(1, 3, 32, 32))\n# print(net)\n# print(y.size())", "step-ids": [ 1, 8, 10, 11, 13 ] }
[ 1, 8, 10, 11, 13 ]
<|reserved_special_token_0|> class GameBoard: <|reserved_special_token_0|> <|reserved_special_token_0|> def draw(self): self.playerSprites.draw() self.groundSprites.draw() <|reserved_special_token_0|> <|reserved_special_token_0|> def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int): if not self.canMoveGamePiece(gamePiece, xTo, yTo): return False for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: self.blocks[y + gamePiece.y][x + gamePiece.x] = None for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: blockXDiff = block.x - gamePiece.x blockYDiff = block.y - gamePiece.y newBlockX = xTo + blockXDiff newBlockY = yTo + blockYDiff self.blocks[newBlockY][newBlockX] = block block.moveTo(newBlockX, newBlockY) gamePiece.x = xTo gamePiece.y = yTo <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def removeBlock(self, aBlock: gp.Block): """ remove a block from the game board """ for y, row in iter(self.blocks): for x, block in iter(row): if block is aBlock: self.blocks[y][x] = None self.playerSprites.remove(aBlock.sprite) return class GameManager: def __init__(self) ->None: pass def start(self): gameBoard = GameBoard(10, 20) gameBoard.addGamePiece() <|reserved_special_token_1|> <|reserved_special_token_0|> class GameBoard: <|reserved_special_token_0|> def __init__(self, width: int, height: int): self.width = width self.height = height self.blocks = [[None for y in range(width)] for x in range(height)] self.playerSprites = SpriteList() self.groundSprites = SpriteList() def draw(self): self.playerSprites.draw() self.groundSprites.draw() def canMoveBlock(self, x: int, y: int) ->bool: return self.blocks[x][y] is None <|reserved_special_token_0|> def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int): if not self.canMoveGamePiece(gamePiece, xTo, yTo): return False for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: self.blocks[y + gamePiece.y][x + gamePiece.x] = None for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: blockXDiff = block.x - gamePiece.x blockYDiff = block.y - gamePiece.y newBlockX = xTo + blockXDiff newBlockY = yTo + blockYDiff self.blocks[newBlockY][newBlockX] = block block.moveTo(newBlockX, newBlockY) gamePiece.x = xTo gamePiece.y = yTo def addBlock(self, aBlock: gp.Block): """adds a block to the game board""" if self.blocks[aBlock.y][aBlock.x] != None: raise MovementError('game board space not empty') self.blocks[aBlock.y][aBlock.x] = aBlock self.groundSprites.append(aBlock.sprite) def addGamePiece(self, gamePiece: gp.GamePiece): for y in range(gamePiece.size): for x in range(gamePiece.size): block = gamePiece.blocks[y][x] if block is None: continue self.blocks[block.y][block.x] = block self.playerSprites.append(block.sprite) def moveBlock(self, aBlock: gp.Block, x: int, y: int): self.blocks[aBlock.y][aBlock.x] = None self.blocks[y][x] = aBlock def removeBlock(self, aBlock: gp.Block): """ remove a block from the game board """ for y, row in iter(self.blocks): for x, block in iter(row): if block is aBlock: self.blocks[y][x] = None self.playerSprites.remove(aBlock.sprite) return class GameManager: def __init__(self) ->None: pass def start(self): gameBoard = GameBoard(10, 20) gameBoard.addGamePiece() <|reserved_special_token_1|> <|reserved_special_token_0|> class GameBoard: <|reserved_special_token_0|> def __init__(self, width: int, height: int): self.width = width self.height = height self.blocks = [[None for y in range(width)] for x in range(height)] self.playerSprites = SpriteList() self.groundSprites = SpriteList() def draw(self): self.playerSprites.draw() self.groundSprites.draw() def canMoveBlock(self, x: int, y: int) ->bool: return self.blocks[x][y] is None def canMoveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int ) ->bool: for yDiff, row in enumerate(gamePiece.blocks): for xDiff, block in enumerate(row): if block is None: continue newX = xTo + xDiff newY = yTo + yDiff if newX >= self.width or newX < 0: return False if newY < 0 or newY >= self.height: return False if self.blocks[newY][newX] is not None and self.blocks[newY][ newX] not in gamePiece.allBlocks(): return False return True def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int): if not self.canMoveGamePiece(gamePiece, xTo, yTo): return False for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: self.blocks[y + gamePiece.y][x + gamePiece.x] = None for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: blockXDiff = block.x - gamePiece.x blockYDiff = block.y - gamePiece.y newBlockX = xTo + blockXDiff newBlockY = yTo + blockYDiff self.blocks[newBlockY][newBlockX] = block block.moveTo(newBlockX, newBlockY) gamePiece.x = xTo gamePiece.y = yTo def addBlock(self, aBlock: gp.Block): """adds a block to the game board""" if self.blocks[aBlock.y][aBlock.x] != None: raise MovementError('game board space not empty') self.blocks[aBlock.y][aBlock.x] = aBlock self.groundSprites.append(aBlock.sprite) def addGamePiece(self, gamePiece: gp.GamePiece): for y in range(gamePiece.size): for x in range(gamePiece.size): block = gamePiece.blocks[y][x] if block is None: continue self.blocks[block.y][block.x] = block self.playerSprites.append(block.sprite) def moveBlock(self, aBlock: gp.Block, x: int, y: int): self.blocks[aBlock.y][aBlock.x] = None self.blocks[y][x] = aBlock def removeBlock(self, aBlock: gp.Block): """ remove a block from the game board """ for y, row in iter(self.blocks): for x, block in iter(row): if block is aBlock: self.blocks[y][x] = None self.playerSprites.remove(aBlock.sprite) return class GameManager: def __init__(self) ->None: pass def start(self): gameBoard = GameBoard(10, 20) gameBoard.addGamePiece() <|reserved_special_token_1|> from arcade.sprite_list.sprite_list import SpriteList import GamePiece as gp from Errors import * class GameConfig: WINDOW_TITLE = 'MyPyTris' SCREEN_WIDTH = 450 SCREEN_HEIGHT = 900 BLOCK_PX = 45 SPRITE_PX = 64 BLOCK_SCALE = BLOCK_PX / SPRITE_PX class GameBoard: """ Class to manage blocks on the game board """ def __init__(self, width: int, height: int): self.width = width self.height = height self.blocks = [[None for y in range(width)] for x in range(height)] self.playerSprites = SpriteList() self.groundSprites = SpriteList() def draw(self): self.playerSprites.draw() self.groundSprites.draw() def canMoveBlock(self, x: int, y: int) ->bool: return self.blocks[x][y] is None def canMoveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int ) ->bool: for yDiff, row in enumerate(gamePiece.blocks): for xDiff, block in enumerate(row): if block is None: continue newX = xTo + xDiff newY = yTo + yDiff if newX >= self.width or newX < 0: return False if newY < 0 or newY >= self.height: return False if self.blocks[newY][newX] is not None and self.blocks[newY][ newX] not in gamePiece.allBlocks(): return False return True def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int): if not self.canMoveGamePiece(gamePiece, xTo, yTo): return False for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: self.blocks[y + gamePiece.y][x + gamePiece.x] = None for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: blockXDiff = block.x - gamePiece.x blockYDiff = block.y - gamePiece.y newBlockX = xTo + blockXDiff newBlockY = yTo + blockYDiff self.blocks[newBlockY][newBlockX] = block block.moveTo(newBlockX, newBlockY) gamePiece.x = xTo gamePiece.y = yTo def addBlock(self, aBlock: gp.Block): """adds a block to the game board""" if self.blocks[aBlock.y][aBlock.x] != None: raise MovementError('game board space not empty') self.blocks[aBlock.y][aBlock.x] = aBlock self.groundSprites.append(aBlock.sprite) def addGamePiece(self, gamePiece: gp.GamePiece): for y in range(gamePiece.size): for x in range(gamePiece.size): block = gamePiece.blocks[y][x] if block is None: continue self.blocks[block.y][block.x] = block self.playerSprites.append(block.sprite) def moveBlock(self, aBlock: gp.Block, x: int, y: int): self.blocks[aBlock.y][aBlock.x] = None self.blocks[y][x] = aBlock def removeBlock(self, aBlock: gp.Block): """ remove a block from the game board """ for y, row in iter(self.blocks): for x, block in iter(row): if block is aBlock: self.blocks[y][x] = None self.playerSprites.remove(aBlock.sprite) return class GameManager: def __init__(self) ->None: pass def start(self): gameBoard = GameBoard(10, 20) gameBoard.addGamePiece() <|reserved_special_token_1|> from arcade.sprite_list.sprite_list import SpriteList import GamePiece as gp from Errors import * class GameConfig: WINDOW_TITLE = "MyPyTris" SCREEN_WIDTH = 450 SCREEN_HEIGHT = 900 BLOCK_PX = 45 # 45px blocks on screen SPRITE_PX = 64 # 64px sprite BLOCK_SCALE = BLOCK_PX/SPRITE_PX # sprite scale ratio class GameBoard: """ Class to manage blocks on the game board """ def __init__(self, width: int, height: int): # 2D list of blocks initialized to empty in the width and height of our game board self.width = width self.height = height self.blocks = [[None for y in range(width)] for x in range(height)] self.playerSprites = SpriteList() self.groundSprites = SpriteList() def draw(self): self.playerSprites.draw() self.groundSprites.draw() def canMoveBlock(self, x: int, y: int) -> bool: return self.blocks[x][y] is None def canMoveGamePiece(self, gamePiece:gp.GamePiece, xTo:int, yTo:int) -> bool: for yDiff, row in enumerate(gamePiece.blocks): for xDiff, block in enumerate(row): if block is None: continue newX = xTo + xDiff newY = yTo + yDiff if newX >= self.width or newX < 0: return False if newY < 0 or newY >= self.height: return False if self.blocks[newY][newX] is not None \ and self.blocks[newY][newX] not in gamePiece.allBlocks(): return False return True def moveGamePiece(self, gamePiece:gp.GamePiece, xTo:int, yTo:int): if (not self.canMoveGamePiece(gamePiece, xTo, yTo)): return False # remove blocks from game board for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: self.blocks[y + gamePiece.y][x + gamePiece.x] = None # add blocks in new positions for y, row in enumerate(gamePiece.blocks): for x, block in enumerate(row): if block is not None: blockXDiff = block.x - gamePiece.x blockYDiff = block.y - gamePiece.y newBlockX = xTo + blockXDiff newBlockY = yTo + blockYDiff self.blocks[newBlockY][newBlockX] = block block.moveTo(newBlockX, newBlockY) gamePiece.x = xTo gamePiece.y = yTo def addBlock(self, aBlock: gp.Block): """adds a block to the game board""" if self.blocks[aBlock.y][aBlock.x] != None: raise MovementError('game board space not empty') self.blocks[aBlock.y][aBlock.x] = aBlock self.groundSprites.append(aBlock.sprite) def addGamePiece(self, gamePiece:gp.GamePiece): for y in range(gamePiece.size): for x in range(gamePiece.size): block = gamePiece.blocks[y][x] if block is None: continue self.blocks[block.y][block.x] = block self.playerSprites.append(block.sprite) def moveBlock(self, aBlock: gp.Block, x: int, y: int): self.blocks[aBlock.y][aBlock.x] = None self.blocks[y][x] = aBlock def removeBlock(self, aBlock: gp.Block): """ remove a block from the game board """ for y, row in iter(self.blocks): for x, block in iter(row): if block is aBlock: self.blocks[y][x] = None self.playerSprites.remove(aBlock.sprite) return class GameManager: def __init__(self) -> None: pass def start(self): gameBoard = GameBoard(10, 20) gameBoard.addGamePiece()
flexible
{ "blob_id": "2d7431996bc8d1099c08fddc815b4706deb4f023", "index": 4393, "step-1": "<mask token>\n\n\nclass GameBoard:\n <mask token>\n <mask token>\n\n def draw(self):\n self.playerSprites.draw()\n self.groundSprites.draw()\n <mask token>\n <mask token>\n\n def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int):\n if not self.canMoveGamePiece(gamePiece, xTo, yTo):\n return False\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n self.blocks[y + gamePiece.y][x + gamePiece.x] = None\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n blockXDiff = block.x - gamePiece.x\n blockYDiff = block.y - gamePiece.y\n newBlockX = xTo + blockXDiff\n newBlockY = yTo + blockYDiff\n self.blocks[newBlockY][newBlockX] = block\n block.moveTo(newBlockX, newBlockY)\n gamePiece.x = xTo\n gamePiece.y = yTo\n <mask token>\n <mask token>\n <mask token>\n\n def removeBlock(self, aBlock: gp.Block):\n \"\"\" remove a block from the game board \"\"\"\n for y, row in iter(self.blocks):\n for x, block in iter(row):\n if block is aBlock:\n self.blocks[y][x] = None\n self.playerSprites.remove(aBlock.sprite)\n return\n\n\nclass GameManager:\n\n def __init__(self) ->None:\n pass\n\n def start(self):\n gameBoard = GameBoard(10, 20)\n gameBoard.addGamePiece()\n", "step-2": "<mask token>\n\n\nclass GameBoard:\n <mask token>\n\n def __init__(self, width: int, height: int):\n self.width = width\n self.height = height\n self.blocks = [[None for y in range(width)] for x in range(height)]\n self.playerSprites = SpriteList()\n self.groundSprites = SpriteList()\n\n def draw(self):\n self.playerSprites.draw()\n self.groundSprites.draw()\n\n def canMoveBlock(self, x: int, y: int) ->bool:\n return self.blocks[x][y] is None\n <mask token>\n\n def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int):\n if not self.canMoveGamePiece(gamePiece, xTo, yTo):\n return False\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n self.blocks[y + gamePiece.y][x + gamePiece.x] = None\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n blockXDiff = block.x - gamePiece.x\n blockYDiff = block.y - gamePiece.y\n newBlockX = xTo + blockXDiff\n newBlockY = yTo + blockYDiff\n self.blocks[newBlockY][newBlockX] = block\n block.moveTo(newBlockX, newBlockY)\n gamePiece.x = xTo\n gamePiece.y = yTo\n\n def addBlock(self, aBlock: gp.Block):\n \"\"\"adds a block to the game board\"\"\"\n if self.blocks[aBlock.y][aBlock.x] != None:\n raise MovementError('game board space not empty')\n self.blocks[aBlock.y][aBlock.x] = aBlock\n self.groundSprites.append(aBlock.sprite)\n\n def addGamePiece(self, gamePiece: gp.GamePiece):\n for y in range(gamePiece.size):\n for x in range(gamePiece.size):\n block = gamePiece.blocks[y][x]\n if block is None:\n continue\n self.blocks[block.y][block.x] = block\n self.playerSprites.append(block.sprite)\n\n def moveBlock(self, aBlock: gp.Block, x: int, y: int):\n self.blocks[aBlock.y][aBlock.x] = None\n self.blocks[y][x] = aBlock\n\n def removeBlock(self, aBlock: gp.Block):\n \"\"\" remove a block from the game board \"\"\"\n for y, row in iter(self.blocks):\n for x, block in iter(row):\n if block is aBlock:\n self.blocks[y][x] = None\n self.playerSprites.remove(aBlock.sprite)\n return\n\n\nclass GameManager:\n\n def __init__(self) ->None:\n pass\n\n def start(self):\n gameBoard = GameBoard(10, 20)\n gameBoard.addGamePiece()\n", "step-3": "<mask token>\n\n\nclass GameBoard:\n <mask token>\n\n def __init__(self, width: int, height: int):\n self.width = width\n self.height = height\n self.blocks = [[None for y in range(width)] for x in range(height)]\n self.playerSprites = SpriteList()\n self.groundSprites = SpriteList()\n\n def draw(self):\n self.playerSprites.draw()\n self.groundSprites.draw()\n\n def canMoveBlock(self, x: int, y: int) ->bool:\n return self.blocks[x][y] is None\n\n def canMoveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int\n ) ->bool:\n for yDiff, row in enumerate(gamePiece.blocks):\n for xDiff, block in enumerate(row):\n if block is None:\n continue\n newX = xTo + xDiff\n newY = yTo + yDiff\n if newX >= self.width or newX < 0:\n return False\n if newY < 0 or newY >= self.height:\n return False\n if self.blocks[newY][newX] is not None and self.blocks[newY][\n newX] not in gamePiece.allBlocks():\n return False\n return True\n\n def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int):\n if not self.canMoveGamePiece(gamePiece, xTo, yTo):\n return False\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n self.blocks[y + gamePiece.y][x + gamePiece.x] = None\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n blockXDiff = block.x - gamePiece.x\n blockYDiff = block.y - gamePiece.y\n newBlockX = xTo + blockXDiff\n newBlockY = yTo + blockYDiff\n self.blocks[newBlockY][newBlockX] = block\n block.moveTo(newBlockX, newBlockY)\n gamePiece.x = xTo\n gamePiece.y = yTo\n\n def addBlock(self, aBlock: gp.Block):\n \"\"\"adds a block to the game board\"\"\"\n if self.blocks[aBlock.y][aBlock.x] != None:\n raise MovementError('game board space not empty')\n self.blocks[aBlock.y][aBlock.x] = aBlock\n self.groundSprites.append(aBlock.sprite)\n\n def addGamePiece(self, gamePiece: gp.GamePiece):\n for y in range(gamePiece.size):\n for x in range(gamePiece.size):\n block = gamePiece.blocks[y][x]\n if block is None:\n continue\n self.blocks[block.y][block.x] = block\n self.playerSprites.append(block.sprite)\n\n def moveBlock(self, aBlock: gp.Block, x: int, y: int):\n self.blocks[aBlock.y][aBlock.x] = None\n self.blocks[y][x] = aBlock\n\n def removeBlock(self, aBlock: gp.Block):\n \"\"\" remove a block from the game board \"\"\"\n for y, row in iter(self.blocks):\n for x, block in iter(row):\n if block is aBlock:\n self.blocks[y][x] = None\n self.playerSprites.remove(aBlock.sprite)\n return\n\n\nclass GameManager:\n\n def __init__(self) ->None:\n pass\n\n def start(self):\n gameBoard = GameBoard(10, 20)\n gameBoard.addGamePiece()\n", "step-4": "from arcade.sprite_list.sprite_list import SpriteList\nimport GamePiece as gp\nfrom Errors import *\n\n\nclass GameConfig:\n WINDOW_TITLE = 'MyPyTris'\n SCREEN_WIDTH = 450\n SCREEN_HEIGHT = 900\n BLOCK_PX = 45\n SPRITE_PX = 64\n BLOCK_SCALE = BLOCK_PX / SPRITE_PX\n\n\nclass GameBoard:\n \"\"\" Class to manage blocks on the game board \"\"\"\n\n def __init__(self, width: int, height: int):\n self.width = width\n self.height = height\n self.blocks = [[None for y in range(width)] for x in range(height)]\n self.playerSprites = SpriteList()\n self.groundSprites = SpriteList()\n\n def draw(self):\n self.playerSprites.draw()\n self.groundSprites.draw()\n\n def canMoveBlock(self, x: int, y: int) ->bool:\n return self.blocks[x][y] is None\n\n def canMoveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int\n ) ->bool:\n for yDiff, row in enumerate(gamePiece.blocks):\n for xDiff, block in enumerate(row):\n if block is None:\n continue\n newX = xTo + xDiff\n newY = yTo + yDiff\n if newX >= self.width or newX < 0:\n return False\n if newY < 0 or newY >= self.height:\n return False\n if self.blocks[newY][newX] is not None and self.blocks[newY][\n newX] not in gamePiece.allBlocks():\n return False\n return True\n\n def moveGamePiece(self, gamePiece: gp.GamePiece, xTo: int, yTo: int):\n if not self.canMoveGamePiece(gamePiece, xTo, yTo):\n return False\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n self.blocks[y + gamePiece.y][x + gamePiece.x] = None\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n blockXDiff = block.x - gamePiece.x\n blockYDiff = block.y - gamePiece.y\n newBlockX = xTo + blockXDiff\n newBlockY = yTo + blockYDiff\n self.blocks[newBlockY][newBlockX] = block\n block.moveTo(newBlockX, newBlockY)\n gamePiece.x = xTo\n gamePiece.y = yTo\n\n def addBlock(self, aBlock: gp.Block):\n \"\"\"adds a block to the game board\"\"\"\n if self.blocks[aBlock.y][aBlock.x] != None:\n raise MovementError('game board space not empty')\n self.blocks[aBlock.y][aBlock.x] = aBlock\n self.groundSprites.append(aBlock.sprite)\n\n def addGamePiece(self, gamePiece: gp.GamePiece):\n for y in range(gamePiece.size):\n for x in range(gamePiece.size):\n block = gamePiece.blocks[y][x]\n if block is None:\n continue\n self.blocks[block.y][block.x] = block\n self.playerSprites.append(block.sprite)\n\n def moveBlock(self, aBlock: gp.Block, x: int, y: int):\n self.blocks[aBlock.y][aBlock.x] = None\n self.blocks[y][x] = aBlock\n\n def removeBlock(self, aBlock: gp.Block):\n \"\"\" remove a block from the game board \"\"\"\n for y, row in iter(self.blocks):\n for x, block in iter(row):\n if block is aBlock:\n self.blocks[y][x] = None\n self.playerSprites.remove(aBlock.sprite)\n return\n\n\nclass GameManager:\n\n def __init__(self) ->None:\n pass\n\n def start(self):\n gameBoard = GameBoard(10, 20)\n gameBoard.addGamePiece()\n", "step-5": "\nfrom arcade.sprite_list.sprite_list import SpriteList\nimport GamePiece as gp\nfrom Errors import *\n\nclass GameConfig:\n WINDOW_TITLE = \"MyPyTris\"\n SCREEN_WIDTH = 450\n SCREEN_HEIGHT = 900\n BLOCK_PX = 45 # 45px blocks on screen\n SPRITE_PX = 64 # 64px sprite\n BLOCK_SCALE = BLOCK_PX/SPRITE_PX # sprite scale ratio\n\nclass GameBoard:\n \"\"\" Class to manage blocks on the game board \"\"\"\n\n def __init__(self, width: int, height: int):\n # 2D list of blocks initialized to empty in the width and height of our game board\n self.width = width\n self.height = height\n self.blocks = [[None for y in range(width)] for x in range(height)]\n self.playerSprites = SpriteList()\n self.groundSprites = SpriteList()\n\n\n def draw(self):\n self.playerSprites.draw()\n self.groundSprites.draw()\n\n def canMoveBlock(self, x: int, y: int) -> bool:\n return self.blocks[x][y] is None\n\n def canMoveGamePiece(self, gamePiece:gp.GamePiece, xTo:int, yTo:int) -> bool:\n for yDiff, row in enumerate(gamePiece.blocks):\n for xDiff, block in enumerate(row):\n if block is None:\n continue\n newX = xTo + xDiff\n newY = yTo + yDiff\n if newX >= self.width or newX < 0:\n return False\n if newY < 0 or newY >= self.height:\n return False\n if self.blocks[newY][newX] is not None \\\n and self.blocks[newY][newX] not in gamePiece.allBlocks():\n return False\n return True\n\n def moveGamePiece(self, gamePiece:gp.GamePiece, xTo:int, yTo:int):\n if (not self.canMoveGamePiece(gamePiece, xTo, yTo)):\n return False\n\n # remove blocks from game board\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n self.blocks[y + gamePiece.y][x + gamePiece.x] = None\n\n # add blocks in new positions\n for y, row in enumerate(gamePiece.blocks):\n for x, block in enumerate(row):\n if block is not None:\n blockXDiff = block.x - gamePiece.x\n blockYDiff = block.y - gamePiece.y\n newBlockX = xTo + blockXDiff\n newBlockY = yTo + blockYDiff\n self.blocks[newBlockY][newBlockX] = block\n block.moveTo(newBlockX, newBlockY)\n\n gamePiece.x = xTo\n gamePiece.y = yTo\n \n\n def addBlock(self, aBlock: gp.Block):\n \"\"\"adds a block to the game board\"\"\"\n\n if self.blocks[aBlock.y][aBlock.x] != None:\n raise MovementError('game board space not empty')\n self.blocks[aBlock.y][aBlock.x] = aBlock\n self.groundSprites.append(aBlock.sprite)\n\n def addGamePiece(self, gamePiece:gp.GamePiece):\n for y in range(gamePiece.size):\n for x in range(gamePiece.size):\n block = gamePiece.blocks[y][x]\n if block is None:\n continue\n self.blocks[block.y][block.x] = block\n self.playerSprites.append(block.sprite)\n\n def moveBlock(self, aBlock: gp.Block, x: int, y: int):\n self.blocks[aBlock.y][aBlock.x] = None\n self.blocks[y][x] = aBlock\n\n def removeBlock(self, aBlock: gp.Block):\n \"\"\" remove a block from the game board \"\"\"\n \n for y, row in iter(self.blocks):\n for x, block in iter(row):\n if block is aBlock:\n self.blocks[y][x] = None\n self.playerSprites.remove(aBlock.sprite)\n return\n\n\nclass GameManager:\n\n def __init__(self) -> None:\n pass\n \n def start(self):\n gameBoard = GameBoard(10, 20)\n gameBoard.addGamePiece()", "step-ids": [ 7, 12, 13, 17, 18 ] }
[ 7, 12, 13, 17, 18 ]
from application.routes import pad_num, tracking_gen from flask import url_for from flask_testing import TestCase from application import app, db from application.models import Users, Orders from os import getenv class TestCase(TestCase): def create_app(self): app.config.update( SQLALCHEMY_DATABASE_URI="sqlite:///test.db", SECRET_KEY="TEST_SECRET_KEY", DEBUG=True, WTF_CSRF_ENABLED=False, ) return app def setUp(self): db.create_all() new_user = Users( email="[email protected]", name="Test", house_number="8", postcode="G3 8PX", phone="07999999999", ) db.session.add(new_user) new_order = Orders(customer_id=1) db.session.add(new_order) new_order = Orders(customer_id=1, order_status="out for delivery") db.session.add(new_order) new_order = Orders(customer_id=1, order_status="delivered") db.session.add(new_order) db.session.commit() def tearDown(self): db.session.remove() db.drop_all() class TestPadNum(TestCase): def test_pad_num(self): self.assertEqual(len(pad_num(3)), 4) class TestTrackingGen(TestCase): def test_tracking_gen(self): self.assertEqual(len(tracking_gen()), 8) class TestViews(TestCase): def test_home_get(self): response = self.client.get(url_for("home")) self.assertEqual(response.status_code, 200) def test_add_order_get(self): response = self.client.get(url_for("add_order")) self.assertEqual(response.status_code, 200) def test_view_order_get(self): response = self.client.get(url_for("view_order", id=1)) self.assertEqual(response.status_code, 200) def test_register_get(self): response = self.client.get(url_for("register")) self.assertEqual(response.status_code, 200) def test_update_order_get(self): response = self.client.get(url_for("update_order", id=1)) self.assertEqual(response.status_code, 200) def test_delete_get(self): response = self.client.get(url_for("delete", id=1)) self.assertEqual(response.status_code, 405) def test_delivered_get(self): response = self.client.get(url_for("delivered", id=1)) self.assertEqual(response.status_code, 405) class TestCreateUser(TestCase): def test_create_user(self): response = self.client.post( url_for("register"), data=dict( email="[email protected]", name="Test2", house_number="82", postcode="G2 8PX", phone="0788888888", ), follow_redirects=True, ) user = Users.query.filter_by(id=2).first() self.assertEqual("[email protected]", user.email) self.assertEqual("Test2", user.name) self.assertEqual("82", user.house_number) self.assertEqual("G2 8PX", user.postcode) self.assertEqual("0788888888", user.phone) class TestDuplicateEmail(TestCase): def test_duplicate_email(self): response = self.client.post( url_for("register"), data=dict( email="[email protected]", name="Test", house_number="82", postcode="G2 8PX", phone="0788888888", ), follow_redirects=True, ) class TestAddOrder(TestCase): def test_add_order(self): response = self.client.post( url_for("add_order", id=1), data=dict(email="[email protected]"), follow_redirects=True, ) order = Orders.query.filter_by(id=1).first() user = Users.query.filter_by(id=1).first() self.assertEqual(1, order.customer_id) self.assertEqual("order placed", order.order_status) self.assertEqual(None, order.tracking_num) self.assertIn(order, user.orders) class TestAddOrderNoUser(TestCase): def test_add_order_no_user(self): response = self.client.post( url_for("add_order"), data=dict(email="[email protected]") ) class TestViewOrder(TestCase): def test_view_order(self): response = self.client.get( url_for("view_order", id=1), data=dict( id="0006", name="Test", house_number="8", postode="G3 8PX", phone="07999999999", ), ) self.assertIn(b"0001", response.data) self.assertIn(b"Test", response.data) self.assertIn(b"8", response.data) self.assertIn(b"G3 8PX", response.data) self.assertIn(b"07999999999", response.data) class TestUpdateOrder(TestCase): def test_update_order(self): response = self.client.post( url_for("update_order", id=1), data=dict( status="out for delivery", tracking_num_len=8, ), ) order = Orders.query.filter_by(id=1).first() self.assertEqual("out for delivery", order.order_status) self.assertEqual(len(order.tracking_num), 8) class TestDelivered(TestCase): def test_delivered(self): response = self.client.post(url_for("delivered", id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual("delivered", order.order_status) class TestDelete(TestCase): def test_delete(self): response = self.client.post(url_for("delete", id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual(order, None)
normal
{ "blob_id": "eeece3bf423f85f05ef11db47909215578e64aec", "index": 4912, "step-1": "<mask token>\n\n\nclass TestViews(TestCase):\n <mask token>\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-2": "<mask token>\n\n\nclass TestPadNum(TestCase):\n <mask token>\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-3": "<mask token>\n\n\nclass TestCase(TestCase):\n\n def create_app(self):\n app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db',\n SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False)\n return app\n\n def setUp(self):\n db.create_all()\n new_user = Users(email='[email protected]', name='Test', house_number=\n '8', postcode='G3 8PX', phone='07999999999')\n db.session.add(new_user)\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='out for delivery')\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='delivered')\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-4": "from application.routes import pad_num, tracking_gen\nfrom flask import url_for\nfrom flask_testing import TestCase\nfrom application import app, db\nfrom application.models import Users, Orders\nfrom os import getenv\n\n\nclass TestCase(TestCase):\n\n def create_app(self):\n app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db',\n SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False)\n return app\n\n def setUp(self):\n db.create_all()\n new_user = Users(email='[email protected]', name='Test', house_number=\n '8', postcode='G3 8PX', phone='07999999999')\n db.session.add(new_user)\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='out for delivery')\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='delivered')\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-5": "from application.routes import pad_num, tracking_gen\nfrom flask import url_for\nfrom flask_testing import TestCase\n\nfrom application import app, db\nfrom application.models import Users, Orders\nfrom os import getenv\n\n\nclass TestCase(TestCase):\n def create_app(self):\n app.config.update(\n SQLALCHEMY_DATABASE_URI=\"sqlite:///test.db\",\n SECRET_KEY=\"TEST_SECRET_KEY\",\n DEBUG=True,\n WTF_CSRF_ENABLED=False,\n )\n return app\n\n def setUp(self):\n db.create_all()\n\n new_user = Users(\n email=\"[email protected]\",\n name=\"Test\",\n house_number=\"8\",\n postcode=\"G3 8PX\",\n phone=\"07999999999\",\n )\n db.session.add(new_user)\n\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n\n new_order = Orders(customer_id=1, order_status=\"out for delivery\")\n db.session.add(new_order)\n\n new_order = Orders(customer_id=1, order_status=\"delivered\")\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n def test_home_get(self):\n response = self.client.get(url_for(\"home\"))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for(\"add_order\"))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for(\"view_order\", id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for(\"register\"))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for(\"update_order\", id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for(\"delete\", id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for(\"delivered\", id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n def test_create_user(self):\n response = self.client.post(\n url_for(\"register\"),\n data=dict(\n email=\"[email protected]\",\n name=\"Test2\",\n house_number=\"82\",\n postcode=\"G2 8PX\",\n phone=\"0788888888\",\n ),\n follow_redirects=True,\n )\n user = Users.query.filter_by(id=2).first()\n self.assertEqual(\"[email protected]\", user.email)\n self.assertEqual(\"Test2\", user.name)\n self.assertEqual(\"82\", user.house_number)\n self.assertEqual(\"G2 8PX\", user.postcode)\n self.assertEqual(\"0788888888\", user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n def test_duplicate_email(self):\n response = self.client.post(\n url_for(\"register\"),\n data=dict(\n email=\"[email protected]\",\n name=\"Test\",\n house_number=\"82\",\n postcode=\"G2 8PX\",\n phone=\"0788888888\",\n ),\n follow_redirects=True,\n )\n\n\nclass TestAddOrder(TestCase):\n def test_add_order(self):\n response = self.client.post(\n url_for(\"add_order\", id=1),\n data=dict(email=\"[email protected]\"),\n follow_redirects=True,\n )\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual(\"order placed\", order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n def test_add_order_no_user(self):\n response = self.client.post(\n url_for(\"add_order\"), data=dict(email=\"[email protected]\")\n )\n\n\nclass TestViewOrder(TestCase):\n def test_view_order(self):\n response = self.client.get(\n url_for(\"view_order\", id=1),\n data=dict(\n id=\"0006\",\n name=\"Test\",\n house_number=\"8\",\n postode=\"G3 8PX\",\n phone=\"07999999999\",\n ),\n )\n self.assertIn(b\"0001\", response.data)\n self.assertIn(b\"Test\", response.data)\n self.assertIn(b\"8\", response.data)\n self.assertIn(b\"G3 8PX\", response.data)\n self.assertIn(b\"07999999999\", response.data)\n\n\nclass TestUpdateOrder(TestCase):\n def test_update_order(self):\n response = self.client.post(\n url_for(\"update_order\", id=1),\n data=dict(\n status=\"out for delivery\",\n tracking_num_len=8,\n ),\n )\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(\"out for delivery\", order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n def test_delivered(self):\n response = self.client.post(url_for(\"delivered\", id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(\"delivered\", order.order_status)\n\n\nclass TestDelete(TestCase):\n def test_delete(self):\n response = self.client.post(url_for(\"delete\", id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-ids": [ 20, 27, 32, 33, 34 ] }
[ 20, 27, 32, 33, 34 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> m.choropleth(geo_data=json, name='choropleth', data=data, columns=['State', 'Unemployment'], Key_on='feature.id', fill_color='YlGn', fill_opacity= 0.7, line_opacity=0.2, legend_name='Unemployment Rate (%)') folium.LayerControl().add_to(m) m.save(ctx + 'result.html') <|reserved_special_token_1|> <|reserved_special_token_0|> ctx = '../data/' json = ctx + 'us-states.json' csv = ctx + 'US_Unemployment_Oct2012.csv' data = pd.read_csv(csv) m = folium.Map(location=[37, -102], zoom_start=5) m.choropleth(geo_data=json, name='choropleth', data=data, columns=['State', 'Unemployment'], Key_on='feature.id', fill_color='YlGn', fill_opacity= 0.7, line_opacity=0.2, legend_name='Unemployment Rate (%)') folium.LayerControl().add_to(m) m.save(ctx + 'result.html') <|reserved_special_token_1|> import pandas as pd import folium ctx = '../data/' json = ctx + 'us-states.json' csv = ctx + 'US_Unemployment_Oct2012.csv' data = pd.read_csv(csv) m = folium.Map(location=[37, -102], zoom_start=5) m.choropleth(geo_data=json, name='choropleth', data=data, columns=['State', 'Unemployment'], Key_on='feature.id', fill_color='YlGn', fill_opacity= 0.7, line_opacity=0.2, legend_name='Unemployment Rate (%)') folium.LayerControl().add_to(m) m.save(ctx + 'result.html')
flexible
{ "blob_id": "382cb55a6b849f0240276d8f45746e995b16d714", "index": 4455, "step-1": "<mask token>\n", "step-2": "<mask token>\nm.choropleth(geo_data=json, name='choropleth', data=data, columns=['State',\n 'Unemployment'], Key_on='feature.id', fill_color='YlGn', fill_opacity=\n 0.7, line_opacity=0.2, legend_name='Unemployment Rate (%)')\nfolium.LayerControl().add_to(m)\nm.save(ctx + 'result.html')\n", "step-3": "<mask token>\nctx = '../data/'\njson = ctx + 'us-states.json'\ncsv = ctx + 'US_Unemployment_Oct2012.csv'\ndata = pd.read_csv(csv)\nm = folium.Map(location=[37, -102], zoom_start=5)\nm.choropleth(geo_data=json, name='choropleth', data=data, columns=['State',\n 'Unemployment'], Key_on='feature.id', fill_color='YlGn', fill_opacity=\n 0.7, line_opacity=0.2, legend_name='Unemployment Rate (%)')\nfolium.LayerControl().add_to(m)\nm.save(ctx + 'result.html')\n", "step-4": "import pandas as pd\nimport folium\nctx = '../data/'\njson = ctx + 'us-states.json'\ncsv = ctx + 'US_Unemployment_Oct2012.csv'\ndata = pd.read_csv(csv)\nm = folium.Map(location=[37, -102], zoom_start=5)\nm.choropleth(geo_data=json, name='choropleth', data=data, columns=['State',\n 'Unemployment'], Key_on='feature.id', fill_color='YlGn', fill_opacity=\n 0.7, line_opacity=0.2, legend_name='Unemployment Rate (%)')\nfolium.LayerControl().add_to(m)\nm.save(ctx + 'result.html')\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> chromedriver = os.path.abspath(os.path.dirname(__file__) ) + '\\chromedriver\\' + getchromdriver_version() download_path = os.path.abspath(os.path.dirname(__file__)) + '\\' Suffix_name = ['.bin', '.rar', '.zip', '.7z'] <|reserved_special_token_1|> from utils.general import getchromdriver_version from chromedriver.path import path import os import sys chromedriver = os.path.abspath(os.path.dirname(__file__) ) + '\\chromedriver\\' + getchromdriver_version() download_path = os.path.abspath(os.path.dirname(__file__)) + '\\' Suffix_name = ['.bin', '.rar', '.zip', '.7z'] <|reserved_special_token_1|> # -*- coding: utf-8 -*- # @File : config.py # @Author: TT # @Email : [email protected] # @Date : 2018/12/4 # @Desc : config file from utils.general import getchromdriver_version from chromedriver.path import path import os import sys chromedriver = os.path.abspath(os.path.dirname(__file__)) + "\\chromedriver\\"+ getchromdriver_version() download_path = os.path.abspath(os.path.dirname(__file__)) + "\\" Suffix_name = ['.bin', '.rar', '.zip', '.7z']
flexible
{ "blob_id": "5b4a196de60a3a30bc571c559fe5f211563b8999", "index": 5449, "step-1": "<mask token>\n", "step-2": "<mask token>\nchromedriver = os.path.abspath(os.path.dirname(__file__)\n ) + '\\\\chromedriver\\\\' + getchromdriver_version()\ndownload_path = os.path.abspath(os.path.dirname(__file__)) + '\\\\'\nSuffix_name = ['.bin', '.rar', '.zip', '.7z']\n", "step-3": "from utils.general import getchromdriver_version\nfrom chromedriver.path import path\nimport os\nimport sys\nchromedriver = os.path.abspath(os.path.dirname(__file__)\n ) + '\\\\chromedriver\\\\' + getchromdriver_version()\ndownload_path = os.path.abspath(os.path.dirname(__file__)) + '\\\\'\nSuffix_name = ['.bin', '.rar', '.zip', '.7z']\n", "step-4": "# -*- coding: utf-8 -*-\n# @File : config.py\n# @Author: TT\n# @Email : [email protected]\n# @Date : 2018/12/4\n# @Desc : config file\nfrom utils.general import getchromdriver_version\nfrom chromedriver.path import path\nimport os\nimport sys\n\nchromedriver = os.path.abspath(os.path.dirname(__file__)) + \"\\\\chromedriver\\\\\"+ getchromdriver_version()\n\ndownload_path = os.path.abspath(os.path.dirname(__file__)) + \"\\\\\"\n\nSuffix_name = ['.bin', '.rar', '.zip', '.7z']\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from tkinter import * class Menuutje: def __init__(self, master): menu = Menu(master) master.config(menu=menu) subMenu = Menu(menu) menu.add_cascade(label="File", menu=subMenu) subMenu.add_command(label="New Game...", command=self.doNothing) subMenu.add_command(label="New...", command=self.doNothing) subMenu.add_separator() subMenu.add_command(label="Exit", command=self.doNothing) editMenu = Menu(menu) menu.add_cascade(label="Edit", menu=editMenu) editMenu.add_command(label="Redo", command=self.doNothing) def doNothing(self): print("Okay I do nothing..") class MenuGameRPS: def __init__(self, master): menu = Menu(master) master.config(menu=menu) subMenu = Menu(menu) menu.add_cascade(label="File", menu=subMenu) subMenu.add_command(label="New Game...", command=self.newGame) subMenu.add_separator() subMenu.add_command(label="Exit", command=self.exitGame) def exitGame(self): exit() def newGame(self):
normal
{ "blob_id": "8fbfa53be826b45b53b530a1766f6a68c61f5be9", "index": 9377, "step-1": "from tkinter import *\n\n\nclass Menuutje:\n\n def __init__(self, master):\n menu = Menu(master)\n master.config(menu=menu)\n\n subMenu = Menu(menu)\n menu.add_cascade(label=\"File\", menu=subMenu)\n subMenu.add_command(label=\"New Game...\", command=self.doNothing)\n subMenu.add_command(label=\"New...\", command=self.doNothing)\n subMenu.add_separator()\n subMenu.add_command(label=\"Exit\", command=self.doNothing)\n\n editMenu = Menu(menu)\n menu.add_cascade(label=\"Edit\", menu=editMenu)\n editMenu.add_command(label=\"Redo\", command=self.doNothing)\n\n\n def doNothing(self):\n print(\"Okay I do nothing..\")\n\n\nclass MenuGameRPS:\n def __init__(self, master):\n menu = Menu(master)\n master.config(menu=menu)\n\n subMenu = Menu(menu)\n menu.add_cascade(label=\"File\", menu=subMenu)\n subMenu.add_command(label=\"New Game...\", command=self.newGame)\n subMenu.add_separator()\n subMenu.add_command(label=\"Exit\", command=self.exitGame)\n\n\n def exitGame(self):\n exit()\n\n\n def newGame(self):\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> def get_labelled_data_from_directories(data_dir, maxlen=None): texts = [] labels_index = {} labels = [] for name in sorted(os.listdir(data_dir)): path = os.path.join(data_dir, name) if os.path.isdir(path): label_id = len(labels_index) labels_index[name] = label_id for fname in os.listdir(path): fpath = os.path.join(path, fname) f = open(fpath) t = f.read() if maxlen is not None: t = get_first_n_words(t, maxlen) texts.append(t) f.close() labels.append(label_id) return texts, labels_index, labels <|reserved_special_token_1|> <|reserved_special_token_0|> def filter_not_punctuation(): return '"#$%&()*+-/:;<=>@[\\]^_`{|}~\t\n' <|reserved_special_token_0|> def get_labelled_data_from_directories(data_dir, maxlen=None): texts = [] labels_index = {} labels = [] for name in sorted(os.listdir(data_dir)): path = os.path.join(data_dir, name) if os.path.isdir(path): label_id = len(labels_index) labels_index[name] = label_id for fname in os.listdir(path): fpath = os.path.join(path, fname) f = open(fpath) t = f.read() if maxlen is not None: t = get_first_n_words(t, maxlen) texts.append(t) f.close() labels.append(label_id) return texts, labels_index, labels <|reserved_special_token_1|> <|reserved_special_token_0|> def filter_not_punctuation(): return '"#$%&()*+-/:;<=>@[\\]^_`{|}~\t\n' def get_first_n_words(text, n): string_sequence = text_to_word_sequence(text, filters= filter_not_punctuation()) truncated_string = '' for word in string_sequence[:n]: truncated_string = truncated_string + word + ' ' return truncated_string def get_labelled_data_from_directories(data_dir, maxlen=None): texts = [] labels_index = {} labels = [] for name in sorted(os.listdir(data_dir)): path = os.path.join(data_dir, name) if os.path.isdir(path): label_id = len(labels_index) labels_index[name] = label_id for fname in os.listdir(path): fpath = os.path.join(path, fname) f = open(fpath) t = f.read() if maxlen is not None: t = get_first_n_words(t, maxlen) texts.append(t) f.close() labels.append(label_id) return texts, labels_index, labels <|reserved_special_token_1|> from keras.preprocessing.text import text_to_word_sequence import os def filter_not_punctuation(): return '"#$%&()*+-/:;<=>@[\\]^_`{|}~\t\n' def get_first_n_words(text, n): string_sequence = text_to_word_sequence(text, filters= filter_not_punctuation()) truncated_string = '' for word in string_sequence[:n]: truncated_string = truncated_string + word + ' ' return truncated_string def get_labelled_data_from_directories(data_dir, maxlen=None): texts = [] labels_index = {} labels = [] for name in sorted(os.listdir(data_dir)): path = os.path.join(data_dir, name) if os.path.isdir(path): label_id = len(labels_index) labels_index[name] = label_id for fname in os.listdir(path): fpath = os.path.join(path, fname) f = open(fpath) t = f.read() if maxlen is not None: t = get_first_n_words(t, maxlen) texts.append(t) f.close() labels.append(label_id) return texts, labels_index, labels <|reserved_special_token_1|> from keras.preprocessing.text import text_to_word_sequence import os # keras NLP tools filter out certain tokens by default # this function replaces the default with a smaller set of things to filter out def filter_not_punctuation(): return '"#$%&()*+-/:;<=>@[\\]^_`{|}~\t\n' def get_first_n_words(text, n): string_sequence = text_to_word_sequence(text, filters=filter_not_punctuation()) truncated_string = '' for word in string_sequence[:n]: truncated_string = truncated_string + word + ' ' return truncated_string # gets text data from files with only maxlen words from each file. Gets whole file if maxlen is None def get_labelled_data_from_directories(data_dir, maxlen=None): texts = [] # list of text samples labels_index = {} # dictionary mapping label name to numeric id labels = [] # list of label ids for name in sorted(os.listdir(data_dir)): path = os.path.join(data_dir, name) if os.path.isdir(path): label_id = len(labels_index) labels_index[name] = label_id for fname in os.listdir(path): fpath = os.path.join(path, fname) f = open(fpath) t = f.read() if maxlen is not None: t = get_first_n_words(t, maxlen) texts.append(t) f.close() labels.append(label_id) return texts, labels_index, labels
flexible
{ "blob_id": "365e2059d5ed3d7f8d9dbb4e44f563b79d68b087", "index": 1856, "step-1": "<mask token>\n\n\ndef get_labelled_data_from_directories(data_dir, maxlen=None):\n texts = []\n labels_index = {}\n labels = []\n for name in sorted(os.listdir(data_dir)):\n path = os.path.join(data_dir, name)\n if os.path.isdir(path):\n label_id = len(labels_index)\n labels_index[name] = label_id\n for fname in os.listdir(path):\n fpath = os.path.join(path, fname)\n f = open(fpath)\n t = f.read()\n if maxlen is not None:\n t = get_first_n_words(t, maxlen)\n texts.append(t)\n f.close()\n labels.append(label_id)\n return texts, labels_index, labels\n", "step-2": "<mask token>\n\n\ndef filter_not_punctuation():\n return '\"#$%&()*+-/:;<=>@[\\\\]^_`{|}~\\t\\n'\n\n\n<mask token>\n\n\ndef get_labelled_data_from_directories(data_dir, maxlen=None):\n texts = []\n labels_index = {}\n labels = []\n for name in sorted(os.listdir(data_dir)):\n path = os.path.join(data_dir, name)\n if os.path.isdir(path):\n label_id = len(labels_index)\n labels_index[name] = label_id\n for fname in os.listdir(path):\n fpath = os.path.join(path, fname)\n f = open(fpath)\n t = f.read()\n if maxlen is not None:\n t = get_first_n_words(t, maxlen)\n texts.append(t)\n f.close()\n labels.append(label_id)\n return texts, labels_index, labels\n", "step-3": "<mask token>\n\n\ndef filter_not_punctuation():\n return '\"#$%&()*+-/:;<=>@[\\\\]^_`{|}~\\t\\n'\n\n\ndef get_first_n_words(text, n):\n string_sequence = text_to_word_sequence(text, filters=\n filter_not_punctuation())\n truncated_string = ''\n for word in string_sequence[:n]:\n truncated_string = truncated_string + word + ' '\n return truncated_string\n\n\ndef get_labelled_data_from_directories(data_dir, maxlen=None):\n texts = []\n labels_index = {}\n labels = []\n for name in sorted(os.listdir(data_dir)):\n path = os.path.join(data_dir, name)\n if os.path.isdir(path):\n label_id = len(labels_index)\n labels_index[name] = label_id\n for fname in os.listdir(path):\n fpath = os.path.join(path, fname)\n f = open(fpath)\n t = f.read()\n if maxlen is not None:\n t = get_first_n_words(t, maxlen)\n texts.append(t)\n f.close()\n labels.append(label_id)\n return texts, labels_index, labels\n", "step-4": "from keras.preprocessing.text import text_to_word_sequence\nimport os\n\n\ndef filter_not_punctuation():\n return '\"#$%&()*+-/:;<=>@[\\\\]^_`{|}~\\t\\n'\n\n\ndef get_first_n_words(text, n):\n string_sequence = text_to_word_sequence(text, filters=\n filter_not_punctuation())\n truncated_string = ''\n for word in string_sequence[:n]:\n truncated_string = truncated_string + word + ' '\n return truncated_string\n\n\ndef get_labelled_data_from_directories(data_dir, maxlen=None):\n texts = []\n labels_index = {}\n labels = []\n for name in sorted(os.listdir(data_dir)):\n path = os.path.join(data_dir, name)\n if os.path.isdir(path):\n label_id = len(labels_index)\n labels_index[name] = label_id\n for fname in os.listdir(path):\n fpath = os.path.join(path, fname)\n f = open(fpath)\n t = f.read()\n if maxlen is not None:\n t = get_first_n_words(t, maxlen)\n texts.append(t)\n f.close()\n labels.append(label_id)\n return texts, labels_index, labels\n", "step-5": "from keras.preprocessing.text import text_to_word_sequence\nimport os\n\n\n# keras NLP tools filter out certain tokens by default\n# this function replaces the default with a smaller set of things to filter out\ndef filter_not_punctuation():\n return '\"#$%&()*+-/:;<=>@[\\\\]^_`{|}~\\t\\n'\n\n\ndef get_first_n_words(text, n):\n string_sequence = text_to_word_sequence(text, filters=filter_not_punctuation())\n truncated_string = ''\n for word in string_sequence[:n]:\n truncated_string = truncated_string + word + ' '\n return truncated_string\n\n\n\n\n# gets text data from files with only maxlen words from each file. Gets whole file if maxlen is None\ndef get_labelled_data_from_directories(data_dir, maxlen=None):\n texts = [] # list of text samples\n labels_index = {} # dictionary mapping label name to numeric id\n labels = [] # list of label ids\n for name in sorted(os.listdir(data_dir)):\n path = os.path.join(data_dir, name)\n if os.path.isdir(path):\n label_id = len(labels_index)\n labels_index[name] = label_id\n for fname in os.listdir(path):\n fpath = os.path.join(path, fname)\n f = open(fpath)\n t = f.read()\n if maxlen is not None:\n t = get_first_n_words(t, maxlen)\n texts.append(t)\n f.close()\n labels.append(label_id)\n return texts, labels_index, labels\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> INITIAL_B = 0.15062677711161448 B_FACTOR = 5.0 INITIAL_GE = 0.22581915788215678 GE_BOUNDS = [1.0 / 10.0, 1.0 / 4.0] FIXED_P = 0.9401234488501574 INITIAL_GU = 0.2145066414796447 GU_BOUNDS = [1.0 / 15.0, 1.0 / 2.0] INITIAL_GI = 0.19235137989123863 GI_BOUNDS = [1.0 / 15.0, 1.0 / 5.0] INITIAL_GH = 0.044937075878220795 GH_BOUNDS = [1.0 / 20.0, 1.0 / 5.0] INITIAL_MU = 0.002840331041978459 MU_BOUNDS = [0.0, 0.1] INITIAL_PARAMETERS = [INITIAL_B, INITIAL_GE, FIXED_P, INITIAL_GU, INITIAL_GI, INITIAL_GH, None, INITIAL_MU] E_FACTOR = 5.0 U_FACTOR = 5.0 I_FACTOR = 5.0 <|reserved_special_token_1|> INITIAL_B = 0.15062677711161448 B_FACTOR = 5.0 INITIAL_GE = 0.22581915788215678 GE_BOUNDS = [1.0 / 10.0, 1.0 / 4.0] FIXED_P = 0.9401234488501574 INITIAL_GU = 0.2145066414796447 GU_BOUNDS = [1.0 / 15.0, 1.0 / 2.0] INITIAL_GI = 0.19235137989123863 GI_BOUNDS = [1.0 / 15.0, 1.0 / 5.0] INITIAL_GH = 0.044937075878220795 GH_BOUNDS = [1.0 / 20.0, 1.0 / 5.0] INITIAL_MU = 0.002840331041978459 MU_BOUNDS = [0.0, 0.1] INITIAL_PARAMETERS = [ INITIAL_B, INITIAL_GE, FIXED_P, INITIAL_GU, INITIAL_GI, INITIAL_GH, None, # rH INITIAL_MU, ] E_FACTOR = 5.0 U_FACTOR = 5.0 I_FACTOR = 5.0
flexible
{ "blob_id": "47cf3045f2fa0f69759e09b1599e4afe953c06d8", "index": 5138, "step-1": "<mask token>\n", "step-2": "INITIAL_B = 0.15062677711161448\nB_FACTOR = 5.0\nINITIAL_GE = 0.22581915788215678\nGE_BOUNDS = [1.0 / 10.0, 1.0 / 4.0]\nFIXED_P = 0.9401234488501574\nINITIAL_GU = 0.2145066414796447\nGU_BOUNDS = [1.0 / 15.0, 1.0 / 2.0]\nINITIAL_GI = 0.19235137989123863\nGI_BOUNDS = [1.0 / 15.0, 1.0 / 5.0]\nINITIAL_GH = 0.044937075878220795\nGH_BOUNDS = [1.0 / 20.0, 1.0 / 5.0]\nINITIAL_MU = 0.002840331041978459\nMU_BOUNDS = [0.0, 0.1]\nINITIAL_PARAMETERS = [INITIAL_B, INITIAL_GE, FIXED_P, INITIAL_GU,\n INITIAL_GI, INITIAL_GH, None, INITIAL_MU]\nE_FACTOR = 5.0\nU_FACTOR = 5.0\nI_FACTOR = 5.0\n", "step-3": "INITIAL_B = 0.15062677711161448\nB_FACTOR = 5.0\n\nINITIAL_GE = 0.22581915788215678\nGE_BOUNDS = [1.0 / 10.0, 1.0 / 4.0]\n\nFIXED_P = 0.9401234488501574\n\nINITIAL_GU = 0.2145066414796447\nGU_BOUNDS = [1.0 / 15.0, 1.0 / 2.0]\n\nINITIAL_GI = 0.19235137989123863\nGI_BOUNDS = [1.0 / 15.0, 1.0 / 5.0]\n\nINITIAL_GH = 0.044937075878220795\nGH_BOUNDS = [1.0 / 20.0, 1.0 / 5.0]\n\nINITIAL_MU = 0.002840331041978459\nMU_BOUNDS = [0.0, 0.1]\n\nINITIAL_PARAMETERS = [\n INITIAL_B,\n INITIAL_GE,\n FIXED_P,\n INITIAL_GU,\n INITIAL_GI,\n INITIAL_GH,\n None, # rH\n INITIAL_MU,\n]\n\nE_FACTOR = 5.0\nU_FACTOR = 5.0\nI_FACTOR = 5.0\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> def nl(): print('\n') def main(): print('Start') msg = 'ana i mujica' msg2 = msg.replace('a', '$') print(msg) print(msg2) ivana = 'ivana' print(ivana * 2) fruit = ['banana', 'apple', 'legit'] for i in range(len(fruit)): print(fruit[i], end='') nl() print([fruit[0], fruit[1]]) print([fruit[0], fruit[1]], sep='$') animal1 = Animal(30) print(animal1) nl() print('End') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def nl(): print('\n') def main(): print('Start') msg = 'ana i mujica' msg2 = msg.replace('a', '$') print(msg) print(msg2) ivana = 'ivana' print(ivana * 2) fruit = ['banana', 'apple', 'legit'] for i in range(len(fruit)): print(fruit[i], end='') nl() print([fruit[0], fruit[1]]) print([fruit[0], fruit[1]], sep='$') animal1 = Animal(30) print(animal1) nl() print('End') main() <|reserved_special_token_1|> <|reserved_special_token_0|> __author__ = 'igord' def nl(): print('\n') def main(): print('Start') msg = 'ana i mujica' msg2 = msg.replace('a', '$') print(msg) print(msg2) ivana = 'ivana' print(ivana * 2) fruit = ['banana', 'apple', 'legit'] for i in range(len(fruit)): print(fruit[i], end='') nl() print([fruit[0], fruit[1]]) print([fruit[0], fruit[1]], sep='$') animal1 = Animal(30) print(animal1) nl() print('End') main() <|reserved_special_token_1|> from pypack.Animal import Animal __author__ = 'igord' def nl(): print('\n') def main(): print('Start') msg = 'ana i mujica' msg2 = msg.replace('a', '$') print(msg) print(msg2) ivana = 'ivana' print(ivana * 2) fruit = ['banana', 'apple', 'legit'] for i in range(len(fruit)): print(fruit[i], end='') nl() print([fruit[0], fruit[1]]) print([fruit[0], fruit[1]], sep='$') animal1 = Animal(30) print(animal1) nl() print('End') main() <|reserved_special_token_1|> from pypack.Animal import Animal __author__ = 'igord' def nl(): print("\n") def main(): # print("Hello2") # animal = Animal(45) # animal.double_age() # print(animal.age) print("Start") msg = "ana i mujica" msg2 = msg.replace("a", "$") print(msg) print(msg2) ivana = "ivana" print(ivana * 2) # print(sys.api_version) fruit = ["banana", "apple", "legit"] for i in range(len(fruit)): # pass # sys.stdout.write("test") # print("test", end="") print(fruit[i], end="") nl() print([fruit[0], fruit[1]]) print([fruit[0], fruit[1]], sep="$") animal1 = Animal(30) print(animal1) nl() print("End") main()
flexible
{ "blob_id": "b0cdf75ff00d72ada75990dd850546414bc11125", "index": 1799, "step-1": "<mask token>\n\n\ndef nl():\n print('\\n')\n\n\ndef main():\n print('Start')\n msg = 'ana i mujica'\n msg2 = msg.replace('a', '$')\n print(msg)\n print(msg2)\n ivana = 'ivana'\n print(ivana * 2)\n fruit = ['banana', 'apple', 'legit']\n for i in range(len(fruit)):\n print(fruit[i], end='')\n nl()\n print([fruit[0], fruit[1]])\n print([fruit[0], fruit[1]], sep='$')\n animal1 = Animal(30)\n print(animal1)\n nl()\n print('End')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef nl():\n print('\\n')\n\n\ndef main():\n print('Start')\n msg = 'ana i mujica'\n msg2 = msg.replace('a', '$')\n print(msg)\n print(msg2)\n ivana = 'ivana'\n print(ivana * 2)\n fruit = ['banana', 'apple', 'legit']\n for i in range(len(fruit)):\n print(fruit[i], end='')\n nl()\n print([fruit[0], fruit[1]])\n print([fruit[0], fruit[1]], sep='$')\n animal1 = Animal(30)\n print(animal1)\n nl()\n print('End')\n\n\nmain()\n", "step-3": "<mask token>\n__author__ = 'igord'\n\n\ndef nl():\n print('\\n')\n\n\ndef main():\n print('Start')\n msg = 'ana i mujica'\n msg2 = msg.replace('a', '$')\n print(msg)\n print(msg2)\n ivana = 'ivana'\n print(ivana * 2)\n fruit = ['banana', 'apple', 'legit']\n for i in range(len(fruit)):\n print(fruit[i], end='')\n nl()\n print([fruit[0], fruit[1]])\n print([fruit[0], fruit[1]], sep='$')\n animal1 = Animal(30)\n print(animal1)\n nl()\n print('End')\n\n\nmain()\n", "step-4": "from pypack.Animal import Animal\n__author__ = 'igord'\n\n\ndef nl():\n print('\\n')\n\n\ndef main():\n print('Start')\n msg = 'ana i mujica'\n msg2 = msg.replace('a', '$')\n print(msg)\n print(msg2)\n ivana = 'ivana'\n print(ivana * 2)\n fruit = ['banana', 'apple', 'legit']\n for i in range(len(fruit)):\n print(fruit[i], end='')\n nl()\n print([fruit[0], fruit[1]])\n print([fruit[0], fruit[1]], sep='$')\n animal1 = Animal(30)\n print(animal1)\n nl()\n print('End')\n\n\nmain()\n", "step-5": "from pypack.Animal import Animal\n\n__author__ = 'igord'\n\n\ndef nl():\n print(\"\\n\")\n\ndef main():\n # print(\"Hello2\")\n # animal = Animal(45)\n # animal.double_age()\n # print(animal.age)\n\n print(\"Start\")\n\n msg = \"ana i mujica\"\n msg2 = msg.replace(\"a\", \"$\")\n print(msg)\n print(msg2)\n ivana = \"ivana\"\n print(ivana * 2)\n\n # print(sys.api_version)\n\n fruit = [\"banana\", \"apple\", \"legit\"]\n for i in range(len(fruit)):\n # pass\n # sys.stdout.write(\"test\")\n # print(\"test\", end=\"\")\n print(fruit[i], end=\"\")\n nl()\n\n print([fruit[0], fruit[1]])\n print([fruit[0], fruit[1]], sep=\"$\")\n\n animal1 = Animal(30)\n print(animal1)\n\n nl()\n print(\"End\")\n\nmain()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
from py.test import raises from ..lazymap import LazyMap def test_lazymap(): data = list(range(10)) lm = LazyMap(data, lambda x: 2 * x) assert len(lm) == 10 assert lm[1] == 2 assert isinstance(lm[1:4], LazyMap) assert lm.append == data.append assert repr(lm) == '<LazyMap [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>' def test_lazymap_iter(): data = list(range(2)) lm = LazyMap(data, lambda x: 2 * x) iter_lm = iter(lm) assert iter_lm.next() == 0 assert iter_lm.next() == 2 with raises(StopIteration): iter_lm.next()
normal
{ "blob_id": "3e7d80fdd1adb570934e4b252bc25d5746b4c68e", "index": 3912, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_lazymap():\n data = list(range(10))\n lm = LazyMap(data, lambda x: 2 * x)\n assert len(lm) == 10\n assert lm[1] == 2\n assert isinstance(lm[1:4], LazyMap)\n assert lm.append == data.append\n assert repr(lm) == '<LazyMap [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>'\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef test_lazymap():\n data = list(range(10))\n lm = LazyMap(data, lambda x: 2 * x)\n assert len(lm) == 10\n assert lm[1] == 2\n assert isinstance(lm[1:4], LazyMap)\n assert lm.append == data.append\n assert repr(lm) == '<LazyMap [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>'\n\n\ndef test_lazymap_iter():\n data = list(range(2))\n lm = LazyMap(data, lambda x: 2 * x)\n iter_lm = iter(lm)\n assert iter_lm.next() == 0\n assert iter_lm.next() == 2\n with raises(StopIteration):\n iter_lm.next()\n", "step-4": "from py.test import raises\nfrom ..lazymap import LazyMap\n\n\ndef test_lazymap():\n data = list(range(10))\n lm = LazyMap(data, lambda x: 2 * x)\n assert len(lm) == 10\n assert lm[1] == 2\n assert isinstance(lm[1:4], LazyMap)\n assert lm.append == data.append\n assert repr(lm) == '<LazyMap [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>'\n\n\ndef test_lazymap_iter():\n data = list(range(2))\n lm = LazyMap(data, lambda x: 2 * x)\n iter_lm = iter(lm)\n assert iter_lm.next() == 0\n assert iter_lm.next() == 2\n with raises(StopIteration):\n iter_lm.next()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import pandas as pd import numpy as np import matplotlib.pyplot as plt import xlrd from enum import Enum from sklearn import linear_model from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import statsmodels.formula.api as smf import statsmodels.api as sm import statsmodels.formula.api as smf def forward_selected(data, response): """Linear model designed by forward selection. Parameters: ----------- data : pandas DataFrame with all possible predictors and response response: string, name of response column in data Returns: -------- model: an "optimal" fitted statsmodels linear model with an intercept selected by forward selection evaluated by adjusted R-squared """ remaining = set(data.columns) remaining.remove(response) selected = [] current_score, best_new_score = 0.0, 0.0 while remaining and current_score == best_new_score: scores_with_candidates = [] for candidate in remaining: formula = "{} ~ {} + 1".format(response, ' + '.join(selected + [candidate])) score = smf.ols(formula, data).fit().rsquared_adj scores_with_candidates.append((score, candidate)) scores_with_candidates.sort() best_new_score, best_candidate = scores_with_candidates.pop() if current_score < best_new_score: remaining.remove(best_candidate) selected.append(best_candidate) current_score = best_new_score formula = "{} ~ {} + 1".format(response, ' + '.join(selected)) model = smf.ols(formula, data).fit() print(selected) return model # def backwardElimination(x, y, sl): # numVars = len(x[0]) # for i in range(0, numVars): # regressor_OLS = sm.OLS(y, x).fit() # maxVar = max(regressor_OLS.pvalues).astype(float) # if maxVar > sl: # for j in range(0, numVars - i): # if (regressor_OLS.pvalues[j].astype(float) == maxVar): # x = (x, j, 1) # regressor_OLS.summary() # return x dfBIG=pd.read_csv("C:\\Users\\family\\Desktop\\Big12and10.csv") dfSEC=pd.read_csv("C:\\Users\\family\\Desktop\\SEC.csv")#- For SEC data dfPAC=pd.read_csv("C:\\Users\\family\\Desktop\\AtlanticCoast.csv")#- For Atlantic Coast and Pac12 df_Predict=pd.read_csv("C:\\Users\\family\\Desktop\\PredictV2.csv") #plt.scatter(dfBIG['DP'],dfBIG['YDS/GAME']) SecX=dfSEC[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS','ROOKIE_YDS_GAME']]# Works for SEC BigX=dfBIG[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS','ROOKIE_YDS_GAME']] #Works for AtlanticCoast/Pac12 and Big 10/12 #PacX=dfPAC[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS','ROOKIE_YDS_GAME']] #Works for AtlanticCoast/Pac12 and Big 10/12 PacX=dfPAC[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS']] #Works for AtlanticCoast/Pac12 and Big 10/12 #PacX=dfPAC[['DP','CATCH_%','40YD','REC','TD','YDS/TA','TARGETS']] #Works for AtlanticCoast/Pac12 and Big 10/12 #PredictSecX=df_Predict[['DP','CATCH_%','YAC','YAC/COMP','40YD','REC','TARGETS','TD','YDS/TA','Broad Jump']] PacY=dfPAC['AVG_YDS_SEASON'] SecY=dfSEC['AVG_YDS_SEASON'] BigY=dfBIG['AVG_YDS_SEASON'] PacZ=dfPAC['YDS_GAME'] BigZ=dfBIG['YDS_GAME'] SecZ=dfSEC['YDS_GAME'] PacJ=dfPAC['MAX_YDS_SEASON'] SecJ=dfSEC['MAX_YDS_SEASON'] BigJ=dfBIG['MAX_YDS_SEASON'] PacK=dfPAC['ROOKIE_YDS_GAME'] SecK=dfSEC['ROOKIE_YDS_GAME'] BigK=dfBIG['ROOKIE_YDS_GAME'] # PacK=dfPAC['ROOKIE_YDS'] # SecK=dfSEC['ROOKIE_YDS'] # BigK=dfBIG['ROOKIE_YDS'] # model=forward_selected(SecX,'ROOKIE_YDS') # print(model) # regrPac = linear_model.LinearRegression() # regrSec=linear_model.LinearRegression() # regrBig=linear_model.LinearRegression() # regPAC=regrPac.fit(PacX, PacK) # regSEC=regrSec.fit(SecX, SecK) # SecX=sm.add_constant(SecX) # regSEC=sm.OLS(SecK,SecX) # regBIG=sm.OLS(BigK,BigX) regPAC=sm.OLS(PacK,PacX) # resultsSEC=regSEC.fit() resultsPAC=regPAC.fit() SecX=SecX.to_numpy() SecY=SecY.to_numpy() model=backwardElimination(SecX,SecY,0.05) print(model) # resultsBIG=regBIG.fit() #model=forward_selected(PacX,'ROOKIE_YDS_GAME') # for i in df_Predict.index: # print(df_Predict['Conference'][i]) # if df_Predict['Conference'][i]=='Southeastern': # print(df_Predict['Player'][i]) # pred=regrSec.predict([[df_Predict['DP'][i],df_Predict['CATCH_P'][i],df_Predict['YAC'][i],df_Predict['YAC_COMP'][i],df_Predict['40YD'][i],df_Predict['REC'][i],df_Predict['TD'][i],df_Predict['YDS/TA'][i],df_Predict['Broad Jump'][i]]]) # if pred<0: # pred=0 # print('Predicted AVG_YDS/SEASON: \n', pred) # if df_Predict['Conference'][i]=='Big': # print(df_Predict['Player'][i]) # print('Predicted AVG_YDS/SEASON: \n', regrBig.predict([[df_Predict['DP'][i],df_Predict['CATCH_P'][i],df_Predict['YAC'][i],df_Predict['YAC_COMP'][i],df_Predict['40YD'][i],df_Predict['REC'][i],df_Predict['TD'][i],df_Predict['YDS/TA'][i],df_Predict['Broad Jump'][i]]])) # if df_Predict['Conference'][i]=='Pac-12': # print(df_Predict['Player'][i]) # pred=regrPac.predict([[df_Predict['DP'][i],df_Predict['CATCH_P'][i],df_Predict['YAC'][i],df_Predict['YAC_COMP'][i],df_Predict['40YD'][i],df_Predict['REC'][i],df_Predict['TD'][i],df_Predict['YDS/TA'][i],df_Predict['Broad Jump'][i]]]) # if pred<0: # pred=0 # print('Predicted AVG_YDS/SEASON: \n', pred) # print (resultsSEC.rsquared_adj) # print(resultsSEC.summary()) #print (resultsPAC.rsquared_adj) # print (resultsBIG.rsquared_adj) # print(model.summary()) #print(model.rsquared_adj) # print('AVG_YDS/GAME\n') #print('Intercept: \n', regrSec.intercept_) #print('Coefficients: \n', regrSec.coef_) #print("R^2: \n",regSEC.score(pcaSecX,SecK)) #print("R^2: \n",regSEC.score(SecX,SecK)) # regPAC=regrPac.fit(PacX, PacZ) # regBIG=regrBig.fit(BigX,BigZ) # regSEC=regrSec.fit(SecX,SecY) # print('YDS/GAME\n') # print('Intercept: \n', regrPac.intercept_) # print('Coefficients: \n', regrPac.coef_) # print("R^2: \n",regPAC.score(PacX,PacZ) ) # regPAC=regrPac.fit(PacX,PacJ)
normal
{ "blob_id": "a903f9c5cae1c2eb2f40dc8ba29f0625a3d34224", "index": 9690, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef forward_selected(data, response):\n \"\"\"Linear model designed by forward selection.\n\n Parameters:\n -----------\n data : pandas DataFrame with all possible predictors and response\n\n response: string, name of response column in data\n\n Returns:\n --------\n model: an \"optimal\" fitted statsmodels linear model\n with an intercept\n selected by forward selection\n evaluated by adjusted R-squared\n \"\"\"\n remaining = set(data.columns)\n remaining.remove(response)\n selected = []\n current_score, best_new_score = 0.0, 0.0\n while remaining and current_score == best_new_score:\n scores_with_candidates = []\n for candidate in remaining:\n formula = '{} ~ {} + 1'.format(response, ' + '.join(selected +\n [candidate]))\n score = smf.ols(formula, data).fit().rsquared_adj\n scores_with_candidates.append((score, candidate))\n scores_with_candidates.sort()\n best_new_score, best_candidate = scores_with_candidates.pop()\n if current_score < best_new_score:\n remaining.remove(best_candidate)\n selected.append(best_candidate)\n current_score = best_new_score\n formula = '{} ~ {} + 1'.format(response, ' + '.join(selected))\n model = smf.ols(formula, data).fit()\n print(selected)\n return model\n\n\n<mask token>\nprint(model)\n", "step-3": "<mask token>\n\n\ndef forward_selected(data, response):\n \"\"\"Linear model designed by forward selection.\n\n Parameters:\n -----------\n data : pandas DataFrame with all possible predictors and response\n\n response: string, name of response column in data\n\n Returns:\n --------\n model: an \"optimal\" fitted statsmodels linear model\n with an intercept\n selected by forward selection\n evaluated by adjusted R-squared\n \"\"\"\n remaining = set(data.columns)\n remaining.remove(response)\n selected = []\n current_score, best_new_score = 0.0, 0.0\n while remaining and current_score == best_new_score:\n scores_with_candidates = []\n for candidate in remaining:\n formula = '{} ~ {} + 1'.format(response, ' + '.join(selected +\n [candidate]))\n score = smf.ols(formula, data).fit().rsquared_adj\n scores_with_candidates.append((score, candidate))\n scores_with_candidates.sort()\n best_new_score, best_candidate = scores_with_candidates.pop()\n if current_score < best_new_score:\n remaining.remove(best_candidate)\n selected.append(best_candidate)\n current_score = best_new_score\n formula = '{} ~ {} + 1'.format(response, ' + '.join(selected))\n model = smf.ols(formula, data).fit()\n print(selected)\n return model\n\n\ndfBIG = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\Big12and10.csv')\ndfSEC = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\SEC.csv')\ndfPAC = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\AtlanticCoast.csv')\ndf_Predict = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\PredictV2.csv')\nSecX = dfSEC[['DP', 'CATCH_P', 'YAC', 'YAC_COMP', 'FORTYYD', 'REC', 'TD',\n 'YDS_TA', 'BroadJump', 'TARGETS', 'ROOKIE_YDS_GAME']]\nBigX = dfBIG[['DP', 'CATCH_P', 'YAC', 'YAC_COMP', 'FORTYYD', 'REC', 'TD',\n 'YDS_TA', 'BroadJump', 'TARGETS', 'ROOKIE_YDS_GAME']]\nPacX = dfPAC[['DP', 'CATCH_P', 'YAC', 'YAC_COMP', 'FORTYYD', 'REC', 'TD',\n 'YDS_TA', 'BroadJump', 'TARGETS']]\nPacY = dfPAC['AVG_YDS_SEASON']\nSecY = dfSEC['AVG_YDS_SEASON']\nBigY = dfBIG['AVG_YDS_SEASON']\nPacZ = dfPAC['YDS_GAME']\nBigZ = dfBIG['YDS_GAME']\nSecZ = dfSEC['YDS_GAME']\nPacJ = dfPAC['MAX_YDS_SEASON']\nSecJ = dfSEC['MAX_YDS_SEASON']\nBigJ = dfBIG['MAX_YDS_SEASON']\nPacK = dfPAC['ROOKIE_YDS_GAME']\nSecK = dfSEC['ROOKIE_YDS_GAME']\nBigK = dfBIG['ROOKIE_YDS_GAME']\nregPAC = sm.OLS(PacK, PacX)\nresultsPAC = regPAC.fit()\nSecX = SecX.to_numpy()\nSecY = SecY.to_numpy()\nmodel = backwardElimination(SecX, SecY, 0.05)\nprint(model)\n", "step-4": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xlrd\nfrom enum import Enum\nfrom sklearn import linear_model\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\n\ndef forward_selected(data, response):\n \"\"\"Linear model designed by forward selection.\n\n Parameters:\n -----------\n data : pandas DataFrame with all possible predictors and response\n\n response: string, name of response column in data\n\n Returns:\n --------\n model: an \"optimal\" fitted statsmodels linear model\n with an intercept\n selected by forward selection\n evaluated by adjusted R-squared\n \"\"\"\n remaining = set(data.columns)\n remaining.remove(response)\n selected = []\n current_score, best_new_score = 0.0, 0.0\n while remaining and current_score == best_new_score:\n scores_with_candidates = []\n for candidate in remaining:\n formula = '{} ~ {} + 1'.format(response, ' + '.join(selected +\n [candidate]))\n score = smf.ols(formula, data).fit().rsquared_adj\n scores_with_candidates.append((score, candidate))\n scores_with_candidates.sort()\n best_new_score, best_candidate = scores_with_candidates.pop()\n if current_score < best_new_score:\n remaining.remove(best_candidate)\n selected.append(best_candidate)\n current_score = best_new_score\n formula = '{} ~ {} + 1'.format(response, ' + '.join(selected))\n model = smf.ols(formula, data).fit()\n print(selected)\n return model\n\n\ndfBIG = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\Big12and10.csv')\ndfSEC = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\SEC.csv')\ndfPAC = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\AtlanticCoast.csv')\ndf_Predict = pd.read_csv('C:\\\\Users\\\\family\\\\Desktop\\\\PredictV2.csv')\nSecX = dfSEC[['DP', 'CATCH_P', 'YAC', 'YAC_COMP', 'FORTYYD', 'REC', 'TD',\n 'YDS_TA', 'BroadJump', 'TARGETS', 'ROOKIE_YDS_GAME']]\nBigX = dfBIG[['DP', 'CATCH_P', 'YAC', 'YAC_COMP', 'FORTYYD', 'REC', 'TD',\n 'YDS_TA', 'BroadJump', 'TARGETS', 'ROOKIE_YDS_GAME']]\nPacX = dfPAC[['DP', 'CATCH_P', 'YAC', 'YAC_COMP', 'FORTYYD', 'REC', 'TD',\n 'YDS_TA', 'BroadJump', 'TARGETS']]\nPacY = dfPAC['AVG_YDS_SEASON']\nSecY = dfSEC['AVG_YDS_SEASON']\nBigY = dfBIG['AVG_YDS_SEASON']\nPacZ = dfPAC['YDS_GAME']\nBigZ = dfBIG['YDS_GAME']\nSecZ = dfSEC['YDS_GAME']\nPacJ = dfPAC['MAX_YDS_SEASON']\nSecJ = dfSEC['MAX_YDS_SEASON']\nBigJ = dfBIG['MAX_YDS_SEASON']\nPacK = dfPAC['ROOKIE_YDS_GAME']\nSecK = dfSEC['ROOKIE_YDS_GAME']\nBigK = dfBIG['ROOKIE_YDS_GAME']\nregPAC = sm.OLS(PacK, PacX)\nresultsPAC = regPAC.fit()\nSecX = SecX.to_numpy()\nSecY = SecY.to_numpy()\nmodel = backwardElimination(SecX, SecY, 0.05)\nprint(model)\n", "step-5": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xlrd\nfrom enum import Enum\nfrom sklearn import linear_model\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\ndef forward_selected(data, response):\n \"\"\"Linear model designed by forward selection.\n\n Parameters:\n -----------\n data : pandas DataFrame with all possible predictors and response\n\n response: string, name of response column in data\n\n Returns:\n --------\n model: an \"optimal\" fitted statsmodels linear model\n with an intercept\n selected by forward selection\n evaluated by adjusted R-squared\n \"\"\"\n remaining = set(data.columns)\n remaining.remove(response)\n selected = []\n current_score, best_new_score = 0.0, 0.0\n while remaining and current_score == best_new_score:\n scores_with_candidates = []\n for candidate in remaining:\n formula = \"{} ~ {} + 1\".format(response,\n ' + '.join(selected + [candidate]))\n score = smf.ols(formula, data).fit().rsquared_adj\n scores_with_candidates.append((score, candidate))\n scores_with_candidates.sort()\n best_new_score, best_candidate = scores_with_candidates.pop()\n if current_score < best_new_score:\n remaining.remove(best_candidate)\n selected.append(best_candidate)\n current_score = best_new_score\n formula = \"{} ~ {} + 1\".format(response,\n ' + '.join(selected))\n model = smf.ols(formula, data).fit()\n\n print(selected)\n return model\n# def backwardElimination(x, y, sl):\n# numVars = len(x[0])\n# for i in range(0, numVars):\n# regressor_OLS = sm.OLS(y, x).fit()\n# maxVar = max(regressor_OLS.pvalues).astype(float)\n# if maxVar > sl:\n# for j in range(0, numVars - i):\n# if (regressor_OLS.pvalues[j].astype(float) == maxVar):\n# x = (x, j, 1)\n# regressor_OLS.summary()\n# return x\n \n\n\n\n\ndfBIG=pd.read_csv(\"C:\\\\Users\\\\family\\\\Desktop\\\\Big12and10.csv\")\ndfSEC=pd.read_csv(\"C:\\\\Users\\\\family\\\\Desktop\\\\SEC.csv\")#- For SEC data\ndfPAC=pd.read_csv(\"C:\\\\Users\\\\family\\\\Desktop\\\\AtlanticCoast.csv\")#- For Atlantic Coast and Pac12\n\ndf_Predict=pd.read_csv(\"C:\\\\Users\\\\family\\\\Desktop\\\\PredictV2.csv\")\n#plt.scatter(dfBIG['DP'],dfBIG['YDS/GAME'])\n \nSecX=dfSEC[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS','ROOKIE_YDS_GAME']]# Works for SEC \nBigX=dfBIG[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS','ROOKIE_YDS_GAME']] #Works for AtlanticCoast/Pac12 and Big 10/12\n#PacX=dfPAC[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS','ROOKIE_YDS_GAME']] #Works for AtlanticCoast/Pac12 and Big 10/12\nPacX=dfPAC[['DP','CATCH_P','YAC','YAC_COMP','FORTYYD','REC','TD','YDS_TA','BroadJump','TARGETS']] #Works for AtlanticCoast/Pac12 and Big 10/12\n\n#PacX=dfPAC[['DP','CATCH_%','40YD','REC','TD','YDS/TA','TARGETS']] #Works for AtlanticCoast/Pac12 and Big 10/12\n\n#PredictSecX=df_Predict[['DP','CATCH_%','YAC','YAC/COMP','40YD','REC','TARGETS','TD','YDS/TA','Broad Jump']]\nPacY=dfPAC['AVG_YDS_SEASON']\nSecY=dfSEC['AVG_YDS_SEASON']\nBigY=dfBIG['AVG_YDS_SEASON']\nPacZ=dfPAC['YDS_GAME']\nBigZ=dfBIG['YDS_GAME']\nSecZ=dfSEC['YDS_GAME']\nPacJ=dfPAC['MAX_YDS_SEASON']\nSecJ=dfSEC['MAX_YDS_SEASON']\nBigJ=dfBIG['MAX_YDS_SEASON']\nPacK=dfPAC['ROOKIE_YDS_GAME']\nSecK=dfSEC['ROOKIE_YDS_GAME']\nBigK=dfBIG['ROOKIE_YDS_GAME']\n# PacK=dfPAC['ROOKIE_YDS']\n# SecK=dfSEC['ROOKIE_YDS']\n# BigK=dfBIG['ROOKIE_YDS']\n# model=forward_selected(SecX,'ROOKIE_YDS')\n# print(model)\n# regrPac = linear_model.LinearRegression()\n# regrSec=linear_model.LinearRegression()\n# regrBig=linear_model.LinearRegression()\n# regPAC=regrPac.fit(PacX, PacK)\n# regSEC=regrSec.fit(SecX, SecK)\n# SecX=sm.add_constant(SecX)\n# regSEC=sm.OLS(SecK,SecX)\n# regBIG=sm.OLS(BigK,BigX)\nregPAC=sm.OLS(PacK,PacX)\n# resultsSEC=regSEC.fit()\nresultsPAC=regPAC.fit()\nSecX=SecX.to_numpy()\nSecY=SecY.to_numpy()\nmodel=backwardElimination(SecX,SecY,0.05)\nprint(model)\n# resultsBIG=regBIG.fit()\n#model=forward_selected(PacX,'ROOKIE_YDS_GAME')\n\n# for i in df_Predict.index:\n# print(df_Predict['Conference'][i])\n# if df_Predict['Conference'][i]=='Southeastern':\n# print(df_Predict['Player'][i])\n# pred=regrSec.predict([[df_Predict['DP'][i],df_Predict['CATCH_P'][i],df_Predict['YAC'][i],df_Predict['YAC_COMP'][i],df_Predict['40YD'][i],df_Predict['REC'][i],df_Predict['TD'][i],df_Predict['YDS/TA'][i],df_Predict['Broad Jump'][i]]])\n# if pred<0:\n# pred=0\n# print('Predicted AVG_YDS/SEASON: \\n', pred)\n# if df_Predict['Conference'][i]=='Big':\n# print(df_Predict['Player'][i])\n# print('Predicted AVG_YDS/SEASON: \\n', regrBig.predict([[df_Predict['DP'][i],df_Predict['CATCH_P'][i],df_Predict['YAC'][i],df_Predict['YAC_COMP'][i],df_Predict['40YD'][i],df_Predict['REC'][i],df_Predict['TD'][i],df_Predict['YDS/TA'][i],df_Predict['Broad Jump'][i]]]))\n# if df_Predict['Conference'][i]=='Pac-12':\n# print(df_Predict['Player'][i])\n# pred=regrPac.predict([[df_Predict['DP'][i],df_Predict['CATCH_P'][i],df_Predict['YAC'][i],df_Predict['YAC_COMP'][i],df_Predict['40YD'][i],df_Predict['REC'][i],df_Predict['TD'][i],df_Predict['YDS/TA'][i],df_Predict['Broad Jump'][i]]])\n# if pred<0:\n# pred=0\n# print('Predicted AVG_YDS/SEASON: \\n', pred)\n\n# print (resultsSEC.rsquared_adj)\n# print(resultsSEC.summary())\n#print (resultsPAC.rsquared_adj)\n# print (resultsBIG.rsquared_adj)\n# print(model.summary())\n#print(model.rsquared_adj)\n# print('AVG_YDS/GAME\\n')\n#print('Intercept: \\n', regrSec.intercept_)\n#print('Coefficients: \\n', regrSec.coef_)\n#print(\"R^2: \\n\",regSEC.score(pcaSecX,SecK))\n#print(\"R^2: \\n\",regSEC.score(SecX,SecK))\n# regPAC=regrPac.fit(PacX, PacZ)\n# regBIG=regrBig.fit(BigX,BigZ)\n# regSEC=regrSec.fit(SecX,SecY)\n# print('YDS/GAME\\n')\n# print('Intercept: \\n', regrPac.intercept_)\n# print('Coefficients: \\n', regrPac.coef_)\n# print(\"R^2: \\n\",regPAC.score(PacX,PacZ) )\n# regPAC=regrPac.fit(PacX,PacJ)\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class RepresentationPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) repLayout = QVBoxLayout() genLayout = QFormLayout() self.winLenEdit = QLineEdit() genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit) self.timeStepEdit = QLineEdit() genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit) self.minFreqEdit = QLineEdit() genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit) self.maxFreqEdit = QLineEdit() genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit) self.numCoresEdit = QLineEdit() genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self .numCoresEdit) repBox = QGroupBox() self.envelopeRadio = QRadioButton('Amplitude envelopes') self.mfccRadio = QRadioButton('MFCCs') self.mhecRadio = QRadioButton('MHECs') self.prosodyRadio = QRadioButton('Prosody') self.formantRadio = QRadioButton('Formants') hbox = QHBoxLayout() hbox.addWidget(self.envelopeRadio) hbox.addWidget(self.mfccRadio) repBox.setLayout(hbox) genLayout.addRow(QLabel('Token representation:'), repBox) genWidget = QGroupBox('General') genWidget.setLayout(genLayout) repLayout.addWidget(genWidget) envLayout = QFormLayout() self.bandEdit = QLineEdit() envLayout.addRow(QLabel('Number of bands:'), self.bandEdit) self.gammatoneCheck = QCheckBox() envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck) self.windowCheck = QCheckBox() envLayout.addRow(QLabel('Windowed:'), self.windowCheck) envWidget = QGroupBox('Amplitude envelopes') envWidget.setLayout(envLayout) repLayout.addWidget(envWidget) mfccLayout = QFormLayout() self.numCCEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit) self.numFiltersEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit) self.powerCheck = QCheckBox() mfccLayout.addRow(QLabel('Use power (first coefficient):'), self. powerCheck) mfccWidget = QGroupBox('MFCC') mfccWidget.setLayout(mfccLayout) repLayout.addWidget(mfccWidget) self.setLayout(repLayout) self.winLenEdit.setText(str(setting_dict['win_len'])) self.timeStepEdit.setText(str(setting_dict['time_step'])) freq_lims = setting_dict['freq_lims'] self.minFreqEdit.setText(str(freq_lims[0])) self.maxFreqEdit.setText(str(freq_lims[1])) self.numCoresEdit.setText(str(setting_dict['num_cores'])) rep = setting_dict['rep'] if rep == 'mfcc': self.mfccRadio.setChecked(True) elif rep == 'mhec': self.mhecRadio.setChecked(True) elif rep == 'prosody': self.prosodyRadio.setChecked(True) elif rep == 'formant': self.formantRadio.setChecked(True) elif rep == 'envelopes': self.envelopeRadio.setChecked(True) self.bandEdit.setText(str(setting_dict['envelope_bands'])) if setting_dict['use_gammatone']: self.gammatoneCheck.setChecked(True) if setting_dict['use_window']: self.windowCheck.setChecked(True) self.numFiltersEdit.setText(str(setting_dict['mfcc_filters'])) self.numCCEdit.setText(str(setting_dict['num_coeffs'])) if setting_dict['use_power']: self.powerCheck.setChecked(True) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.mfccRadio.isChecked(): setting_dict['rep'] = 'mfcc' elif self.mhecRadio.isChecked(): setting_dict['rep'] = 'mhec' elif self.prosodyRadio.isChecked(): setting_dict['rep'] = 'prosody' elif self.formantRadio.isChecked(): setting_dict['rep'] = 'formant' elif self.envelopeRadio.isChecked(): setting_dict['rep'] = 'envelopes' setting_dict['win_len'] = float(self.winLenEdit.text()) setting_dict['time_step'] = float(self.timeStepEdit.text()) setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self. maxFreqEdit.text()) setting_dict['num_cores'] = int(self.numCoresEdit.text()) setting_dict['envelope_bands'] = int(self.bandEdit.text()) setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked()) setting_dict['use_window'] = int(self.windowCheck.isChecked()) setting_dict['num_coeffs'] = int(self.numCCEdit.text()) setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text()) setting_dict['use_power'] = int(self.powerCheck.isChecked()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['rep'] != cur_state['rep']: return True if cur_state['rep'] == 'mfcc': for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs', 'mfcc_filters', 'use_power']: if cur_state[k] != self.prev_state[k]: return True elif cur_state['rep'] == 'envelopes': for k in ['freq_lims', 'envelope_bands', 'use_gammatone', 'use_window']: if cur_state[k] != self.prev_state[k]: return True if cur_state['use_window']: for k in ['win_len', 'time_step']: if cur_state[k] != self.prev_state[k]: return True return False class SpecgramPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) specLayout = QFormLayout() analysisLayout = QFormLayout() self.winLenEdit = QLineEdit() analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit) self.methodCombo = QComboBox() self.methodCombo.addItem('Fourier') analysisLayout.addRow(QLabel('Method:'), self.methodCombo) self.winTypeCombo = QComboBox() self.winTypeCombo.addItem('Square (rectangular)') self.winTypeCombo.addItem('Hamming (raised sine-squared)') self.winTypeCombo.addItem('Bartlett (triangular)') self.winTypeCombo.addItem('Welch (parabolic)') self.winTypeCombo.addItem('Hanning (sine-squared)') self.winTypeCombo.addItem('Gaussian') analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo) analysisWidget = QGroupBox('Analysis') analysisWidget.setLayout(analysisLayout) specLayout.addWidget(analysisWidget) resLayout = QFormLayout() self.freqStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of frequency steps:'), self. freqStepsEdit) self.timeStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit) resWidget = QGroupBox('Frequency and time resolution') resWidget.setLayout(resLayout) specLayout.addWidget(resWidget) viewLayout = QFormLayout() self.autoScaleCheck = QCheckBox() viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck) self.dynamicRangeEdit = QLineEdit() viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit) self.maxEdit = QLineEdit() viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit) self.preEmphAlphaEdit = QLineEdit() viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit) viewWidget = QGroupBox('View settings') viewWidget.setLayout(viewLayout) specLayout.addWidget(viewWidget) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} return setting_dict class Settings(object): key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270, 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': ( 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq', 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength', 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': ( 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20), 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': ( 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4 ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window': ('envelopes/UseWindow', False), 'dist_func': ( 'network/DistanceFunction', 'dtw'), 'cluster_alg': ( 'network/ClusterAlgorithm', 'complete'), 'one_cluster': ( 'network/OneCluster', False), 'threshold': ('network/Threshold', 0), 'spec_win_len': ('spectrogram/WindowLength', 0.005), 'spec_win_type': ('spectrogram/WindowType', 'gaussian'), 'spec_freq_steps': ('spectrogram/FreqSteps', 250), 'spec_time_steps': ('spectrogram/TimeSteps', 1000), 'spec_autoscale': ('spectrogram/Autoscale', True), 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max': ('spectrogram/Maximum', 100), 'spec_alpha': ( 'spectrogram/PreEmphAlpha', 0.97)} rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power', 'num_cores', 'use_gammatone', 'use_window'] asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func'] network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster', 'threshold'] specgram_setting_keys = ['spec_win_len', 'spec_win_type', 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale', 'spec_dynamic_range', 'spec_max', 'spec_alpha'] def __init__(self): self.qs = QSettings('settings.ini', QSettings.IniFormat) self.qs.setFallbacksEnabled(False) def __getitem__(self, key): if key == 'num_filters': if self['rep'] == 'mfcc': return self['mfcc_filters'] elif self['rep'] == 'envelopes': return self['envelope_bands'] mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key) else: inikey, default = mapped_key return type(default)(self.qs.value(inikey, default)) def __setitem__(self, key, value): mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): if not isinstance(value, list) and not isinstance(value, tuple): raise KeyError if len(mapped_key) != len(value): raise KeyError for i, (k, d) in enumerate(mapped_key): self.qs.setValue(k, value[i]) else: inikey, default = mapped_key self.qs.setValue(inikey, value) def update(self, setting_dict): for k, v in setting_dict.items(): self[k] = v def acousticsim_kwarg(self): out = {x: self[x] for x in self.asim_kwarg_keys} out['return_rep'] = True return out def get_rep_settings(self): out = {x: self[x] for x in self.rep_setting_keys} return out def get_network_settings(self): out = {x: self[x] for x in self.network_setting_keys} return out def get_specgram_settings(self): out = {x: self[x] for x in self.specgram_setting_keys} return out class PreferencesDialog(QDialog): def __init__(self, parent, settings): QDialog.__init__(self, parent) self.settings = settings tabWidget = QTabWidget() self.repWidget = RepresentationPane(self.settings.get_rep_settings()) tabWidget.addTab(self.repWidget, 'Representations') self.networkWidget = NetworkPane(self.settings.get_network_settings()) tabWidget.addTab(self.networkWidget, 'Network') self.specWidget = SpecgramPane(self.settings.get_specgram_settings()) tabWidget.addTab(self.specWidget, 'Spectrogram') layout = QVBoxLayout() layout.addWidget(tabWidget) self.acceptButton = QPushButton('Ok') self.cancelButton = QPushButton('Cancel') self.acceptButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) hbox = QHBoxLayout() hbox.addWidget(self.acceptButton) hbox.addWidget(self.cancelButton) ac = QWidget() ac.setLayout(hbox) layout.addWidget(ac) self.setLayout(layout) self.network_changed = False self.rep_changed = False self.specgram_changed = False def accept(self): self.network_changed = self.networkWidget.is_changed() self.rep_changed = self.repWidget.is_changed() self.specgram_changed = self.specWidget.is_changed() self.settings.update(self.networkWidget.get_current_state()) self.settings.update(self.repWidget.get_current_state()) self.settings.update(self.specWidget.get_current_state()) QDialog.accept(self) <|reserved_special_token_1|> <|reserved_special_token_0|> class NetworkPane(BasePane): <|reserved_special_token_0|> def get_current_state(self): setting_dict = {} if self.ccRadio.isChecked(): setting_dict['dist_func'] = 'xcorr' elif self.dctRadio.isChecked(): setting_dict['dist_func'] = 'dct' elif self.dtwRadio.isChecked(): setting_dict['dist_func'] = 'dtw' if self.completeRadio.isChecked(): setting_dict['cluster_alg'] = 'complete' elif self.thresholdRadio.isChecked(): setting_dict['cluster_alg'] = 'threshold' elif self.apRadio.isChecked(): setting_dict['cluster_alg'] = 'affinity' elif self.scRadio.isChecked(): setting_dict['cluster_alg'] = 'spectral' setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked()) setting_dict['threshold'] = float(self.thresholdEdit.text()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['dist_func'] != cur_state['dist_func']: return True return False for k in ['dist_func', 'cluster_alg']: if self.prev_state[k] != cur_state[k]: return True if cur_state['cluster_alg'] == 'threshold': if self.prev_state['threshold'] != cur_state['threshold']: return True elif cur_state['cluster_alg'] in {'affinity', 'spectral'}: if self.prev_state['one_cluster'] != cur_state['one_cluster']: return True return False class RepresentationPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) repLayout = QVBoxLayout() genLayout = QFormLayout() self.winLenEdit = QLineEdit() genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit) self.timeStepEdit = QLineEdit() genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit) self.minFreqEdit = QLineEdit() genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit) self.maxFreqEdit = QLineEdit() genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit) self.numCoresEdit = QLineEdit() genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self .numCoresEdit) repBox = QGroupBox() self.envelopeRadio = QRadioButton('Amplitude envelopes') self.mfccRadio = QRadioButton('MFCCs') self.mhecRadio = QRadioButton('MHECs') self.prosodyRadio = QRadioButton('Prosody') self.formantRadio = QRadioButton('Formants') hbox = QHBoxLayout() hbox.addWidget(self.envelopeRadio) hbox.addWidget(self.mfccRadio) repBox.setLayout(hbox) genLayout.addRow(QLabel('Token representation:'), repBox) genWidget = QGroupBox('General') genWidget.setLayout(genLayout) repLayout.addWidget(genWidget) envLayout = QFormLayout() self.bandEdit = QLineEdit() envLayout.addRow(QLabel('Number of bands:'), self.bandEdit) self.gammatoneCheck = QCheckBox() envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck) self.windowCheck = QCheckBox() envLayout.addRow(QLabel('Windowed:'), self.windowCheck) envWidget = QGroupBox('Amplitude envelopes') envWidget.setLayout(envLayout) repLayout.addWidget(envWidget) mfccLayout = QFormLayout() self.numCCEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit) self.numFiltersEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit) self.powerCheck = QCheckBox() mfccLayout.addRow(QLabel('Use power (first coefficient):'), self. powerCheck) mfccWidget = QGroupBox('MFCC') mfccWidget.setLayout(mfccLayout) repLayout.addWidget(mfccWidget) self.setLayout(repLayout) self.winLenEdit.setText(str(setting_dict['win_len'])) self.timeStepEdit.setText(str(setting_dict['time_step'])) freq_lims = setting_dict['freq_lims'] self.minFreqEdit.setText(str(freq_lims[0])) self.maxFreqEdit.setText(str(freq_lims[1])) self.numCoresEdit.setText(str(setting_dict['num_cores'])) rep = setting_dict['rep'] if rep == 'mfcc': self.mfccRadio.setChecked(True) elif rep == 'mhec': self.mhecRadio.setChecked(True) elif rep == 'prosody': self.prosodyRadio.setChecked(True) elif rep == 'formant': self.formantRadio.setChecked(True) elif rep == 'envelopes': self.envelopeRadio.setChecked(True) self.bandEdit.setText(str(setting_dict['envelope_bands'])) if setting_dict['use_gammatone']: self.gammatoneCheck.setChecked(True) if setting_dict['use_window']: self.windowCheck.setChecked(True) self.numFiltersEdit.setText(str(setting_dict['mfcc_filters'])) self.numCCEdit.setText(str(setting_dict['num_coeffs'])) if setting_dict['use_power']: self.powerCheck.setChecked(True) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.mfccRadio.isChecked(): setting_dict['rep'] = 'mfcc' elif self.mhecRadio.isChecked(): setting_dict['rep'] = 'mhec' elif self.prosodyRadio.isChecked(): setting_dict['rep'] = 'prosody' elif self.formantRadio.isChecked(): setting_dict['rep'] = 'formant' elif self.envelopeRadio.isChecked(): setting_dict['rep'] = 'envelopes' setting_dict['win_len'] = float(self.winLenEdit.text()) setting_dict['time_step'] = float(self.timeStepEdit.text()) setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self. maxFreqEdit.text()) setting_dict['num_cores'] = int(self.numCoresEdit.text()) setting_dict['envelope_bands'] = int(self.bandEdit.text()) setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked()) setting_dict['use_window'] = int(self.windowCheck.isChecked()) setting_dict['num_coeffs'] = int(self.numCCEdit.text()) setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text()) setting_dict['use_power'] = int(self.powerCheck.isChecked()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['rep'] != cur_state['rep']: return True if cur_state['rep'] == 'mfcc': for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs', 'mfcc_filters', 'use_power']: if cur_state[k] != self.prev_state[k]: return True elif cur_state['rep'] == 'envelopes': for k in ['freq_lims', 'envelope_bands', 'use_gammatone', 'use_window']: if cur_state[k] != self.prev_state[k]: return True if cur_state['use_window']: for k in ['win_len', 'time_step']: if cur_state[k] != self.prev_state[k]: return True return False class SpecgramPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) specLayout = QFormLayout() analysisLayout = QFormLayout() self.winLenEdit = QLineEdit() analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit) self.methodCombo = QComboBox() self.methodCombo.addItem('Fourier') analysisLayout.addRow(QLabel('Method:'), self.methodCombo) self.winTypeCombo = QComboBox() self.winTypeCombo.addItem('Square (rectangular)') self.winTypeCombo.addItem('Hamming (raised sine-squared)') self.winTypeCombo.addItem('Bartlett (triangular)') self.winTypeCombo.addItem('Welch (parabolic)') self.winTypeCombo.addItem('Hanning (sine-squared)') self.winTypeCombo.addItem('Gaussian') analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo) analysisWidget = QGroupBox('Analysis') analysisWidget.setLayout(analysisLayout) specLayout.addWidget(analysisWidget) resLayout = QFormLayout() self.freqStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of frequency steps:'), self. freqStepsEdit) self.timeStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit) resWidget = QGroupBox('Frequency and time resolution') resWidget.setLayout(resLayout) specLayout.addWidget(resWidget) viewLayout = QFormLayout() self.autoScaleCheck = QCheckBox() viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck) self.dynamicRangeEdit = QLineEdit() viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit) self.maxEdit = QLineEdit() viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit) self.preEmphAlphaEdit = QLineEdit() viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit) viewWidget = QGroupBox('View settings') viewWidget.setLayout(viewLayout) specLayout.addWidget(viewWidget) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} return setting_dict class Settings(object): key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270, 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': ( 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq', 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength', 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': ( 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20), 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': ( 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4 ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window': ('envelopes/UseWindow', False), 'dist_func': ( 'network/DistanceFunction', 'dtw'), 'cluster_alg': ( 'network/ClusterAlgorithm', 'complete'), 'one_cluster': ( 'network/OneCluster', False), 'threshold': ('network/Threshold', 0), 'spec_win_len': ('spectrogram/WindowLength', 0.005), 'spec_win_type': ('spectrogram/WindowType', 'gaussian'), 'spec_freq_steps': ('spectrogram/FreqSteps', 250), 'spec_time_steps': ('spectrogram/TimeSteps', 1000), 'spec_autoscale': ('spectrogram/Autoscale', True), 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max': ('spectrogram/Maximum', 100), 'spec_alpha': ( 'spectrogram/PreEmphAlpha', 0.97)} rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power', 'num_cores', 'use_gammatone', 'use_window'] asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func'] network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster', 'threshold'] specgram_setting_keys = ['spec_win_len', 'spec_win_type', 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale', 'spec_dynamic_range', 'spec_max', 'spec_alpha'] def __init__(self): self.qs = QSettings('settings.ini', QSettings.IniFormat) self.qs.setFallbacksEnabled(False) def __getitem__(self, key): if key == 'num_filters': if self['rep'] == 'mfcc': return self['mfcc_filters'] elif self['rep'] == 'envelopes': return self['envelope_bands'] mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key) else: inikey, default = mapped_key return type(default)(self.qs.value(inikey, default)) def __setitem__(self, key, value): mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): if not isinstance(value, list) and not isinstance(value, tuple): raise KeyError if len(mapped_key) != len(value): raise KeyError for i, (k, d) in enumerate(mapped_key): self.qs.setValue(k, value[i]) else: inikey, default = mapped_key self.qs.setValue(inikey, value) def update(self, setting_dict): for k, v in setting_dict.items(): self[k] = v def acousticsim_kwarg(self): out = {x: self[x] for x in self.asim_kwarg_keys} out['return_rep'] = True return out def get_rep_settings(self): out = {x: self[x] for x in self.rep_setting_keys} return out def get_network_settings(self): out = {x: self[x] for x in self.network_setting_keys} return out def get_specgram_settings(self): out = {x: self[x] for x in self.specgram_setting_keys} return out class PreferencesDialog(QDialog): def __init__(self, parent, settings): QDialog.__init__(self, parent) self.settings = settings tabWidget = QTabWidget() self.repWidget = RepresentationPane(self.settings.get_rep_settings()) tabWidget.addTab(self.repWidget, 'Representations') self.networkWidget = NetworkPane(self.settings.get_network_settings()) tabWidget.addTab(self.networkWidget, 'Network') self.specWidget = SpecgramPane(self.settings.get_specgram_settings()) tabWidget.addTab(self.specWidget, 'Spectrogram') layout = QVBoxLayout() layout.addWidget(tabWidget) self.acceptButton = QPushButton('Ok') self.cancelButton = QPushButton('Cancel') self.acceptButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) hbox = QHBoxLayout() hbox.addWidget(self.acceptButton) hbox.addWidget(self.cancelButton) ac = QWidget() ac.setLayout(hbox) layout.addWidget(ac) self.setLayout(layout) self.network_changed = False self.rep_changed = False self.specgram_changed = False def accept(self): self.network_changed = self.networkWidget.is_changed() self.rep_changed = self.repWidget.is_changed() self.specgram_changed = self.specWidget.is_changed() self.settings.update(self.networkWidget.get_current_state()) self.settings.update(self.repWidget.get_current_state()) self.settings.update(self.specWidget.get_current_state()) QDialog.accept(self) <|reserved_special_token_1|> <|reserved_special_token_0|> class BasePane(QWidget): <|reserved_special_token_0|> prev_state = {} def get_current_state(self): return None def is_changed(self): return self.get_current_state() != self.prev_state class NetworkPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) networkLayout = QFormLayout() matchAlgorithmBox = QGroupBox() self.ccRadio = QRadioButton('Cross-correlation') self.dtwRadio = QRadioButton('DTW') self.dctRadio = QRadioButton('DCT') hbox = QHBoxLayout() hbox.addWidget(self.ccRadio) hbox.addWidget(self.dtwRadio) hbox.addWidget(self.dctRadio) matchAlgorithmBox.setLayout(hbox) networkLayout.addRow(QLabel('Similarity algorithm:'), matchAlgorithmBox ) clusterBox = QGroupBox() self.completeRadio = QRadioButton('Complete') self.thresholdRadio = QRadioButton('Threshold') self.apRadio = QRadioButton('Affinity propagation') self.scRadio = QRadioButton('Spectral clustering') hbox = QHBoxLayout() hbox.addWidget(self.completeRadio) hbox.addWidget(self.thresholdRadio) hbox.addWidget(self.apRadio) hbox.addWidget(self.scRadio) clusterBox.setLayout(hbox) networkLayout.addRow(QLabel('Cluster algorithm:'), clusterBox) self.oneClusterCheck = QCheckBox() networkLayout.addRow(QLabel('Enforce single cluster:'), self. oneClusterCheck) self.thresholdEdit = QLineEdit() networkLayout.addRow(QLabel('Similarity threshold:'), self. thresholdEdit) self.setLayout(networkLayout) matchAlgorithm = setting_dict['dist_func'] clustAlgorithm = setting_dict['cluster_alg'] oneCluster = setting_dict['one_cluster'] if matchAlgorithm == 'xcorr': self.ccRadio.setChecked(True) elif matchAlgorithm == 'dct': self.dctRadio.setChecked(True) else: self.dtwRadio.setChecked(True) if clustAlgorithm == 'complete': self.completeRadio.setChecked(True) elif clustAlgorithm == 'threshold': self.thresholdRadio.setChecked(True) elif clustAlgorithm == 'affinity': self.apRadio.setChecked(True) elif clustAlgorithm == 'spectral': self.scRadio.setChecked(True) if oneCluster: self.oneClusterCheck.setChecked(True) self.thresholdEdit.setText(str(setting_dict['threshold'])) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.ccRadio.isChecked(): setting_dict['dist_func'] = 'xcorr' elif self.dctRadio.isChecked(): setting_dict['dist_func'] = 'dct' elif self.dtwRadio.isChecked(): setting_dict['dist_func'] = 'dtw' if self.completeRadio.isChecked(): setting_dict['cluster_alg'] = 'complete' elif self.thresholdRadio.isChecked(): setting_dict['cluster_alg'] = 'threshold' elif self.apRadio.isChecked(): setting_dict['cluster_alg'] = 'affinity' elif self.scRadio.isChecked(): setting_dict['cluster_alg'] = 'spectral' setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked()) setting_dict['threshold'] = float(self.thresholdEdit.text()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['dist_func'] != cur_state['dist_func']: return True return False for k in ['dist_func', 'cluster_alg']: if self.prev_state[k] != cur_state[k]: return True if cur_state['cluster_alg'] == 'threshold': if self.prev_state['threshold'] != cur_state['threshold']: return True elif cur_state['cluster_alg'] in {'affinity', 'spectral'}: if self.prev_state['one_cluster'] != cur_state['one_cluster']: return True return False class RepresentationPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) repLayout = QVBoxLayout() genLayout = QFormLayout() self.winLenEdit = QLineEdit() genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit) self.timeStepEdit = QLineEdit() genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit) self.minFreqEdit = QLineEdit() genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit) self.maxFreqEdit = QLineEdit() genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit) self.numCoresEdit = QLineEdit() genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self .numCoresEdit) repBox = QGroupBox() self.envelopeRadio = QRadioButton('Amplitude envelopes') self.mfccRadio = QRadioButton('MFCCs') self.mhecRadio = QRadioButton('MHECs') self.prosodyRadio = QRadioButton('Prosody') self.formantRadio = QRadioButton('Formants') hbox = QHBoxLayout() hbox.addWidget(self.envelopeRadio) hbox.addWidget(self.mfccRadio) repBox.setLayout(hbox) genLayout.addRow(QLabel('Token representation:'), repBox) genWidget = QGroupBox('General') genWidget.setLayout(genLayout) repLayout.addWidget(genWidget) envLayout = QFormLayout() self.bandEdit = QLineEdit() envLayout.addRow(QLabel('Number of bands:'), self.bandEdit) self.gammatoneCheck = QCheckBox() envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck) self.windowCheck = QCheckBox() envLayout.addRow(QLabel('Windowed:'), self.windowCheck) envWidget = QGroupBox('Amplitude envelopes') envWidget.setLayout(envLayout) repLayout.addWidget(envWidget) mfccLayout = QFormLayout() self.numCCEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit) self.numFiltersEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit) self.powerCheck = QCheckBox() mfccLayout.addRow(QLabel('Use power (first coefficient):'), self. powerCheck) mfccWidget = QGroupBox('MFCC') mfccWidget.setLayout(mfccLayout) repLayout.addWidget(mfccWidget) self.setLayout(repLayout) self.winLenEdit.setText(str(setting_dict['win_len'])) self.timeStepEdit.setText(str(setting_dict['time_step'])) freq_lims = setting_dict['freq_lims'] self.minFreqEdit.setText(str(freq_lims[0])) self.maxFreqEdit.setText(str(freq_lims[1])) self.numCoresEdit.setText(str(setting_dict['num_cores'])) rep = setting_dict['rep'] if rep == 'mfcc': self.mfccRadio.setChecked(True) elif rep == 'mhec': self.mhecRadio.setChecked(True) elif rep == 'prosody': self.prosodyRadio.setChecked(True) elif rep == 'formant': self.formantRadio.setChecked(True) elif rep == 'envelopes': self.envelopeRadio.setChecked(True) self.bandEdit.setText(str(setting_dict['envelope_bands'])) if setting_dict['use_gammatone']: self.gammatoneCheck.setChecked(True) if setting_dict['use_window']: self.windowCheck.setChecked(True) self.numFiltersEdit.setText(str(setting_dict['mfcc_filters'])) self.numCCEdit.setText(str(setting_dict['num_coeffs'])) if setting_dict['use_power']: self.powerCheck.setChecked(True) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.mfccRadio.isChecked(): setting_dict['rep'] = 'mfcc' elif self.mhecRadio.isChecked(): setting_dict['rep'] = 'mhec' elif self.prosodyRadio.isChecked(): setting_dict['rep'] = 'prosody' elif self.formantRadio.isChecked(): setting_dict['rep'] = 'formant' elif self.envelopeRadio.isChecked(): setting_dict['rep'] = 'envelopes' setting_dict['win_len'] = float(self.winLenEdit.text()) setting_dict['time_step'] = float(self.timeStepEdit.text()) setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self. maxFreqEdit.text()) setting_dict['num_cores'] = int(self.numCoresEdit.text()) setting_dict['envelope_bands'] = int(self.bandEdit.text()) setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked()) setting_dict['use_window'] = int(self.windowCheck.isChecked()) setting_dict['num_coeffs'] = int(self.numCCEdit.text()) setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text()) setting_dict['use_power'] = int(self.powerCheck.isChecked()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['rep'] != cur_state['rep']: return True if cur_state['rep'] == 'mfcc': for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs', 'mfcc_filters', 'use_power']: if cur_state[k] != self.prev_state[k]: return True elif cur_state['rep'] == 'envelopes': for k in ['freq_lims', 'envelope_bands', 'use_gammatone', 'use_window']: if cur_state[k] != self.prev_state[k]: return True if cur_state['use_window']: for k in ['win_len', 'time_step']: if cur_state[k] != self.prev_state[k]: return True return False class SpecgramPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) specLayout = QFormLayout() analysisLayout = QFormLayout() self.winLenEdit = QLineEdit() analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit) self.methodCombo = QComboBox() self.methodCombo.addItem('Fourier') analysisLayout.addRow(QLabel('Method:'), self.methodCombo) self.winTypeCombo = QComboBox() self.winTypeCombo.addItem('Square (rectangular)') self.winTypeCombo.addItem('Hamming (raised sine-squared)') self.winTypeCombo.addItem('Bartlett (triangular)') self.winTypeCombo.addItem('Welch (parabolic)') self.winTypeCombo.addItem('Hanning (sine-squared)') self.winTypeCombo.addItem('Gaussian') analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo) analysisWidget = QGroupBox('Analysis') analysisWidget.setLayout(analysisLayout) specLayout.addWidget(analysisWidget) resLayout = QFormLayout() self.freqStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of frequency steps:'), self. freqStepsEdit) self.timeStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit) resWidget = QGroupBox('Frequency and time resolution') resWidget.setLayout(resLayout) specLayout.addWidget(resWidget) viewLayout = QFormLayout() self.autoScaleCheck = QCheckBox() viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck) self.dynamicRangeEdit = QLineEdit() viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit) self.maxEdit = QLineEdit() viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit) self.preEmphAlphaEdit = QLineEdit() viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit) viewWidget = QGroupBox('View settings') viewWidget.setLayout(viewLayout) specLayout.addWidget(viewWidget) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} return setting_dict class Settings(object): key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270, 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': ( 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq', 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength', 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': ( 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20), 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': ( 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4 ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window': ('envelopes/UseWindow', False), 'dist_func': ( 'network/DistanceFunction', 'dtw'), 'cluster_alg': ( 'network/ClusterAlgorithm', 'complete'), 'one_cluster': ( 'network/OneCluster', False), 'threshold': ('network/Threshold', 0), 'spec_win_len': ('spectrogram/WindowLength', 0.005), 'spec_win_type': ('spectrogram/WindowType', 'gaussian'), 'spec_freq_steps': ('spectrogram/FreqSteps', 250), 'spec_time_steps': ('spectrogram/TimeSteps', 1000), 'spec_autoscale': ('spectrogram/Autoscale', True), 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max': ('spectrogram/Maximum', 100), 'spec_alpha': ( 'spectrogram/PreEmphAlpha', 0.97)} rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power', 'num_cores', 'use_gammatone', 'use_window'] asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func'] network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster', 'threshold'] specgram_setting_keys = ['spec_win_len', 'spec_win_type', 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale', 'spec_dynamic_range', 'spec_max', 'spec_alpha'] def __init__(self): self.qs = QSettings('settings.ini', QSettings.IniFormat) self.qs.setFallbacksEnabled(False) def __getitem__(self, key): if key == 'num_filters': if self['rep'] == 'mfcc': return self['mfcc_filters'] elif self['rep'] == 'envelopes': return self['envelope_bands'] mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key) else: inikey, default = mapped_key return type(default)(self.qs.value(inikey, default)) def __setitem__(self, key, value): mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): if not isinstance(value, list) and not isinstance(value, tuple): raise KeyError if len(mapped_key) != len(value): raise KeyError for i, (k, d) in enumerate(mapped_key): self.qs.setValue(k, value[i]) else: inikey, default = mapped_key self.qs.setValue(inikey, value) def update(self, setting_dict): for k, v in setting_dict.items(): self[k] = v def acousticsim_kwarg(self): out = {x: self[x] for x in self.asim_kwarg_keys} out['return_rep'] = True return out def get_rep_settings(self): out = {x: self[x] for x in self.rep_setting_keys} return out def get_network_settings(self): out = {x: self[x] for x in self.network_setting_keys} return out def get_specgram_settings(self): out = {x: self[x] for x in self.specgram_setting_keys} return out class PreferencesDialog(QDialog): def __init__(self, parent, settings): QDialog.__init__(self, parent) self.settings = settings tabWidget = QTabWidget() self.repWidget = RepresentationPane(self.settings.get_rep_settings()) tabWidget.addTab(self.repWidget, 'Representations') self.networkWidget = NetworkPane(self.settings.get_network_settings()) tabWidget.addTab(self.networkWidget, 'Network') self.specWidget = SpecgramPane(self.settings.get_specgram_settings()) tabWidget.addTab(self.specWidget, 'Spectrogram') layout = QVBoxLayout() layout.addWidget(tabWidget) self.acceptButton = QPushButton('Ok') self.cancelButton = QPushButton('Cancel') self.acceptButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) hbox = QHBoxLayout() hbox.addWidget(self.acceptButton) hbox.addWidget(self.cancelButton) ac = QWidget() ac.setLayout(hbox) layout.addWidget(ac) self.setLayout(layout) self.network_changed = False self.rep_changed = False self.specgram_changed = False def accept(self): self.network_changed = self.networkWidget.is_changed() self.rep_changed = self.repWidget.is_changed() self.specgram_changed = self.specWidget.is_changed() self.settings.update(self.networkWidget.get_current_state()) self.settings.update(self.repWidget.get_current_state()) self.settings.update(self.specWidget.get_current_state()) QDialog.accept(self) <|reserved_special_token_1|> from PySide.QtCore import qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand, Qt, QTime, QSettings, QSize, QPoint from PySide.QtGui import QBrush, QKeySequence, QColor, QLinearGradient, QPainter, QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene, QGraphicsView, QStyle, QMainWindow, QAction, QDialog, QDockWidget, QHBoxLayout, QWidget, QFileDialog, QListWidget, QMessageBox, QTableWidget, QTableWidgetItem, QDialog, QItemSelectionModel, QPushButton, QLabel, QTabWidget, QGroupBox, QRadioButton, QVBoxLayout, QLineEdit, QFormLayout, QCheckBox, QFont, QSound, QComboBox class BasePane(QWidget): """Abstract, don't use""" prev_state = {} def get_current_state(self): return None def is_changed(self): return self.get_current_state() != self.prev_state class NetworkPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) networkLayout = QFormLayout() matchAlgorithmBox = QGroupBox() self.ccRadio = QRadioButton('Cross-correlation') self.dtwRadio = QRadioButton('DTW') self.dctRadio = QRadioButton('DCT') hbox = QHBoxLayout() hbox.addWidget(self.ccRadio) hbox.addWidget(self.dtwRadio) hbox.addWidget(self.dctRadio) matchAlgorithmBox.setLayout(hbox) networkLayout.addRow(QLabel('Similarity algorithm:'), matchAlgorithmBox ) clusterBox = QGroupBox() self.completeRadio = QRadioButton('Complete') self.thresholdRadio = QRadioButton('Threshold') self.apRadio = QRadioButton('Affinity propagation') self.scRadio = QRadioButton('Spectral clustering') hbox = QHBoxLayout() hbox.addWidget(self.completeRadio) hbox.addWidget(self.thresholdRadio) hbox.addWidget(self.apRadio) hbox.addWidget(self.scRadio) clusterBox.setLayout(hbox) networkLayout.addRow(QLabel('Cluster algorithm:'), clusterBox) self.oneClusterCheck = QCheckBox() networkLayout.addRow(QLabel('Enforce single cluster:'), self. oneClusterCheck) self.thresholdEdit = QLineEdit() networkLayout.addRow(QLabel('Similarity threshold:'), self. thresholdEdit) self.setLayout(networkLayout) matchAlgorithm = setting_dict['dist_func'] clustAlgorithm = setting_dict['cluster_alg'] oneCluster = setting_dict['one_cluster'] if matchAlgorithm == 'xcorr': self.ccRadio.setChecked(True) elif matchAlgorithm == 'dct': self.dctRadio.setChecked(True) else: self.dtwRadio.setChecked(True) if clustAlgorithm == 'complete': self.completeRadio.setChecked(True) elif clustAlgorithm == 'threshold': self.thresholdRadio.setChecked(True) elif clustAlgorithm == 'affinity': self.apRadio.setChecked(True) elif clustAlgorithm == 'spectral': self.scRadio.setChecked(True) if oneCluster: self.oneClusterCheck.setChecked(True) self.thresholdEdit.setText(str(setting_dict['threshold'])) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.ccRadio.isChecked(): setting_dict['dist_func'] = 'xcorr' elif self.dctRadio.isChecked(): setting_dict['dist_func'] = 'dct' elif self.dtwRadio.isChecked(): setting_dict['dist_func'] = 'dtw' if self.completeRadio.isChecked(): setting_dict['cluster_alg'] = 'complete' elif self.thresholdRadio.isChecked(): setting_dict['cluster_alg'] = 'threshold' elif self.apRadio.isChecked(): setting_dict['cluster_alg'] = 'affinity' elif self.scRadio.isChecked(): setting_dict['cluster_alg'] = 'spectral' setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked()) setting_dict['threshold'] = float(self.thresholdEdit.text()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['dist_func'] != cur_state['dist_func']: return True return False for k in ['dist_func', 'cluster_alg']: if self.prev_state[k] != cur_state[k]: return True if cur_state['cluster_alg'] == 'threshold': if self.prev_state['threshold'] != cur_state['threshold']: return True elif cur_state['cluster_alg'] in {'affinity', 'spectral'}: if self.prev_state['one_cluster'] != cur_state['one_cluster']: return True return False class RepresentationPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) repLayout = QVBoxLayout() genLayout = QFormLayout() self.winLenEdit = QLineEdit() genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit) self.timeStepEdit = QLineEdit() genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit) self.minFreqEdit = QLineEdit() genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit) self.maxFreqEdit = QLineEdit() genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit) self.numCoresEdit = QLineEdit() genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self .numCoresEdit) repBox = QGroupBox() self.envelopeRadio = QRadioButton('Amplitude envelopes') self.mfccRadio = QRadioButton('MFCCs') self.mhecRadio = QRadioButton('MHECs') self.prosodyRadio = QRadioButton('Prosody') self.formantRadio = QRadioButton('Formants') hbox = QHBoxLayout() hbox.addWidget(self.envelopeRadio) hbox.addWidget(self.mfccRadio) repBox.setLayout(hbox) genLayout.addRow(QLabel('Token representation:'), repBox) genWidget = QGroupBox('General') genWidget.setLayout(genLayout) repLayout.addWidget(genWidget) envLayout = QFormLayout() self.bandEdit = QLineEdit() envLayout.addRow(QLabel('Number of bands:'), self.bandEdit) self.gammatoneCheck = QCheckBox() envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck) self.windowCheck = QCheckBox() envLayout.addRow(QLabel('Windowed:'), self.windowCheck) envWidget = QGroupBox('Amplitude envelopes') envWidget.setLayout(envLayout) repLayout.addWidget(envWidget) mfccLayout = QFormLayout() self.numCCEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit) self.numFiltersEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit) self.powerCheck = QCheckBox() mfccLayout.addRow(QLabel('Use power (first coefficient):'), self. powerCheck) mfccWidget = QGroupBox('MFCC') mfccWidget.setLayout(mfccLayout) repLayout.addWidget(mfccWidget) self.setLayout(repLayout) self.winLenEdit.setText(str(setting_dict['win_len'])) self.timeStepEdit.setText(str(setting_dict['time_step'])) freq_lims = setting_dict['freq_lims'] self.minFreqEdit.setText(str(freq_lims[0])) self.maxFreqEdit.setText(str(freq_lims[1])) self.numCoresEdit.setText(str(setting_dict['num_cores'])) rep = setting_dict['rep'] if rep == 'mfcc': self.mfccRadio.setChecked(True) elif rep == 'mhec': self.mhecRadio.setChecked(True) elif rep == 'prosody': self.prosodyRadio.setChecked(True) elif rep == 'formant': self.formantRadio.setChecked(True) elif rep == 'envelopes': self.envelopeRadio.setChecked(True) self.bandEdit.setText(str(setting_dict['envelope_bands'])) if setting_dict['use_gammatone']: self.gammatoneCheck.setChecked(True) if setting_dict['use_window']: self.windowCheck.setChecked(True) self.numFiltersEdit.setText(str(setting_dict['mfcc_filters'])) self.numCCEdit.setText(str(setting_dict['num_coeffs'])) if setting_dict['use_power']: self.powerCheck.setChecked(True) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.mfccRadio.isChecked(): setting_dict['rep'] = 'mfcc' elif self.mhecRadio.isChecked(): setting_dict['rep'] = 'mhec' elif self.prosodyRadio.isChecked(): setting_dict['rep'] = 'prosody' elif self.formantRadio.isChecked(): setting_dict['rep'] = 'formant' elif self.envelopeRadio.isChecked(): setting_dict['rep'] = 'envelopes' setting_dict['win_len'] = float(self.winLenEdit.text()) setting_dict['time_step'] = float(self.timeStepEdit.text()) setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self. maxFreqEdit.text()) setting_dict['num_cores'] = int(self.numCoresEdit.text()) setting_dict['envelope_bands'] = int(self.bandEdit.text()) setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked()) setting_dict['use_window'] = int(self.windowCheck.isChecked()) setting_dict['num_coeffs'] = int(self.numCCEdit.text()) setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text()) setting_dict['use_power'] = int(self.powerCheck.isChecked()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['rep'] != cur_state['rep']: return True if cur_state['rep'] == 'mfcc': for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs', 'mfcc_filters', 'use_power']: if cur_state[k] != self.prev_state[k]: return True elif cur_state['rep'] == 'envelopes': for k in ['freq_lims', 'envelope_bands', 'use_gammatone', 'use_window']: if cur_state[k] != self.prev_state[k]: return True if cur_state['use_window']: for k in ['win_len', 'time_step']: if cur_state[k] != self.prev_state[k]: return True return False class SpecgramPane(BasePane): def __init__(self, setting_dict): BasePane.__init__(self) specLayout = QFormLayout() analysisLayout = QFormLayout() self.winLenEdit = QLineEdit() analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit) self.methodCombo = QComboBox() self.methodCombo.addItem('Fourier') analysisLayout.addRow(QLabel('Method:'), self.methodCombo) self.winTypeCombo = QComboBox() self.winTypeCombo.addItem('Square (rectangular)') self.winTypeCombo.addItem('Hamming (raised sine-squared)') self.winTypeCombo.addItem('Bartlett (triangular)') self.winTypeCombo.addItem('Welch (parabolic)') self.winTypeCombo.addItem('Hanning (sine-squared)') self.winTypeCombo.addItem('Gaussian') analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo) analysisWidget = QGroupBox('Analysis') analysisWidget.setLayout(analysisLayout) specLayout.addWidget(analysisWidget) resLayout = QFormLayout() self.freqStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of frequency steps:'), self. freqStepsEdit) self.timeStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit) resWidget = QGroupBox('Frequency and time resolution') resWidget.setLayout(resLayout) specLayout.addWidget(resWidget) viewLayout = QFormLayout() self.autoScaleCheck = QCheckBox() viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck) self.dynamicRangeEdit = QLineEdit() viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit) self.maxEdit = QLineEdit() viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit) self.preEmphAlphaEdit = QLineEdit() viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit) viewWidget = QGroupBox('View settings') viewWidget.setLayout(viewLayout) specLayout.addWidget(viewWidget) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} return setting_dict class Settings(object): key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270, 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': ( 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq', 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength', 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': ( 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20), 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': ( 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4 ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window': ('envelopes/UseWindow', False), 'dist_func': ( 'network/DistanceFunction', 'dtw'), 'cluster_alg': ( 'network/ClusterAlgorithm', 'complete'), 'one_cluster': ( 'network/OneCluster', False), 'threshold': ('network/Threshold', 0), 'spec_win_len': ('spectrogram/WindowLength', 0.005), 'spec_win_type': ('spectrogram/WindowType', 'gaussian'), 'spec_freq_steps': ('spectrogram/FreqSteps', 250), 'spec_time_steps': ('spectrogram/TimeSteps', 1000), 'spec_autoscale': ('spectrogram/Autoscale', True), 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max': ('spectrogram/Maximum', 100), 'spec_alpha': ( 'spectrogram/PreEmphAlpha', 0.97)} rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power', 'num_cores', 'use_gammatone', 'use_window'] asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step', 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func'] network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster', 'threshold'] specgram_setting_keys = ['spec_win_len', 'spec_win_type', 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale', 'spec_dynamic_range', 'spec_max', 'spec_alpha'] def __init__(self): self.qs = QSettings('settings.ini', QSettings.IniFormat) self.qs.setFallbacksEnabled(False) def __getitem__(self, key): if key == 'num_filters': if self['rep'] == 'mfcc': return self['mfcc_filters'] elif self['rep'] == 'envelopes': return self['envelope_bands'] mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key) else: inikey, default = mapped_key return type(default)(self.qs.value(inikey, default)) def __setitem__(self, key, value): mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): if not isinstance(value, list) and not isinstance(value, tuple): raise KeyError if len(mapped_key) != len(value): raise KeyError for i, (k, d) in enumerate(mapped_key): self.qs.setValue(k, value[i]) else: inikey, default = mapped_key self.qs.setValue(inikey, value) def update(self, setting_dict): for k, v in setting_dict.items(): self[k] = v def acousticsim_kwarg(self): out = {x: self[x] for x in self.asim_kwarg_keys} out['return_rep'] = True return out def get_rep_settings(self): out = {x: self[x] for x in self.rep_setting_keys} return out def get_network_settings(self): out = {x: self[x] for x in self.network_setting_keys} return out def get_specgram_settings(self): out = {x: self[x] for x in self.specgram_setting_keys} return out class PreferencesDialog(QDialog): def __init__(self, parent, settings): QDialog.__init__(self, parent) self.settings = settings tabWidget = QTabWidget() self.repWidget = RepresentationPane(self.settings.get_rep_settings()) tabWidget.addTab(self.repWidget, 'Representations') self.networkWidget = NetworkPane(self.settings.get_network_settings()) tabWidget.addTab(self.networkWidget, 'Network') self.specWidget = SpecgramPane(self.settings.get_specgram_settings()) tabWidget.addTab(self.specWidget, 'Spectrogram') layout = QVBoxLayout() layout.addWidget(tabWidget) self.acceptButton = QPushButton('Ok') self.cancelButton = QPushButton('Cancel') self.acceptButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) hbox = QHBoxLayout() hbox.addWidget(self.acceptButton) hbox.addWidget(self.cancelButton) ac = QWidget() ac.setLayout(hbox) layout.addWidget(ac) self.setLayout(layout) self.network_changed = False self.rep_changed = False self.specgram_changed = False def accept(self): self.network_changed = self.networkWidget.is_changed() self.rep_changed = self.repWidget.is_changed() self.specgram_changed = self.specWidget.is_changed() self.settings.update(self.networkWidget.get_current_state()) self.settings.update(self.repWidget.get_current_state()) self.settings.update(self.specWidget.get_current_state()) QDialog.accept(self) <|reserved_special_token_1|> from PySide.QtCore import (qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand, Qt, QTime,QSettings,QSize,QPoint) from PySide.QtGui import (QBrush, QKeySequence, QColor, QLinearGradient, QPainter, QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene, QGraphicsView, QStyle,QMainWindow, QAction, QDialog, QDockWidget, QHBoxLayout, QWidget, QFileDialog, QListWidget, QMessageBox,QTableWidget,QTableWidgetItem,QDialog,QItemSelectionModel, QPushButton,QLabel,QTabWidget,QGroupBox, QRadioButton,QVBoxLayout,QLineEdit,QFormLayout, QCheckBox,QFont,QSound, QComboBox) class BasePane(QWidget): """Abstract, don't use""" prev_state = {} def get_current_state(self): return None def is_changed(self): return self.get_current_state() != self.prev_state class NetworkPane(BasePane): def __init__(self, setting_dict): BasePane.__init__( self ) networkLayout = QFormLayout() matchAlgorithmBox = QGroupBox() self.ccRadio = QRadioButton('Cross-correlation') self.dtwRadio = QRadioButton('DTW') self.dctRadio = QRadioButton('DCT') hbox = QHBoxLayout() hbox.addWidget(self.ccRadio) hbox.addWidget(self.dtwRadio) hbox.addWidget(self.dctRadio) matchAlgorithmBox.setLayout(hbox) networkLayout.addRow(QLabel('Similarity algorithm:'),matchAlgorithmBox) clusterBox = QGroupBox() self.completeRadio = QRadioButton('Complete') self.thresholdRadio = QRadioButton('Threshold') self.apRadio = QRadioButton('Affinity propagation') self.scRadio = QRadioButton('Spectral clustering') hbox = QHBoxLayout() hbox.addWidget(self.completeRadio) hbox.addWidget(self.thresholdRadio) hbox.addWidget(self.apRadio) hbox.addWidget(self.scRadio) clusterBox.setLayout(hbox) networkLayout.addRow(QLabel('Cluster algorithm:'),clusterBox) self.oneClusterCheck = QCheckBox() networkLayout.addRow(QLabel('Enforce single cluster:'),self.oneClusterCheck) self.thresholdEdit = QLineEdit() networkLayout.addRow(QLabel('Similarity threshold:'),self.thresholdEdit) self.setLayout(networkLayout) #set up defaults matchAlgorithm = setting_dict['dist_func'] clustAlgorithm = setting_dict['cluster_alg'] oneCluster = setting_dict['one_cluster'] if matchAlgorithm == 'xcorr': self.ccRadio.setChecked(True) elif matchAlgorithm == 'dct': self.dctRadio.setChecked(True) else: self.dtwRadio.setChecked(True) if clustAlgorithm == 'complete': self.completeRadio.setChecked(True) elif clustAlgorithm == 'threshold': self.thresholdRadio.setChecked(True) elif clustAlgorithm == 'affinity': self.apRadio.setChecked(True) elif clustAlgorithm == 'spectral': self.scRadio.setChecked(True) if oneCluster: self.oneClusterCheck.setChecked(True) self.thresholdEdit.setText(str(setting_dict['threshold'])) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.ccRadio.isChecked(): setting_dict['dist_func'] = 'xcorr' elif self.dctRadio.isChecked(): setting_dict['dist_func'] = 'dct' elif self.dtwRadio.isChecked(): setting_dict['dist_func'] = 'dtw' if self.completeRadio.isChecked(): setting_dict['cluster_alg'] = 'complete' elif self.thresholdRadio.isChecked(): setting_dict['cluster_alg'] = 'threshold' elif self.apRadio.isChecked(): setting_dict['cluster_alg'] = 'affinity' elif self.scRadio.isChecked(): setting_dict['cluster_alg'] = 'spectral' setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked()) setting_dict['threshold'] = float(self.thresholdEdit.text()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['dist_func'] != cur_state['dist_func']: return True return False for k in ['dist_func','cluster_alg']: if self.prev_state[k] != cur_state[k]: return True if cur_state['cluster_alg'] == 'threshold': if self.prev_state['threshold'] != cur_state['threshold']: return True elif cur_state['cluster_alg'] in {'affinity','spectral'}: if self.prev_state['one_cluster'] != cur_state['one_cluster']: return True return False class RepresentationPane(BasePane): def __init__(self, setting_dict): BasePane.__init__( self ) repLayout = QVBoxLayout() genLayout = QFormLayout() self.winLenEdit = QLineEdit() genLayout.addRow(QLabel('Window length (s):'),self.winLenEdit) self.timeStepEdit = QLineEdit() genLayout.addRow(QLabel('Time step (s):'),self.timeStepEdit) self.minFreqEdit = QLineEdit() genLayout.addRow(QLabel('Minimum frequency (Hz):'),self.minFreqEdit) self.maxFreqEdit = QLineEdit() genLayout.addRow(QLabel('Maximum frequency (Hz):'),self.maxFreqEdit) self.numCoresEdit = QLineEdit() genLayout.addRow(QLabel('Number of cores (multiprocessing):'),self.numCoresEdit) repBox = QGroupBox() self.envelopeRadio = QRadioButton('Amplitude envelopes') self.mfccRadio = QRadioButton('MFCCs') self.mhecRadio = QRadioButton('MHECs') self.prosodyRadio = QRadioButton('Prosody') self.formantRadio = QRadioButton('Formants') hbox = QHBoxLayout() hbox.addWidget(self.envelopeRadio) hbox.addWidget(self.mfccRadio) #hbox.addWidget(self.mhecRadio) #hbox.addWidget(self.prosodyRadio) #hbox.addWidget(self.formantRadio) repBox.setLayout(hbox) genLayout.addRow(QLabel('Token representation:'),repBox) genWidget = QGroupBox('General') genWidget.setLayout(genLayout) repLayout.addWidget(genWidget) envLayout = QFormLayout() self.bandEdit = QLineEdit() envLayout.addRow(QLabel('Number of bands:'),self.bandEdit) self.gammatoneCheck = QCheckBox() envLayout.addRow(QLabel('Gammatone:'),self.gammatoneCheck) self.windowCheck = QCheckBox() envLayout.addRow(QLabel('Windowed:'),self.windowCheck) envWidget = QGroupBox('Amplitude envelopes') envWidget.setLayout(envLayout) repLayout.addWidget(envWidget) mfccLayout = QFormLayout() self.numCCEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of coefficents:'),self.numCCEdit) self.numFiltersEdit = QLineEdit() mfccLayout.addRow(QLabel('Number of filters:'),self.numFiltersEdit) self.powerCheck = QCheckBox() mfccLayout.addRow(QLabel('Use power (first coefficient):'),self.powerCheck) mfccWidget = QGroupBox('MFCC') mfccWidget.setLayout(mfccLayout) repLayout.addWidget(mfccWidget) self.setLayout(repLayout) self.winLenEdit.setText(str(setting_dict['win_len'])) self.timeStepEdit.setText(str(setting_dict['time_step'])) freq_lims = setting_dict['freq_lims'] self.minFreqEdit.setText(str(freq_lims[0])) self.maxFreqEdit.setText(str(freq_lims[1])) self.numCoresEdit.setText(str(setting_dict['num_cores'])) rep = setting_dict['rep'] if rep == 'mfcc': self.mfccRadio.setChecked(True) elif rep == 'mhec': self.mhecRadio.setChecked(True) elif rep == 'prosody': self.prosodyRadio.setChecked(True) elif rep == 'formant': self.formantRadio.setChecked(True) elif rep == 'envelopes': self.envelopeRadio.setChecked(True) self.bandEdit.setText(str(setting_dict['envelope_bands'])) if setting_dict['use_gammatone']: self.gammatoneCheck.setChecked(True) if setting_dict['use_window']: self.windowCheck.setChecked(True) self.numFiltersEdit.setText(str(setting_dict['mfcc_filters'])) self.numCCEdit.setText(str(setting_dict['num_coeffs'])) if setting_dict['use_power']: self.powerCheck.setChecked(True) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} if self.mfccRadio.isChecked(): setting_dict['rep'] = 'mfcc' elif self.mhecRadio.isChecked(): setting_dict['rep'] = 'mhec' elif self.prosodyRadio.isChecked(): setting_dict['rep'] = 'prosody' elif self.formantRadio.isChecked(): setting_dict['rep'] = 'formant' elif self.envelopeRadio.isChecked(): setting_dict['rep'] = 'envelopes' setting_dict['win_len'] = float(self.winLenEdit.text()) setting_dict['time_step'] = float(self.timeStepEdit.text()) setting_dict['freq_lims'] = (int(self.minFreqEdit.text()), int(self.maxFreqEdit.text())) setting_dict['num_cores'] = int(self.numCoresEdit.text()) setting_dict['envelope_bands'] = int(self.bandEdit.text()) setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked()) setting_dict['use_window'] = int(self.windowCheck.isChecked()) setting_dict['num_coeffs'] = int(self.numCCEdit.text()) setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text()) setting_dict['use_power'] = int(self.powerCheck.isChecked()) return setting_dict def is_changed(self): cur_state = self.get_current_state() if self.prev_state['rep'] != cur_state['rep']: return True if cur_state['rep'] == 'mfcc': for k in ['win_len','time_step','freq_lims', 'num_coeffs','mfcc_filters','use_power']: if cur_state[k] != self.prev_state[k]: return True elif cur_state['rep'] == 'envelopes': for k in ['freq_lims','envelope_bands', 'use_gammatone', 'use_window']: if cur_state[k] != self.prev_state[k]: return True if cur_state['use_window']: for k in ['win_len','time_step']: if cur_state[k] != self.prev_state[k]: return True return False class SpecgramPane(BasePane): def __init__(self, setting_dict): BasePane.__init__( self ) specLayout = QFormLayout() analysisLayout = QFormLayout() self.winLenEdit = QLineEdit() analysisLayout.addRow(QLabel('Window length:'),self.winLenEdit) self.methodCombo = QComboBox() self.methodCombo.addItem("Fourier") analysisLayout.addRow(QLabel('Method:'),self.methodCombo) self.winTypeCombo = QComboBox() self.winTypeCombo.addItem("Square (rectangular)") self.winTypeCombo.addItem("Hamming (raised sine-squared)") self.winTypeCombo.addItem("Bartlett (triangular)") self.winTypeCombo.addItem("Welch (parabolic)") self.winTypeCombo.addItem("Hanning (sine-squared)") self.winTypeCombo.addItem("Gaussian") analysisLayout.addRow(QLabel('Window type:'),self.winTypeCombo) analysisWidget = QGroupBox('Analysis') analysisWidget.setLayout(analysisLayout) specLayout.addWidget(analysisWidget) resLayout = QFormLayout() self.freqStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of frequency steps:'),self.freqStepsEdit) self.timeStepsEdit = QLineEdit() resLayout.addRow(QLabel('Number of time steps:'),self.timeStepsEdit) resWidget = QGroupBox('Frequency and time resolution') resWidget.setLayout(resLayout) specLayout.addWidget(resWidget) viewLayout = QFormLayout() self.autoScaleCheck = QCheckBox() viewLayout.addRow(QLabel('Autoscale:'),self.autoScaleCheck) self.dynamicRangeEdit = QLineEdit() viewLayout.addRow(QLabel('Dynamic range (dB):'),self.dynamicRangeEdit) self.maxEdit = QLineEdit() viewLayout.addRow(QLabel('Maximum (dB/Hz):'),self.maxEdit) self.preEmphAlphaEdit = QLineEdit() viewLayout.addRow(QLabel('Pre-emphasis alpha:'),self.preEmphAlphaEdit) viewWidget = QGroupBox('View settings') viewWidget.setLayout(viewLayout) specLayout.addWidget(viewWidget) self.prev_state = setting_dict def get_current_state(self): setting_dict = {} return setting_dict class Settings(object): key_to_ini = {'path': ('general/path',''), 'size':('size', QSize(270, 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': ('general/Representation','mfcc'), 'freq_lims': [('general/MinFreq',80),('general/MaxFreq',7800)], 'win_len': ('general/WindowLength',0.025), 'time_step': ('general/TimeStep',0.01), 'num_cores': ('general/NumCores',1), 'num_coeffs': ('mfcc/NumCC',20), 'mfcc_filters': ('mfcc/NumFilters',26), 'use_power': ('mfcc/UsePower',False), 'envelope_bands': ('envelopes/NumBands',4), 'use_gammatone': ('envelopes/UseGammatone',False), 'use_window': ('envelopes/UseWindow',False), 'dist_func': ('network/DistanceFunction','dtw'), 'cluster_alg': ('network/ClusterAlgorithm','complete'), 'one_cluster': ('network/OneCluster',False), 'threshold': ('network/Threshold',0), 'spec_win_len':('spectrogram/WindowLength',0.005), 'spec_win_type':('spectrogram/WindowType','gaussian'), 'spec_freq_steps':('spectrogram/FreqSteps',250), 'spec_time_steps':('spectrogram/TimeSteps',1000), 'spec_autoscale':('spectrogram/Autoscale',True), 'spec_dynamic_range':('spectrogram/DynamicRange',70), 'spec_max':('spectrogram/Maximum',100), 'spec_alpha':('spectrogram/PreEmphAlpha',0.97)} rep_setting_keys = ['rep','freq_lims','win_len','time_step','num_coeffs', 'mfcc_filters','envelope_bands','use_power','num_cores', 'use_gammatone', 'use_window'] asim_kwarg_keys = ['rep','freq_lims','win_len','time_step','num_coeffs', 'num_filters','use_power','num_cores','dist_func'] network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster', 'threshold'] specgram_setting_keys = ['spec_win_len','spec_win_type','spec_freq_steps', 'spec_time_steps','spec_autoscale', 'spec_dynamic_range', 'spec_max','spec_alpha'] def __init__(self): self.qs = QSettings('settings.ini',QSettings.IniFormat) self.qs.setFallbacksEnabled(False) def __getitem__(self, key): if key == 'num_filters': if self['rep'] == 'mfcc': return self['mfcc_filters'] elif self['rep'] == 'envelopes': return self['envelope_bands'] mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): return tuple(type(d)(self.qs.value(k,d)) for k, d in mapped_key) else: inikey, default = mapped_key return type(default)(self.qs.value(inikey,default)) def __setitem__(self, key, value): mapped_key = self.key_to_ini[key] if isinstance(mapped_key, list): if not isinstance(value,list) and not isinstance(value,tuple): raise(KeyError) if len(mapped_key) != len(value): raise(KeyError) for i,(k, d) in enumerate(mapped_key): self.qs.setValue(k,value[i]) else: inikey, default = mapped_key self.qs.setValue(inikey,value) def update(self,setting_dict): for k,v in setting_dict.items(): self[k] = v def acousticsim_kwarg(self): out = {x: self[x] for x in self.asim_kwarg_keys} out['return_rep'] = True return out def get_rep_settings(self): out = {x: self[x] for x in self.rep_setting_keys} return out def get_network_settings(self): out = {x: self[x] for x in self.network_setting_keys} return out def get_specgram_settings(self): out = {x: self[x] for x in self.specgram_setting_keys} return out class PreferencesDialog(QDialog): def __init__(self, parent, settings): QDialog.__init__( self, parent ) self.settings = settings tabWidget = QTabWidget() #Representations self.repWidget = RepresentationPane(self.settings.get_rep_settings()) tabWidget.addTab(self.repWidget,'Representations') #Network Tab self.networkWidget = NetworkPane(self.settings.get_network_settings()) tabWidget.addTab(self.networkWidget, 'Network') self.specWidget = SpecgramPane(self.settings.get_specgram_settings()) tabWidget.addTab(self.specWidget,'Spectrogram') layout = QVBoxLayout() layout.addWidget(tabWidget) #Accept cancel self.acceptButton = QPushButton('Ok') self.cancelButton = QPushButton('Cancel') self.acceptButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) hbox = QHBoxLayout() hbox.addWidget(self.acceptButton) hbox.addWidget(self.cancelButton) ac = QWidget() ac.setLayout(hbox) layout.addWidget(ac) self.setLayout(layout) self.network_changed = False self.rep_changed = False self.specgram_changed = False def accept(self): self.network_changed = self.networkWidget.is_changed() self.rep_changed = self.repWidget.is_changed() self.specgram_changed = self.specWidget.is_changed() self.settings.update(self.networkWidget.get_current_state()) self.settings.update(self.repWidget.get_current_state()) self.settings.update(self.specWidget.get_current_state()) QDialog.accept(self)
flexible
{ "blob_id": "88a3c3fad9717675ed13bcbc778d635f6552c4b1", "index": 8215, "step-1": "<mask token>\n\n\nclass RepresentationPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n repLayout = QVBoxLayout()\n genLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit)\n self.timeStepEdit = QLineEdit()\n genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit)\n self.minFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit)\n self.maxFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit)\n self.numCoresEdit = QLineEdit()\n genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self\n .numCoresEdit)\n repBox = QGroupBox()\n self.envelopeRadio = QRadioButton('Amplitude envelopes')\n self.mfccRadio = QRadioButton('MFCCs')\n self.mhecRadio = QRadioButton('MHECs')\n self.prosodyRadio = QRadioButton('Prosody')\n self.formantRadio = QRadioButton('Formants')\n hbox = QHBoxLayout()\n hbox.addWidget(self.envelopeRadio)\n hbox.addWidget(self.mfccRadio)\n repBox.setLayout(hbox)\n genLayout.addRow(QLabel('Token representation:'), repBox)\n genWidget = QGroupBox('General')\n genWidget.setLayout(genLayout)\n repLayout.addWidget(genWidget)\n envLayout = QFormLayout()\n self.bandEdit = QLineEdit()\n envLayout.addRow(QLabel('Number of bands:'), self.bandEdit)\n self.gammatoneCheck = QCheckBox()\n envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck)\n self.windowCheck = QCheckBox()\n envLayout.addRow(QLabel('Windowed:'), self.windowCheck)\n envWidget = QGroupBox('Amplitude envelopes')\n envWidget.setLayout(envLayout)\n repLayout.addWidget(envWidget)\n mfccLayout = QFormLayout()\n self.numCCEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit)\n self.numFiltersEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit)\n self.powerCheck = QCheckBox()\n mfccLayout.addRow(QLabel('Use power (first coefficient):'), self.\n powerCheck)\n mfccWidget = QGroupBox('MFCC')\n mfccWidget.setLayout(mfccLayout)\n repLayout.addWidget(mfccWidget)\n self.setLayout(repLayout)\n self.winLenEdit.setText(str(setting_dict['win_len']))\n self.timeStepEdit.setText(str(setting_dict['time_step']))\n freq_lims = setting_dict['freq_lims']\n self.minFreqEdit.setText(str(freq_lims[0]))\n self.maxFreqEdit.setText(str(freq_lims[1]))\n self.numCoresEdit.setText(str(setting_dict['num_cores']))\n rep = setting_dict['rep']\n if rep == 'mfcc':\n self.mfccRadio.setChecked(True)\n elif rep == 'mhec':\n self.mhecRadio.setChecked(True)\n elif rep == 'prosody':\n self.prosodyRadio.setChecked(True)\n elif rep == 'formant':\n self.formantRadio.setChecked(True)\n elif rep == 'envelopes':\n self.envelopeRadio.setChecked(True)\n self.bandEdit.setText(str(setting_dict['envelope_bands']))\n if setting_dict['use_gammatone']:\n self.gammatoneCheck.setChecked(True)\n if setting_dict['use_window']:\n self.windowCheck.setChecked(True)\n self.numFiltersEdit.setText(str(setting_dict['mfcc_filters']))\n self.numCCEdit.setText(str(setting_dict['num_coeffs']))\n if setting_dict['use_power']:\n self.powerCheck.setChecked(True)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n if self.mfccRadio.isChecked():\n setting_dict['rep'] = 'mfcc'\n elif self.mhecRadio.isChecked():\n setting_dict['rep'] = 'mhec'\n elif self.prosodyRadio.isChecked():\n setting_dict['rep'] = 'prosody'\n elif self.formantRadio.isChecked():\n setting_dict['rep'] = 'formant'\n elif self.envelopeRadio.isChecked():\n setting_dict['rep'] = 'envelopes'\n setting_dict['win_len'] = float(self.winLenEdit.text())\n setting_dict['time_step'] = float(self.timeStepEdit.text())\n setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self.\n maxFreqEdit.text())\n setting_dict['num_cores'] = int(self.numCoresEdit.text())\n setting_dict['envelope_bands'] = int(self.bandEdit.text())\n setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked())\n setting_dict['use_window'] = int(self.windowCheck.isChecked())\n setting_dict['num_coeffs'] = int(self.numCCEdit.text())\n setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text())\n setting_dict['use_power'] = int(self.powerCheck.isChecked())\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['rep'] != cur_state['rep']:\n return True\n if cur_state['rep'] == 'mfcc':\n for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs',\n 'mfcc_filters', 'use_power']:\n if cur_state[k] != self.prev_state[k]:\n return True\n elif cur_state['rep'] == 'envelopes':\n for k in ['freq_lims', 'envelope_bands', 'use_gammatone',\n 'use_window']:\n if cur_state[k] != self.prev_state[k]:\n return True\n if cur_state['use_window']:\n for k in ['win_len', 'time_step']:\n if cur_state[k] != self.prev_state[k]:\n return True\n return False\n\n\nclass SpecgramPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n specLayout = QFormLayout()\n analysisLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit)\n self.methodCombo = QComboBox()\n self.methodCombo.addItem('Fourier')\n analysisLayout.addRow(QLabel('Method:'), self.methodCombo)\n self.winTypeCombo = QComboBox()\n self.winTypeCombo.addItem('Square (rectangular)')\n self.winTypeCombo.addItem('Hamming (raised sine-squared)')\n self.winTypeCombo.addItem('Bartlett (triangular)')\n self.winTypeCombo.addItem('Welch (parabolic)')\n self.winTypeCombo.addItem('Hanning (sine-squared)')\n self.winTypeCombo.addItem('Gaussian')\n analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo)\n analysisWidget = QGroupBox('Analysis')\n analysisWidget.setLayout(analysisLayout)\n specLayout.addWidget(analysisWidget)\n resLayout = QFormLayout()\n self.freqStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of frequency steps:'), self.\n freqStepsEdit)\n self.timeStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit)\n resWidget = QGroupBox('Frequency and time resolution')\n resWidget.setLayout(resLayout)\n specLayout.addWidget(resWidget)\n viewLayout = QFormLayout()\n self.autoScaleCheck = QCheckBox()\n viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck)\n self.dynamicRangeEdit = QLineEdit()\n viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit)\n self.maxEdit = QLineEdit()\n viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit)\n self.preEmphAlphaEdit = QLineEdit()\n viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit)\n viewWidget = QGroupBox('View settings')\n viewWidget.setLayout(viewLayout)\n specLayout.addWidget(viewWidget)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n return setting_dict\n\n\nclass Settings(object):\n key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270,\n 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': (\n 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq',\n 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength',\n 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': (\n 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20),\n 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': (\n 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4\n ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window':\n ('envelopes/UseWindow', False), 'dist_func': (\n 'network/DistanceFunction', 'dtw'), 'cluster_alg': (\n 'network/ClusterAlgorithm', 'complete'), 'one_cluster': (\n 'network/OneCluster', False), 'threshold': ('network/Threshold', 0),\n 'spec_win_len': ('spectrogram/WindowLength', 0.005),\n 'spec_win_type': ('spectrogram/WindowType', 'gaussian'),\n 'spec_freq_steps': ('spectrogram/FreqSteps', 250),\n 'spec_time_steps': ('spectrogram/TimeSteps', 1000),\n 'spec_autoscale': ('spectrogram/Autoscale', True),\n 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max':\n ('spectrogram/Maximum', 100), 'spec_alpha': (\n 'spectrogram/PreEmphAlpha', 0.97)}\n rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power',\n 'num_cores', 'use_gammatone', 'use_window']\n asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func']\n network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster',\n 'threshold']\n specgram_setting_keys = ['spec_win_len', 'spec_win_type',\n 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale',\n 'spec_dynamic_range', 'spec_max', 'spec_alpha']\n\n def __init__(self):\n self.qs = QSettings('settings.ini', QSettings.IniFormat)\n self.qs.setFallbacksEnabled(False)\n\n def __getitem__(self, key):\n if key == 'num_filters':\n if self['rep'] == 'mfcc':\n return self['mfcc_filters']\n elif self['rep'] == 'envelopes':\n return self['envelope_bands']\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key)\n else:\n inikey, default = mapped_key\n return type(default)(self.qs.value(inikey, default))\n\n def __setitem__(self, key, value):\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n if not isinstance(value, list) and not isinstance(value, tuple):\n raise KeyError\n if len(mapped_key) != len(value):\n raise KeyError\n for i, (k, d) in enumerate(mapped_key):\n self.qs.setValue(k, value[i])\n else:\n inikey, default = mapped_key\n self.qs.setValue(inikey, value)\n\n def update(self, setting_dict):\n for k, v in setting_dict.items():\n self[k] = v\n\n def acousticsim_kwarg(self):\n out = {x: self[x] for x in self.asim_kwarg_keys}\n out['return_rep'] = True\n return out\n\n def get_rep_settings(self):\n out = {x: self[x] for x in self.rep_setting_keys}\n return out\n\n def get_network_settings(self):\n out = {x: self[x] for x in self.network_setting_keys}\n return out\n\n def get_specgram_settings(self):\n out = {x: self[x] for x in self.specgram_setting_keys}\n return out\n\n\nclass PreferencesDialog(QDialog):\n\n def __init__(self, parent, settings):\n QDialog.__init__(self, parent)\n self.settings = settings\n tabWidget = QTabWidget()\n self.repWidget = RepresentationPane(self.settings.get_rep_settings())\n tabWidget.addTab(self.repWidget, 'Representations')\n self.networkWidget = NetworkPane(self.settings.get_network_settings())\n tabWidget.addTab(self.networkWidget, 'Network')\n self.specWidget = SpecgramPane(self.settings.get_specgram_settings())\n tabWidget.addTab(self.specWidget, 'Spectrogram')\n layout = QVBoxLayout()\n layout.addWidget(tabWidget)\n self.acceptButton = QPushButton('Ok')\n self.cancelButton = QPushButton('Cancel')\n self.acceptButton.clicked.connect(self.accept)\n self.cancelButton.clicked.connect(self.reject)\n hbox = QHBoxLayout()\n hbox.addWidget(self.acceptButton)\n hbox.addWidget(self.cancelButton)\n ac = QWidget()\n ac.setLayout(hbox)\n layout.addWidget(ac)\n self.setLayout(layout)\n self.network_changed = False\n self.rep_changed = False\n self.specgram_changed = False\n\n def accept(self):\n self.network_changed = self.networkWidget.is_changed()\n self.rep_changed = self.repWidget.is_changed()\n self.specgram_changed = self.specWidget.is_changed()\n self.settings.update(self.networkWidget.get_current_state())\n self.settings.update(self.repWidget.get_current_state())\n self.settings.update(self.specWidget.get_current_state())\n QDialog.accept(self)\n", "step-2": "<mask token>\n\n\nclass NetworkPane(BasePane):\n <mask token>\n\n def get_current_state(self):\n setting_dict = {}\n if self.ccRadio.isChecked():\n setting_dict['dist_func'] = 'xcorr'\n elif self.dctRadio.isChecked():\n setting_dict['dist_func'] = 'dct'\n elif self.dtwRadio.isChecked():\n setting_dict['dist_func'] = 'dtw'\n if self.completeRadio.isChecked():\n setting_dict['cluster_alg'] = 'complete'\n elif self.thresholdRadio.isChecked():\n setting_dict['cluster_alg'] = 'threshold'\n elif self.apRadio.isChecked():\n setting_dict['cluster_alg'] = 'affinity'\n elif self.scRadio.isChecked():\n setting_dict['cluster_alg'] = 'spectral'\n setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked())\n setting_dict['threshold'] = float(self.thresholdEdit.text())\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['dist_func'] != cur_state['dist_func']:\n return True\n return False\n for k in ['dist_func', 'cluster_alg']:\n if self.prev_state[k] != cur_state[k]:\n return True\n if cur_state['cluster_alg'] == 'threshold':\n if self.prev_state['threshold'] != cur_state['threshold']:\n return True\n elif cur_state['cluster_alg'] in {'affinity', 'spectral'}:\n if self.prev_state['one_cluster'] != cur_state['one_cluster']:\n return True\n return False\n\n\nclass RepresentationPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n repLayout = QVBoxLayout()\n genLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit)\n self.timeStepEdit = QLineEdit()\n genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit)\n self.minFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit)\n self.maxFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit)\n self.numCoresEdit = QLineEdit()\n genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self\n .numCoresEdit)\n repBox = QGroupBox()\n self.envelopeRadio = QRadioButton('Amplitude envelopes')\n self.mfccRadio = QRadioButton('MFCCs')\n self.mhecRadio = QRadioButton('MHECs')\n self.prosodyRadio = QRadioButton('Prosody')\n self.formantRadio = QRadioButton('Formants')\n hbox = QHBoxLayout()\n hbox.addWidget(self.envelopeRadio)\n hbox.addWidget(self.mfccRadio)\n repBox.setLayout(hbox)\n genLayout.addRow(QLabel('Token representation:'), repBox)\n genWidget = QGroupBox('General')\n genWidget.setLayout(genLayout)\n repLayout.addWidget(genWidget)\n envLayout = QFormLayout()\n self.bandEdit = QLineEdit()\n envLayout.addRow(QLabel('Number of bands:'), self.bandEdit)\n self.gammatoneCheck = QCheckBox()\n envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck)\n self.windowCheck = QCheckBox()\n envLayout.addRow(QLabel('Windowed:'), self.windowCheck)\n envWidget = QGroupBox('Amplitude envelopes')\n envWidget.setLayout(envLayout)\n repLayout.addWidget(envWidget)\n mfccLayout = QFormLayout()\n self.numCCEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit)\n self.numFiltersEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit)\n self.powerCheck = QCheckBox()\n mfccLayout.addRow(QLabel('Use power (first coefficient):'), self.\n powerCheck)\n mfccWidget = QGroupBox('MFCC')\n mfccWidget.setLayout(mfccLayout)\n repLayout.addWidget(mfccWidget)\n self.setLayout(repLayout)\n self.winLenEdit.setText(str(setting_dict['win_len']))\n self.timeStepEdit.setText(str(setting_dict['time_step']))\n freq_lims = setting_dict['freq_lims']\n self.minFreqEdit.setText(str(freq_lims[0]))\n self.maxFreqEdit.setText(str(freq_lims[1]))\n self.numCoresEdit.setText(str(setting_dict['num_cores']))\n rep = setting_dict['rep']\n if rep == 'mfcc':\n self.mfccRadio.setChecked(True)\n elif rep == 'mhec':\n self.mhecRadio.setChecked(True)\n elif rep == 'prosody':\n self.prosodyRadio.setChecked(True)\n elif rep == 'formant':\n self.formantRadio.setChecked(True)\n elif rep == 'envelopes':\n self.envelopeRadio.setChecked(True)\n self.bandEdit.setText(str(setting_dict['envelope_bands']))\n if setting_dict['use_gammatone']:\n self.gammatoneCheck.setChecked(True)\n if setting_dict['use_window']:\n self.windowCheck.setChecked(True)\n self.numFiltersEdit.setText(str(setting_dict['mfcc_filters']))\n self.numCCEdit.setText(str(setting_dict['num_coeffs']))\n if setting_dict['use_power']:\n self.powerCheck.setChecked(True)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n if self.mfccRadio.isChecked():\n setting_dict['rep'] = 'mfcc'\n elif self.mhecRadio.isChecked():\n setting_dict['rep'] = 'mhec'\n elif self.prosodyRadio.isChecked():\n setting_dict['rep'] = 'prosody'\n elif self.formantRadio.isChecked():\n setting_dict['rep'] = 'formant'\n elif self.envelopeRadio.isChecked():\n setting_dict['rep'] = 'envelopes'\n setting_dict['win_len'] = float(self.winLenEdit.text())\n setting_dict['time_step'] = float(self.timeStepEdit.text())\n setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self.\n maxFreqEdit.text())\n setting_dict['num_cores'] = int(self.numCoresEdit.text())\n setting_dict['envelope_bands'] = int(self.bandEdit.text())\n setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked())\n setting_dict['use_window'] = int(self.windowCheck.isChecked())\n setting_dict['num_coeffs'] = int(self.numCCEdit.text())\n setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text())\n setting_dict['use_power'] = int(self.powerCheck.isChecked())\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['rep'] != cur_state['rep']:\n return True\n if cur_state['rep'] == 'mfcc':\n for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs',\n 'mfcc_filters', 'use_power']:\n if cur_state[k] != self.prev_state[k]:\n return True\n elif cur_state['rep'] == 'envelopes':\n for k in ['freq_lims', 'envelope_bands', 'use_gammatone',\n 'use_window']:\n if cur_state[k] != self.prev_state[k]:\n return True\n if cur_state['use_window']:\n for k in ['win_len', 'time_step']:\n if cur_state[k] != self.prev_state[k]:\n return True\n return False\n\n\nclass SpecgramPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n specLayout = QFormLayout()\n analysisLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit)\n self.methodCombo = QComboBox()\n self.methodCombo.addItem('Fourier')\n analysisLayout.addRow(QLabel('Method:'), self.methodCombo)\n self.winTypeCombo = QComboBox()\n self.winTypeCombo.addItem('Square (rectangular)')\n self.winTypeCombo.addItem('Hamming (raised sine-squared)')\n self.winTypeCombo.addItem('Bartlett (triangular)')\n self.winTypeCombo.addItem('Welch (parabolic)')\n self.winTypeCombo.addItem('Hanning (sine-squared)')\n self.winTypeCombo.addItem('Gaussian')\n analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo)\n analysisWidget = QGroupBox('Analysis')\n analysisWidget.setLayout(analysisLayout)\n specLayout.addWidget(analysisWidget)\n resLayout = QFormLayout()\n self.freqStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of frequency steps:'), self.\n freqStepsEdit)\n self.timeStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit)\n resWidget = QGroupBox('Frequency and time resolution')\n resWidget.setLayout(resLayout)\n specLayout.addWidget(resWidget)\n viewLayout = QFormLayout()\n self.autoScaleCheck = QCheckBox()\n viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck)\n self.dynamicRangeEdit = QLineEdit()\n viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit)\n self.maxEdit = QLineEdit()\n viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit)\n self.preEmphAlphaEdit = QLineEdit()\n viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit)\n viewWidget = QGroupBox('View settings')\n viewWidget.setLayout(viewLayout)\n specLayout.addWidget(viewWidget)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n return setting_dict\n\n\nclass Settings(object):\n key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270,\n 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': (\n 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq',\n 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength',\n 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': (\n 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20),\n 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': (\n 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4\n ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window':\n ('envelopes/UseWindow', False), 'dist_func': (\n 'network/DistanceFunction', 'dtw'), 'cluster_alg': (\n 'network/ClusterAlgorithm', 'complete'), 'one_cluster': (\n 'network/OneCluster', False), 'threshold': ('network/Threshold', 0),\n 'spec_win_len': ('spectrogram/WindowLength', 0.005),\n 'spec_win_type': ('spectrogram/WindowType', 'gaussian'),\n 'spec_freq_steps': ('spectrogram/FreqSteps', 250),\n 'spec_time_steps': ('spectrogram/TimeSteps', 1000),\n 'spec_autoscale': ('spectrogram/Autoscale', True),\n 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max':\n ('spectrogram/Maximum', 100), 'spec_alpha': (\n 'spectrogram/PreEmphAlpha', 0.97)}\n rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power',\n 'num_cores', 'use_gammatone', 'use_window']\n asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func']\n network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster',\n 'threshold']\n specgram_setting_keys = ['spec_win_len', 'spec_win_type',\n 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale',\n 'spec_dynamic_range', 'spec_max', 'spec_alpha']\n\n def __init__(self):\n self.qs = QSettings('settings.ini', QSettings.IniFormat)\n self.qs.setFallbacksEnabled(False)\n\n def __getitem__(self, key):\n if key == 'num_filters':\n if self['rep'] == 'mfcc':\n return self['mfcc_filters']\n elif self['rep'] == 'envelopes':\n return self['envelope_bands']\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key)\n else:\n inikey, default = mapped_key\n return type(default)(self.qs.value(inikey, default))\n\n def __setitem__(self, key, value):\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n if not isinstance(value, list) and not isinstance(value, tuple):\n raise KeyError\n if len(mapped_key) != len(value):\n raise KeyError\n for i, (k, d) in enumerate(mapped_key):\n self.qs.setValue(k, value[i])\n else:\n inikey, default = mapped_key\n self.qs.setValue(inikey, value)\n\n def update(self, setting_dict):\n for k, v in setting_dict.items():\n self[k] = v\n\n def acousticsim_kwarg(self):\n out = {x: self[x] for x in self.asim_kwarg_keys}\n out['return_rep'] = True\n return out\n\n def get_rep_settings(self):\n out = {x: self[x] for x in self.rep_setting_keys}\n return out\n\n def get_network_settings(self):\n out = {x: self[x] for x in self.network_setting_keys}\n return out\n\n def get_specgram_settings(self):\n out = {x: self[x] for x in self.specgram_setting_keys}\n return out\n\n\nclass PreferencesDialog(QDialog):\n\n def __init__(self, parent, settings):\n QDialog.__init__(self, parent)\n self.settings = settings\n tabWidget = QTabWidget()\n self.repWidget = RepresentationPane(self.settings.get_rep_settings())\n tabWidget.addTab(self.repWidget, 'Representations')\n self.networkWidget = NetworkPane(self.settings.get_network_settings())\n tabWidget.addTab(self.networkWidget, 'Network')\n self.specWidget = SpecgramPane(self.settings.get_specgram_settings())\n tabWidget.addTab(self.specWidget, 'Spectrogram')\n layout = QVBoxLayout()\n layout.addWidget(tabWidget)\n self.acceptButton = QPushButton('Ok')\n self.cancelButton = QPushButton('Cancel')\n self.acceptButton.clicked.connect(self.accept)\n self.cancelButton.clicked.connect(self.reject)\n hbox = QHBoxLayout()\n hbox.addWidget(self.acceptButton)\n hbox.addWidget(self.cancelButton)\n ac = QWidget()\n ac.setLayout(hbox)\n layout.addWidget(ac)\n self.setLayout(layout)\n self.network_changed = False\n self.rep_changed = False\n self.specgram_changed = False\n\n def accept(self):\n self.network_changed = self.networkWidget.is_changed()\n self.rep_changed = self.repWidget.is_changed()\n self.specgram_changed = self.specWidget.is_changed()\n self.settings.update(self.networkWidget.get_current_state())\n self.settings.update(self.repWidget.get_current_state())\n self.settings.update(self.specWidget.get_current_state())\n QDialog.accept(self)\n", "step-3": "<mask token>\n\n\nclass BasePane(QWidget):\n <mask token>\n prev_state = {}\n\n def get_current_state(self):\n return None\n\n def is_changed(self):\n return self.get_current_state() != self.prev_state\n\n\nclass NetworkPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n networkLayout = QFormLayout()\n matchAlgorithmBox = QGroupBox()\n self.ccRadio = QRadioButton('Cross-correlation')\n self.dtwRadio = QRadioButton('DTW')\n self.dctRadio = QRadioButton('DCT')\n hbox = QHBoxLayout()\n hbox.addWidget(self.ccRadio)\n hbox.addWidget(self.dtwRadio)\n hbox.addWidget(self.dctRadio)\n matchAlgorithmBox.setLayout(hbox)\n networkLayout.addRow(QLabel('Similarity algorithm:'), matchAlgorithmBox\n )\n clusterBox = QGroupBox()\n self.completeRadio = QRadioButton('Complete')\n self.thresholdRadio = QRadioButton('Threshold')\n self.apRadio = QRadioButton('Affinity propagation')\n self.scRadio = QRadioButton('Spectral clustering')\n hbox = QHBoxLayout()\n hbox.addWidget(self.completeRadio)\n hbox.addWidget(self.thresholdRadio)\n hbox.addWidget(self.apRadio)\n hbox.addWidget(self.scRadio)\n clusterBox.setLayout(hbox)\n networkLayout.addRow(QLabel('Cluster algorithm:'), clusterBox)\n self.oneClusterCheck = QCheckBox()\n networkLayout.addRow(QLabel('Enforce single cluster:'), self.\n oneClusterCheck)\n self.thresholdEdit = QLineEdit()\n networkLayout.addRow(QLabel('Similarity threshold:'), self.\n thresholdEdit)\n self.setLayout(networkLayout)\n matchAlgorithm = setting_dict['dist_func']\n clustAlgorithm = setting_dict['cluster_alg']\n oneCluster = setting_dict['one_cluster']\n if matchAlgorithm == 'xcorr':\n self.ccRadio.setChecked(True)\n elif matchAlgorithm == 'dct':\n self.dctRadio.setChecked(True)\n else:\n self.dtwRadio.setChecked(True)\n if clustAlgorithm == 'complete':\n self.completeRadio.setChecked(True)\n elif clustAlgorithm == 'threshold':\n self.thresholdRadio.setChecked(True)\n elif clustAlgorithm == 'affinity':\n self.apRadio.setChecked(True)\n elif clustAlgorithm == 'spectral':\n self.scRadio.setChecked(True)\n if oneCluster:\n self.oneClusterCheck.setChecked(True)\n self.thresholdEdit.setText(str(setting_dict['threshold']))\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n if self.ccRadio.isChecked():\n setting_dict['dist_func'] = 'xcorr'\n elif self.dctRadio.isChecked():\n setting_dict['dist_func'] = 'dct'\n elif self.dtwRadio.isChecked():\n setting_dict['dist_func'] = 'dtw'\n if self.completeRadio.isChecked():\n setting_dict['cluster_alg'] = 'complete'\n elif self.thresholdRadio.isChecked():\n setting_dict['cluster_alg'] = 'threshold'\n elif self.apRadio.isChecked():\n setting_dict['cluster_alg'] = 'affinity'\n elif self.scRadio.isChecked():\n setting_dict['cluster_alg'] = 'spectral'\n setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked())\n setting_dict['threshold'] = float(self.thresholdEdit.text())\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['dist_func'] != cur_state['dist_func']:\n return True\n return False\n for k in ['dist_func', 'cluster_alg']:\n if self.prev_state[k] != cur_state[k]:\n return True\n if cur_state['cluster_alg'] == 'threshold':\n if self.prev_state['threshold'] != cur_state['threshold']:\n return True\n elif cur_state['cluster_alg'] in {'affinity', 'spectral'}:\n if self.prev_state['one_cluster'] != cur_state['one_cluster']:\n return True\n return False\n\n\nclass RepresentationPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n repLayout = QVBoxLayout()\n genLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit)\n self.timeStepEdit = QLineEdit()\n genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit)\n self.minFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit)\n self.maxFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit)\n self.numCoresEdit = QLineEdit()\n genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self\n .numCoresEdit)\n repBox = QGroupBox()\n self.envelopeRadio = QRadioButton('Amplitude envelopes')\n self.mfccRadio = QRadioButton('MFCCs')\n self.mhecRadio = QRadioButton('MHECs')\n self.prosodyRadio = QRadioButton('Prosody')\n self.formantRadio = QRadioButton('Formants')\n hbox = QHBoxLayout()\n hbox.addWidget(self.envelopeRadio)\n hbox.addWidget(self.mfccRadio)\n repBox.setLayout(hbox)\n genLayout.addRow(QLabel('Token representation:'), repBox)\n genWidget = QGroupBox('General')\n genWidget.setLayout(genLayout)\n repLayout.addWidget(genWidget)\n envLayout = QFormLayout()\n self.bandEdit = QLineEdit()\n envLayout.addRow(QLabel('Number of bands:'), self.bandEdit)\n self.gammatoneCheck = QCheckBox()\n envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck)\n self.windowCheck = QCheckBox()\n envLayout.addRow(QLabel('Windowed:'), self.windowCheck)\n envWidget = QGroupBox('Amplitude envelopes')\n envWidget.setLayout(envLayout)\n repLayout.addWidget(envWidget)\n mfccLayout = QFormLayout()\n self.numCCEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit)\n self.numFiltersEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit)\n self.powerCheck = QCheckBox()\n mfccLayout.addRow(QLabel('Use power (first coefficient):'), self.\n powerCheck)\n mfccWidget = QGroupBox('MFCC')\n mfccWidget.setLayout(mfccLayout)\n repLayout.addWidget(mfccWidget)\n self.setLayout(repLayout)\n self.winLenEdit.setText(str(setting_dict['win_len']))\n self.timeStepEdit.setText(str(setting_dict['time_step']))\n freq_lims = setting_dict['freq_lims']\n self.minFreqEdit.setText(str(freq_lims[0]))\n self.maxFreqEdit.setText(str(freq_lims[1]))\n self.numCoresEdit.setText(str(setting_dict['num_cores']))\n rep = setting_dict['rep']\n if rep == 'mfcc':\n self.mfccRadio.setChecked(True)\n elif rep == 'mhec':\n self.mhecRadio.setChecked(True)\n elif rep == 'prosody':\n self.prosodyRadio.setChecked(True)\n elif rep == 'formant':\n self.formantRadio.setChecked(True)\n elif rep == 'envelopes':\n self.envelopeRadio.setChecked(True)\n self.bandEdit.setText(str(setting_dict['envelope_bands']))\n if setting_dict['use_gammatone']:\n self.gammatoneCheck.setChecked(True)\n if setting_dict['use_window']:\n self.windowCheck.setChecked(True)\n self.numFiltersEdit.setText(str(setting_dict['mfcc_filters']))\n self.numCCEdit.setText(str(setting_dict['num_coeffs']))\n if setting_dict['use_power']:\n self.powerCheck.setChecked(True)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n if self.mfccRadio.isChecked():\n setting_dict['rep'] = 'mfcc'\n elif self.mhecRadio.isChecked():\n setting_dict['rep'] = 'mhec'\n elif self.prosodyRadio.isChecked():\n setting_dict['rep'] = 'prosody'\n elif self.formantRadio.isChecked():\n setting_dict['rep'] = 'formant'\n elif self.envelopeRadio.isChecked():\n setting_dict['rep'] = 'envelopes'\n setting_dict['win_len'] = float(self.winLenEdit.text())\n setting_dict['time_step'] = float(self.timeStepEdit.text())\n setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self.\n maxFreqEdit.text())\n setting_dict['num_cores'] = int(self.numCoresEdit.text())\n setting_dict['envelope_bands'] = int(self.bandEdit.text())\n setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked())\n setting_dict['use_window'] = int(self.windowCheck.isChecked())\n setting_dict['num_coeffs'] = int(self.numCCEdit.text())\n setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text())\n setting_dict['use_power'] = int(self.powerCheck.isChecked())\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['rep'] != cur_state['rep']:\n return True\n if cur_state['rep'] == 'mfcc':\n for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs',\n 'mfcc_filters', 'use_power']:\n if cur_state[k] != self.prev_state[k]:\n return True\n elif cur_state['rep'] == 'envelopes':\n for k in ['freq_lims', 'envelope_bands', 'use_gammatone',\n 'use_window']:\n if cur_state[k] != self.prev_state[k]:\n return True\n if cur_state['use_window']:\n for k in ['win_len', 'time_step']:\n if cur_state[k] != self.prev_state[k]:\n return True\n return False\n\n\nclass SpecgramPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n specLayout = QFormLayout()\n analysisLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit)\n self.methodCombo = QComboBox()\n self.methodCombo.addItem('Fourier')\n analysisLayout.addRow(QLabel('Method:'), self.methodCombo)\n self.winTypeCombo = QComboBox()\n self.winTypeCombo.addItem('Square (rectangular)')\n self.winTypeCombo.addItem('Hamming (raised sine-squared)')\n self.winTypeCombo.addItem('Bartlett (triangular)')\n self.winTypeCombo.addItem('Welch (parabolic)')\n self.winTypeCombo.addItem('Hanning (sine-squared)')\n self.winTypeCombo.addItem('Gaussian')\n analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo)\n analysisWidget = QGroupBox('Analysis')\n analysisWidget.setLayout(analysisLayout)\n specLayout.addWidget(analysisWidget)\n resLayout = QFormLayout()\n self.freqStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of frequency steps:'), self.\n freqStepsEdit)\n self.timeStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit)\n resWidget = QGroupBox('Frequency and time resolution')\n resWidget.setLayout(resLayout)\n specLayout.addWidget(resWidget)\n viewLayout = QFormLayout()\n self.autoScaleCheck = QCheckBox()\n viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck)\n self.dynamicRangeEdit = QLineEdit()\n viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit)\n self.maxEdit = QLineEdit()\n viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit)\n self.preEmphAlphaEdit = QLineEdit()\n viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit)\n viewWidget = QGroupBox('View settings')\n viewWidget.setLayout(viewLayout)\n specLayout.addWidget(viewWidget)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n return setting_dict\n\n\nclass Settings(object):\n key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270,\n 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': (\n 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq',\n 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength',\n 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': (\n 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20),\n 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': (\n 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4\n ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window':\n ('envelopes/UseWindow', False), 'dist_func': (\n 'network/DistanceFunction', 'dtw'), 'cluster_alg': (\n 'network/ClusterAlgorithm', 'complete'), 'one_cluster': (\n 'network/OneCluster', False), 'threshold': ('network/Threshold', 0),\n 'spec_win_len': ('spectrogram/WindowLength', 0.005),\n 'spec_win_type': ('spectrogram/WindowType', 'gaussian'),\n 'spec_freq_steps': ('spectrogram/FreqSteps', 250),\n 'spec_time_steps': ('spectrogram/TimeSteps', 1000),\n 'spec_autoscale': ('spectrogram/Autoscale', True),\n 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max':\n ('spectrogram/Maximum', 100), 'spec_alpha': (\n 'spectrogram/PreEmphAlpha', 0.97)}\n rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power',\n 'num_cores', 'use_gammatone', 'use_window']\n asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func']\n network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster',\n 'threshold']\n specgram_setting_keys = ['spec_win_len', 'spec_win_type',\n 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale',\n 'spec_dynamic_range', 'spec_max', 'spec_alpha']\n\n def __init__(self):\n self.qs = QSettings('settings.ini', QSettings.IniFormat)\n self.qs.setFallbacksEnabled(False)\n\n def __getitem__(self, key):\n if key == 'num_filters':\n if self['rep'] == 'mfcc':\n return self['mfcc_filters']\n elif self['rep'] == 'envelopes':\n return self['envelope_bands']\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key)\n else:\n inikey, default = mapped_key\n return type(default)(self.qs.value(inikey, default))\n\n def __setitem__(self, key, value):\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n if not isinstance(value, list) and not isinstance(value, tuple):\n raise KeyError\n if len(mapped_key) != len(value):\n raise KeyError\n for i, (k, d) in enumerate(mapped_key):\n self.qs.setValue(k, value[i])\n else:\n inikey, default = mapped_key\n self.qs.setValue(inikey, value)\n\n def update(self, setting_dict):\n for k, v in setting_dict.items():\n self[k] = v\n\n def acousticsim_kwarg(self):\n out = {x: self[x] for x in self.asim_kwarg_keys}\n out['return_rep'] = True\n return out\n\n def get_rep_settings(self):\n out = {x: self[x] for x in self.rep_setting_keys}\n return out\n\n def get_network_settings(self):\n out = {x: self[x] for x in self.network_setting_keys}\n return out\n\n def get_specgram_settings(self):\n out = {x: self[x] for x in self.specgram_setting_keys}\n return out\n\n\nclass PreferencesDialog(QDialog):\n\n def __init__(self, parent, settings):\n QDialog.__init__(self, parent)\n self.settings = settings\n tabWidget = QTabWidget()\n self.repWidget = RepresentationPane(self.settings.get_rep_settings())\n tabWidget.addTab(self.repWidget, 'Representations')\n self.networkWidget = NetworkPane(self.settings.get_network_settings())\n tabWidget.addTab(self.networkWidget, 'Network')\n self.specWidget = SpecgramPane(self.settings.get_specgram_settings())\n tabWidget.addTab(self.specWidget, 'Spectrogram')\n layout = QVBoxLayout()\n layout.addWidget(tabWidget)\n self.acceptButton = QPushButton('Ok')\n self.cancelButton = QPushButton('Cancel')\n self.acceptButton.clicked.connect(self.accept)\n self.cancelButton.clicked.connect(self.reject)\n hbox = QHBoxLayout()\n hbox.addWidget(self.acceptButton)\n hbox.addWidget(self.cancelButton)\n ac = QWidget()\n ac.setLayout(hbox)\n layout.addWidget(ac)\n self.setLayout(layout)\n self.network_changed = False\n self.rep_changed = False\n self.specgram_changed = False\n\n def accept(self):\n self.network_changed = self.networkWidget.is_changed()\n self.rep_changed = self.repWidget.is_changed()\n self.specgram_changed = self.specWidget.is_changed()\n self.settings.update(self.networkWidget.get_current_state())\n self.settings.update(self.repWidget.get_current_state())\n self.settings.update(self.specWidget.get_current_state())\n QDialog.accept(self)\n", "step-4": "from PySide.QtCore import qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand, Qt, QTime, QSettings, QSize, QPoint\nfrom PySide.QtGui import QBrush, QKeySequence, QColor, QLinearGradient, QPainter, QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene, QGraphicsView, QStyle, QMainWindow, QAction, QDialog, QDockWidget, QHBoxLayout, QWidget, QFileDialog, QListWidget, QMessageBox, QTableWidget, QTableWidgetItem, QDialog, QItemSelectionModel, QPushButton, QLabel, QTabWidget, QGroupBox, QRadioButton, QVBoxLayout, QLineEdit, QFormLayout, QCheckBox, QFont, QSound, QComboBox\n\n\nclass BasePane(QWidget):\n \"\"\"Abstract, don't use\"\"\"\n prev_state = {}\n\n def get_current_state(self):\n return None\n\n def is_changed(self):\n return self.get_current_state() != self.prev_state\n\n\nclass NetworkPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n networkLayout = QFormLayout()\n matchAlgorithmBox = QGroupBox()\n self.ccRadio = QRadioButton('Cross-correlation')\n self.dtwRadio = QRadioButton('DTW')\n self.dctRadio = QRadioButton('DCT')\n hbox = QHBoxLayout()\n hbox.addWidget(self.ccRadio)\n hbox.addWidget(self.dtwRadio)\n hbox.addWidget(self.dctRadio)\n matchAlgorithmBox.setLayout(hbox)\n networkLayout.addRow(QLabel('Similarity algorithm:'), matchAlgorithmBox\n )\n clusterBox = QGroupBox()\n self.completeRadio = QRadioButton('Complete')\n self.thresholdRadio = QRadioButton('Threshold')\n self.apRadio = QRadioButton('Affinity propagation')\n self.scRadio = QRadioButton('Spectral clustering')\n hbox = QHBoxLayout()\n hbox.addWidget(self.completeRadio)\n hbox.addWidget(self.thresholdRadio)\n hbox.addWidget(self.apRadio)\n hbox.addWidget(self.scRadio)\n clusterBox.setLayout(hbox)\n networkLayout.addRow(QLabel('Cluster algorithm:'), clusterBox)\n self.oneClusterCheck = QCheckBox()\n networkLayout.addRow(QLabel('Enforce single cluster:'), self.\n oneClusterCheck)\n self.thresholdEdit = QLineEdit()\n networkLayout.addRow(QLabel('Similarity threshold:'), self.\n thresholdEdit)\n self.setLayout(networkLayout)\n matchAlgorithm = setting_dict['dist_func']\n clustAlgorithm = setting_dict['cluster_alg']\n oneCluster = setting_dict['one_cluster']\n if matchAlgorithm == 'xcorr':\n self.ccRadio.setChecked(True)\n elif matchAlgorithm == 'dct':\n self.dctRadio.setChecked(True)\n else:\n self.dtwRadio.setChecked(True)\n if clustAlgorithm == 'complete':\n self.completeRadio.setChecked(True)\n elif clustAlgorithm == 'threshold':\n self.thresholdRadio.setChecked(True)\n elif clustAlgorithm == 'affinity':\n self.apRadio.setChecked(True)\n elif clustAlgorithm == 'spectral':\n self.scRadio.setChecked(True)\n if oneCluster:\n self.oneClusterCheck.setChecked(True)\n self.thresholdEdit.setText(str(setting_dict['threshold']))\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n if self.ccRadio.isChecked():\n setting_dict['dist_func'] = 'xcorr'\n elif self.dctRadio.isChecked():\n setting_dict['dist_func'] = 'dct'\n elif self.dtwRadio.isChecked():\n setting_dict['dist_func'] = 'dtw'\n if self.completeRadio.isChecked():\n setting_dict['cluster_alg'] = 'complete'\n elif self.thresholdRadio.isChecked():\n setting_dict['cluster_alg'] = 'threshold'\n elif self.apRadio.isChecked():\n setting_dict['cluster_alg'] = 'affinity'\n elif self.scRadio.isChecked():\n setting_dict['cluster_alg'] = 'spectral'\n setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked())\n setting_dict['threshold'] = float(self.thresholdEdit.text())\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['dist_func'] != cur_state['dist_func']:\n return True\n return False\n for k in ['dist_func', 'cluster_alg']:\n if self.prev_state[k] != cur_state[k]:\n return True\n if cur_state['cluster_alg'] == 'threshold':\n if self.prev_state['threshold'] != cur_state['threshold']:\n return True\n elif cur_state['cluster_alg'] in {'affinity', 'spectral'}:\n if self.prev_state['one_cluster'] != cur_state['one_cluster']:\n return True\n return False\n\n\nclass RepresentationPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n repLayout = QVBoxLayout()\n genLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n genLayout.addRow(QLabel('Window length (s):'), self.winLenEdit)\n self.timeStepEdit = QLineEdit()\n genLayout.addRow(QLabel('Time step (s):'), self.timeStepEdit)\n self.minFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Minimum frequency (Hz):'), self.minFreqEdit)\n self.maxFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Maximum frequency (Hz):'), self.maxFreqEdit)\n self.numCoresEdit = QLineEdit()\n genLayout.addRow(QLabel('Number of cores (multiprocessing):'), self\n .numCoresEdit)\n repBox = QGroupBox()\n self.envelopeRadio = QRadioButton('Amplitude envelopes')\n self.mfccRadio = QRadioButton('MFCCs')\n self.mhecRadio = QRadioButton('MHECs')\n self.prosodyRadio = QRadioButton('Prosody')\n self.formantRadio = QRadioButton('Formants')\n hbox = QHBoxLayout()\n hbox.addWidget(self.envelopeRadio)\n hbox.addWidget(self.mfccRadio)\n repBox.setLayout(hbox)\n genLayout.addRow(QLabel('Token representation:'), repBox)\n genWidget = QGroupBox('General')\n genWidget.setLayout(genLayout)\n repLayout.addWidget(genWidget)\n envLayout = QFormLayout()\n self.bandEdit = QLineEdit()\n envLayout.addRow(QLabel('Number of bands:'), self.bandEdit)\n self.gammatoneCheck = QCheckBox()\n envLayout.addRow(QLabel('Gammatone:'), self.gammatoneCheck)\n self.windowCheck = QCheckBox()\n envLayout.addRow(QLabel('Windowed:'), self.windowCheck)\n envWidget = QGroupBox('Amplitude envelopes')\n envWidget.setLayout(envLayout)\n repLayout.addWidget(envWidget)\n mfccLayout = QFormLayout()\n self.numCCEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of coefficents:'), self.numCCEdit)\n self.numFiltersEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of filters:'), self.numFiltersEdit)\n self.powerCheck = QCheckBox()\n mfccLayout.addRow(QLabel('Use power (first coefficient):'), self.\n powerCheck)\n mfccWidget = QGroupBox('MFCC')\n mfccWidget.setLayout(mfccLayout)\n repLayout.addWidget(mfccWidget)\n self.setLayout(repLayout)\n self.winLenEdit.setText(str(setting_dict['win_len']))\n self.timeStepEdit.setText(str(setting_dict['time_step']))\n freq_lims = setting_dict['freq_lims']\n self.minFreqEdit.setText(str(freq_lims[0]))\n self.maxFreqEdit.setText(str(freq_lims[1]))\n self.numCoresEdit.setText(str(setting_dict['num_cores']))\n rep = setting_dict['rep']\n if rep == 'mfcc':\n self.mfccRadio.setChecked(True)\n elif rep == 'mhec':\n self.mhecRadio.setChecked(True)\n elif rep == 'prosody':\n self.prosodyRadio.setChecked(True)\n elif rep == 'formant':\n self.formantRadio.setChecked(True)\n elif rep == 'envelopes':\n self.envelopeRadio.setChecked(True)\n self.bandEdit.setText(str(setting_dict['envelope_bands']))\n if setting_dict['use_gammatone']:\n self.gammatoneCheck.setChecked(True)\n if setting_dict['use_window']:\n self.windowCheck.setChecked(True)\n self.numFiltersEdit.setText(str(setting_dict['mfcc_filters']))\n self.numCCEdit.setText(str(setting_dict['num_coeffs']))\n if setting_dict['use_power']:\n self.powerCheck.setChecked(True)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n if self.mfccRadio.isChecked():\n setting_dict['rep'] = 'mfcc'\n elif self.mhecRadio.isChecked():\n setting_dict['rep'] = 'mhec'\n elif self.prosodyRadio.isChecked():\n setting_dict['rep'] = 'prosody'\n elif self.formantRadio.isChecked():\n setting_dict['rep'] = 'formant'\n elif self.envelopeRadio.isChecked():\n setting_dict['rep'] = 'envelopes'\n setting_dict['win_len'] = float(self.winLenEdit.text())\n setting_dict['time_step'] = float(self.timeStepEdit.text())\n setting_dict['freq_lims'] = int(self.minFreqEdit.text()), int(self.\n maxFreqEdit.text())\n setting_dict['num_cores'] = int(self.numCoresEdit.text())\n setting_dict['envelope_bands'] = int(self.bandEdit.text())\n setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked())\n setting_dict['use_window'] = int(self.windowCheck.isChecked())\n setting_dict['num_coeffs'] = int(self.numCCEdit.text())\n setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text())\n setting_dict['use_power'] = int(self.powerCheck.isChecked())\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['rep'] != cur_state['rep']:\n return True\n if cur_state['rep'] == 'mfcc':\n for k in ['win_len', 'time_step', 'freq_lims', 'num_coeffs',\n 'mfcc_filters', 'use_power']:\n if cur_state[k] != self.prev_state[k]:\n return True\n elif cur_state['rep'] == 'envelopes':\n for k in ['freq_lims', 'envelope_bands', 'use_gammatone',\n 'use_window']:\n if cur_state[k] != self.prev_state[k]:\n return True\n if cur_state['use_window']:\n for k in ['win_len', 'time_step']:\n if cur_state[k] != self.prev_state[k]:\n return True\n return False\n\n\nclass SpecgramPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n specLayout = QFormLayout()\n analysisLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n analysisLayout.addRow(QLabel('Window length:'), self.winLenEdit)\n self.methodCombo = QComboBox()\n self.methodCombo.addItem('Fourier')\n analysisLayout.addRow(QLabel('Method:'), self.methodCombo)\n self.winTypeCombo = QComboBox()\n self.winTypeCombo.addItem('Square (rectangular)')\n self.winTypeCombo.addItem('Hamming (raised sine-squared)')\n self.winTypeCombo.addItem('Bartlett (triangular)')\n self.winTypeCombo.addItem('Welch (parabolic)')\n self.winTypeCombo.addItem('Hanning (sine-squared)')\n self.winTypeCombo.addItem('Gaussian')\n analysisLayout.addRow(QLabel('Window type:'), self.winTypeCombo)\n analysisWidget = QGroupBox('Analysis')\n analysisWidget.setLayout(analysisLayout)\n specLayout.addWidget(analysisWidget)\n resLayout = QFormLayout()\n self.freqStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of frequency steps:'), self.\n freqStepsEdit)\n self.timeStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of time steps:'), self.timeStepsEdit)\n resWidget = QGroupBox('Frequency and time resolution')\n resWidget.setLayout(resLayout)\n specLayout.addWidget(resWidget)\n viewLayout = QFormLayout()\n self.autoScaleCheck = QCheckBox()\n viewLayout.addRow(QLabel('Autoscale:'), self.autoScaleCheck)\n self.dynamicRangeEdit = QLineEdit()\n viewLayout.addRow(QLabel('Dynamic range (dB):'), self.dynamicRangeEdit)\n self.maxEdit = QLineEdit()\n viewLayout.addRow(QLabel('Maximum (dB/Hz):'), self.maxEdit)\n self.preEmphAlphaEdit = QLineEdit()\n viewLayout.addRow(QLabel('Pre-emphasis alpha:'), self.preEmphAlphaEdit)\n viewWidget = QGroupBox('View settings')\n viewWidget.setLayout(viewLayout)\n specLayout.addWidget(viewWidget)\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n return setting_dict\n\n\nclass Settings(object):\n key_to_ini = {'path': ('general/path', ''), 'size': ('size', QSize(270,\n 225)), 'pos': ('pos', QPoint(50, 50)), 'rep': (\n 'general/Representation', 'mfcc'), 'freq_lims': [('general/MinFreq',\n 80), ('general/MaxFreq', 7800)], 'win_len': ('general/WindowLength',\n 0.025), 'time_step': ('general/TimeStep', 0.01), 'num_cores': (\n 'general/NumCores', 1), 'num_coeffs': ('mfcc/NumCC', 20),\n 'mfcc_filters': ('mfcc/NumFilters', 26), 'use_power': (\n 'mfcc/UsePower', False), 'envelope_bands': ('envelopes/NumBands', 4\n ), 'use_gammatone': ('envelopes/UseGammatone', False), 'use_window':\n ('envelopes/UseWindow', False), 'dist_func': (\n 'network/DistanceFunction', 'dtw'), 'cluster_alg': (\n 'network/ClusterAlgorithm', 'complete'), 'one_cluster': (\n 'network/OneCluster', False), 'threshold': ('network/Threshold', 0),\n 'spec_win_len': ('spectrogram/WindowLength', 0.005),\n 'spec_win_type': ('spectrogram/WindowType', 'gaussian'),\n 'spec_freq_steps': ('spectrogram/FreqSteps', 250),\n 'spec_time_steps': ('spectrogram/TimeSteps', 1000),\n 'spec_autoscale': ('spectrogram/Autoscale', True),\n 'spec_dynamic_range': ('spectrogram/DynamicRange', 70), 'spec_max':\n ('spectrogram/Maximum', 100), 'spec_alpha': (\n 'spectrogram/PreEmphAlpha', 0.97)}\n rep_setting_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'mfcc_filters', 'envelope_bands', 'use_power',\n 'num_cores', 'use_gammatone', 'use_window']\n asim_kwarg_keys = ['rep', 'freq_lims', 'win_len', 'time_step',\n 'num_coeffs', 'num_filters', 'use_power', 'num_cores', 'dist_func']\n network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster',\n 'threshold']\n specgram_setting_keys = ['spec_win_len', 'spec_win_type',\n 'spec_freq_steps', 'spec_time_steps', 'spec_autoscale',\n 'spec_dynamic_range', 'spec_max', 'spec_alpha']\n\n def __init__(self):\n self.qs = QSettings('settings.ini', QSettings.IniFormat)\n self.qs.setFallbacksEnabled(False)\n\n def __getitem__(self, key):\n if key == 'num_filters':\n if self['rep'] == 'mfcc':\n return self['mfcc_filters']\n elif self['rep'] == 'envelopes':\n return self['envelope_bands']\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n return tuple(type(d)(self.qs.value(k, d)) for k, d in mapped_key)\n else:\n inikey, default = mapped_key\n return type(default)(self.qs.value(inikey, default))\n\n def __setitem__(self, key, value):\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n if not isinstance(value, list) and not isinstance(value, tuple):\n raise KeyError\n if len(mapped_key) != len(value):\n raise KeyError\n for i, (k, d) in enumerate(mapped_key):\n self.qs.setValue(k, value[i])\n else:\n inikey, default = mapped_key\n self.qs.setValue(inikey, value)\n\n def update(self, setting_dict):\n for k, v in setting_dict.items():\n self[k] = v\n\n def acousticsim_kwarg(self):\n out = {x: self[x] for x in self.asim_kwarg_keys}\n out['return_rep'] = True\n return out\n\n def get_rep_settings(self):\n out = {x: self[x] for x in self.rep_setting_keys}\n return out\n\n def get_network_settings(self):\n out = {x: self[x] for x in self.network_setting_keys}\n return out\n\n def get_specgram_settings(self):\n out = {x: self[x] for x in self.specgram_setting_keys}\n return out\n\n\nclass PreferencesDialog(QDialog):\n\n def __init__(self, parent, settings):\n QDialog.__init__(self, parent)\n self.settings = settings\n tabWidget = QTabWidget()\n self.repWidget = RepresentationPane(self.settings.get_rep_settings())\n tabWidget.addTab(self.repWidget, 'Representations')\n self.networkWidget = NetworkPane(self.settings.get_network_settings())\n tabWidget.addTab(self.networkWidget, 'Network')\n self.specWidget = SpecgramPane(self.settings.get_specgram_settings())\n tabWidget.addTab(self.specWidget, 'Spectrogram')\n layout = QVBoxLayout()\n layout.addWidget(tabWidget)\n self.acceptButton = QPushButton('Ok')\n self.cancelButton = QPushButton('Cancel')\n self.acceptButton.clicked.connect(self.accept)\n self.cancelButton.clicked.connect(self.reject)\n hbox = QHBoxLayout()\n hbox.addWidget(self.acceptButton)\n hbox.addWidget(self.cancelButton)\n ac = QWidget()\n ac.setLayout(hbox)\n layout.addWidget(ac)\n self.setLayout(layout)\n self.network_changed = False\n self.rep_changed = False\n self.specgram_changed = False\n\n def accept(self):\n self.network_changed = self.networkWidget.is_changed()\n self.rep_changed = self.repWidget.is_changed()\n self.specgram_changed = self.specWidget.is_changed()\n self.settings.update(self.networkWidget.get_current_state())\n self.settings.update(self.repWidget.get_current_state())\n self.settings.update(self.specWidget.get_current_state())\n QDialog.accept(self)\n", "step-5": "\nfrom PySide.QtCore import (qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand,\n Qt, QTime,QSettings,QSize,QPoint)\nfrom PySide.QtGui import (QBrush, QKeySequence, QColor, QLinearGradient, QPainter,\n QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene,\n QGraphicsView, QStyle,QMainWindow, QAction, QDialog, QDockWidget, QHBoxLayout, QWidget,\n QFileDialog, QListWidget, QMessageBox,QTableWidget,QTableWidgetItem,QDialog,QItemSelectionModel,\n QPushButton,QLabel,QTabWidget,QGroupBox, QRadioButton,QVBoxLayout,QLineEdit,QFormLayout,\n QCheckBox,QFont,QSound, QComboBox)\n\nclass BasePane(QWidget):\n \"\"\"Abstract, don't use\"\"\"\n\n prev_state = {}\n\n def get_current_state(self):\n return None\n\n def is_changed(self):\n return self.get_current_state() != self.prev_state\n\n\nclass NetworkPane(BasePane):\n def __init__(self, setting_dict):\n BasePane.__init__( self )\n\n networkLayout = QFormLayout()\n\n matchAlgorithmBox = QGroupBox()\n self.ccRadio = QRadioButton('Cross-correlation')\n self.dtwRadio = QRadioButton('DTW')\n self.dctRadio = QRadioButton('DCT')\n\n hbox = QHBoxLayout()\n hbox.addWidget(self.ccRadio)\n hbox.addWidget(self.dtwRadio)\n hbox.addWidget(self.dctRadio)\n matchAlgorithmBox.setLayout(hbox)\n\n networkLayout.addRow(QLabel('Similarity algorithm:'),matchAlgorithmBox)\n\n clusterBox = QGroupBox()\n self.completeRadio = QRadioButton('Complete')\n self.thresholdRadio = QRadioButton('Threshold')\n self.apRadio = QRadioButton('Affinity propagation')\n self.scRadio = QRadioButton('Spectral clustering')\n\n hbox = QHBoxLayout()\n hbox.addWidget(self.completeRadio)\n hbox.addWidget(self.thresholdRadio)\n hbox.addWidget(self.apRadio)\n hbox.addWidget(self.scRadio)\n clusterBox.setLayout(hbox)\n\n networkLayout.addRow(QLabel('Cluster algorithm:'),clusterBox)\n\n self.oneClusterCheck = QCheckBox()\n networkLayout.addRow(QLabel('Enforce single cluster:'),self.oneClusterCheck)\n\n self.thresholdEdit = QLineEdit()\n networkLayout.addRow(QLabel('Similarity threshold:'),self.thresholdEdit)\n\n self.setLayout(networkLayout)\n\n #set up defaults\n\n matchAlgorithm = setting_dict['dist_func']\n clustAlgorithm = setting_dict['cluster_alg']\n oneCluster = setting_dict['one_cluster']\n\n if matchAlgorithm == 'xcorr':\n self.ccRadio.setChecked(True)\n elif matchAlgorithm == 'dct':\n self.dctRadio.setChecked(True)\n else:\n self.dtwRadio.setChecked(True)\n\n if clustAlgorithm == 'complete':\n self.completeRadio.setChecked(True)\n elif clustAlgorithm == 'threshold':\n self.thresholdRadio.setChecked(True)\n elif clustAlgorithm == 'affinity':\n self.apRadio.setChecked(True)\n elif clustAlgorithm == 'spectral':\n self.scRadio.setChecked(True)\n\n if oneCluster:\n self.oneClusterCheck.setChecked(True)\n self.thresholdEdit.setText(str(setting_dict['threshold']))\n\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n\n if self.ccRadio.isChecked():\n setting_dict['dist_func'] = 'xcorr'\n elif self.dctRadio.isChecked():\n setting_dict['dist_func'] = 'dct'\n elif self.dtwRadio.isChecked():\n setting_dict['dist_func'] = 'dtw'\n\n if self.completeRadio.isChecked():\n setting_dict['cluster_alg'] = 'complete'\n elif self.thresholdRadio.isChecked():\n setting_dict['cluster_alg'] = 'threshold'\n elif self.apRadio.isChecked():\n setting_dict['cluster_alg'] = 'affinity'\n elif self.scRadio.isChecked():\n setting_dict['cluster_alg'] = 'spectral'\n\n setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked())\n setting_dict['threshold'] = float(self.thresholdEdit.text())\n\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['dist_func'] != cur_state['dist_func']:\n return True\n return False\n for k in ['dist_func','cluster_alg']:\n if self.prev_state[k] != cur_state[k]:\n return True\n if cur_state['cluster_alg'] == 'threshold':\n if self.prev_state['threshold'] != cur_state['threshold']:\n return True\n elif cur_state['cluster_alg'] in {'affinity','spectral'}:\n if self.prev_state['one_cluster'] != cur_state['one_cluster']:\n return True\n return False\n\nclass RepresentationPane(BasePane):\n def __init__(self, setting_dict):\n BasePane.__init__( self )\n\n repLayout = QVBoxLayout()\n\n genLayout = QFormLayout()\n self.winLenEdit = QLineEdit()\n genLayout.addRow(QLabel('Window length (s):'),self.winLenEdit)\n self.timeStepEdit = QLineEdit()\n genLayout.addRow(QLabel('Time step (s):'),self.timeStepEdit)\n self.minFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Minimum frequency (Hz):'),self.minFreqEdit)\n self.maxFreqEdit = QLineEdit()\n genLayout.addRow(QLabel('Maximum frequency (Hz):'),self.maxFreqEdit)\n self.numCoresEdit = QLineEdit()\n genLayout.addRow(QLabel('Number of cores (multiprocessing):'),self.numCoresEdit)\n\n repBox = QGroupBox()\n self.envelopeRadio = QRadioButton('Amplitude envelopes')\n self.mfccRadio = QRadioButton('MFCCs')\n self.mhecRadio = QRadioButton('MHECs')\n self.prosodyRadio = QRadioButton('Prosody')\n self.formantRadio = QRadioButton('Formants')\n hbox = QHBoxLayout()\n hbox.addWidget(self.envelopeRadio)\n hbox.addWidget(self.mfccRadio)\n #hbox.addWidget(self.mhecRadio)\n #hbox.addWidget(self.prosodyRadio)\n #hbox.addWidget(self.formantRadio)\n repBox.setLayout(hbox)\n\n genLayout.addRow(QLabel('Token representation:'),repBox)\n\n genWidget = QGroupBox('General')\n genWidget.setLayout(genLayout)\n repLayout.addWidget(genWidget)\n\n envLayout = QFormLayout()\n self.bandEdit = QLineEdit()\n envLayout.addRow(QLabel('Number of bands:'),self.bandEdit)\n self.gammatoneCheck = QCheckBox()\n envLayout.addRow(QLabel('Gammatone:'),self.gammatoneCheck)\n self.windowCheck = QCheckBox()\n envLayout.addRow(QLabel('Windowed:'),self.windowCheck)\n\n\n envWidget = QGroupBox('Amplitude envelopes')\n envWidget.setLayout(envLayout)\n repLayout.addWidget(envWidget)\n\n mfccLayout = QFormLayout()\n self.numCCEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of coefficents:'),self.numCCEdit)\n self.numFiltersEdit = QLineEdit()\n mfccLayout.addRow(QLabel('Number of filters:'),self.numFiltersEdit)\n self.powerCheck = QCheckBox()\n mfccLayout.addRow(QLabel('Use power (first coefficient):'),self.powerCheck)\n\n mfccWidget = QGroupBox('MFCC')\n mfccWidget.setLayout(mfccLayout)\n\n repLayout.addWidget(mfccWidget)\n\n self.setLayout(repLayout)\n\n self.winLenEdit.setText(str(setting_dict['win_len']))\n self.timeStepEdit.setText(str(setting_dict['time_step']))\n freq_lims = setting_dict['freq_lims']\n self.minFreqEdit.setText(str(freq_lims[0]))\n self.maxFreqEdit.setText(str(freq_lims[1]))\n self.numCoresEdit.setText(str(setting_dict['num_cores']))\n\n rep = setting_dict['rep']\n if rep == 'mfcc':\n self.mfccRadio.setChecked(True)\n elif rep == 'mhec':\n self.mhecRadio.setChecked(True)\n elif rep == 'prosody':\n self.prosodyRadio.setChecked(True)\n elif rep == 'formant':\n self.formantRadio.setChecked(True)\n elif rep == 'envelopes':\n self.envelopeRadio.setChecked(True)\n\n self.bandEdit.setText(str(setting_dict['envelope_bands']))\n\n if setting_dict['use_gammatone']:\n self.gammatoneCheck.setChecked(True)\n if setting_dict['use_window']:\n self.windowCheck.setChecked(True)\n\n self.numFiltersEdit.setText(str(setting_dict['mfcc_filters']))\n self.numCCEdit.setText(str(setting_dict['num_coeffs']))\n if setting_dict['use_power']:\n self.powerCheck.setChecked(True)\n\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n\n if self.mfccRadio.isChecked():\n setting_dict['rep'] = 'mfcc'\n elif self.mhecRadio.isChecked():\n setting_dict['rep'] = 'mhec'\n elif self.prosodyRadio.isChecked():\n setting_dict['rep'] = 'prosody'\n elif self.formantRadio.isChecked():\n setting_dict['rep'] = 'formant'\n elif self.envelopeRadio.isChecked():\n setting_dict['rep'] = 'envelopes'\n\n setting_dict['win_len'] = float(self.winLenEdit.text())\n setting_dict['time_step'] = float(self.timeStepEdit.text())\n setting_dict['freq_lims'] = (int(self.minFreqEdit.text()),\n int(self.maxFreqEdit.text()))\n setting_dict['num_cores'] = int(self.numCoresEdit.text())\n\n setting_dict['envelope_bands'] = int(self.bandEdit.text())\n setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked())\n setting_dict['use_window'] = int(self.windowCheck.isChecked())\n\n setting_dict['num_coeffs'] = int(self.numCCEdit.text())\n setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text())\n setting_dict['use_power'] = int(self.powerCheck.isChecked())\n\n return setting_dict\n\n def is_changed(self):\n cur_state = self.get_current_state()\n if self.prev_state['rep'] != cur_state['rep']:\n return True\n if cur_state['rep'] == 'mfcc':\n for k in ['win_len','time_step','freq_lims',\n 'num_coeffs','mfcc_filters','use_power']:\n if cur_state[k] != self.prev_state[k]:\n return True\n elif cur_state['rep'] == 'envelopes':\n for k in ['freq_lims','envelope_bands',\n 'use_gammatone', 'use_window']:\n if cur_state[k] != self.prev_state[k]:\n return True\n if cur_state['use_window']:\n for k in ['win_len','time_step']:\n if cur_state[k] != self.prev_state[k]:\n return True\n return False\n\nclass SpecgramPane(BasePane):\n def __init__(self, setting_dict):\n BasePane.__init__( self )\n specLayout = QFormLayout()\n\n analysisLayout = QFormLayout()\n\n self.winLenEdit = QLineEdit()\n analysisLayout.addRow(QLabel('Window length:'),self.winLenEdit)\n\n self.methodCombo = QComboBox()\n self.methodCombo.addItem(\"Fourier\")\n analysisLayout.addRow(QLabel('Method:'),self.methodCombo)\n\n self.winTypeCombo = QComboBox()\n self.winTypeCombo.addItem(\"Square (rectangular)\")\n self.winTypeCombo.addItem(\"Hamming (raised sine-squared)\")\n self.winTypeCombo.addItem(\"Bartlett (triangular)\")\n self.winTypeCombo.addItem(\"Welch (parabolic)\")\n self.winTypeCombo.addItem(\"Hanning (sine-squared)\")\n self.winTypeCombo.addItem(\"Gaussian\")\n analysisLayout.addRow(QLabel('Window type:'),self.winTypeCombo)\n\n analysisWidget = QGroupBox('Analysis')\n analysisWidget.setLayout(analysisLayout)\n specLayout.addWidget(analysisWidget)\n\n\n resLayout = QFormLayout()\n self.freqStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of frequency steps:'),self.freqStepsEdit)\n\n self.timeStepsEdit = QLineEdit()\n resLayout.addRow(QLabel('Number of time steps:'),self.timeStepsEdit)\n\n\n resWidget = QGroupBox('Frequency and time resolution')\n resWidget.setLayout(resLayout)\n specLayout.addWidget(resWidget)\n\n\n viewLayout = QFormLayout()\n self.autoScaleCheck = QCheckBox()\n viewLayout.addRow(QLabel('Autoscale:'),self.autoScaleCheck)\n\n self.dynamicRangeEdit = QLineEdit()\n viewLayout.addRow(QLabel('Dynamic range (dB):'),self.dynamicRangeEdit)\n\n self.maxEdit = QLineEdit()\n viewLayout.addRow(QLabel('Maximum (dB/Hz):'),self.maxEdit)\n\n self.preEmphAlphaEdit = QLineEdit()\n viewLayout.addRow(QLabel('Pre-emphasis alpha:'),self.preEmphAlphaEdit)\n\n\n viewWidget = QGroupBox('View settings')\n viewWidget.setLayout(viewLayout)\n specLayout.addWidget(viewWidget)\n\n\n\n self.prev_state = setting_dict\n\n def get_current_state(self):\n setting_dict = {}\n return setting_dict\n\n\nclass Settings(object):\n\n key_to_ini = {'path': ('general/path',''),\n 'size':('size', QSize(270, 225)),\n 'pos': ('pos', QPoint(50, 50)),\n 'rep': ('general/Representation','mfcc'),\n 'freq_lims': [('general/MinFreq',80),('general/MaxFreq',7800)],\n 'win_len': ('general/WindowLength',0.025),\n 'time_step': ('general/TimeStep',0.01),\n 'num_cores': ('general/NumCores',1),\n 'num_coeffs': ('mfcc/NumCC',20),\n 'mfcc_filters': ('mfcc/NumFilters',26),\n 'use_power': ('mfcc/UsePower',False),\n 'envelope_bands': ('envelopes/NumBands',4),\n 'use_gammatone': ('envelopes/UseGammatone',False),\n 'use_window': ('envelopes/UseWindow',False),\n 'dist_func': ('network/DistanceFunction','dtw'),\n 'cluster_alg': ('network/ClusterAlgorithm','complete'),\n 'one_cluster': ('network/OneCluster',False),\n 'threshold': ('network/Threshold',0),\n 'spec_win_len':('spectrogram/WindowLength',0.005),\n 'spec_win_type':('spectrogram/WindowType','gaussian'),\n 'spec_freq_steps':('spectrogram/FreqSteps',250),\n 'spec_time_steps':('spectrogram/TimeSteps',1000),\n 'spec_autoscale':('spectrogram/Autoscale',True),\n 'spec_dynamic_range':('spectrogram/DynamicRange',70),\n 'spec_max':('spectrogram/Maximum',100),\n 'spec_alpha':('spectrogram/PreEmphAlpha',0.97)}\n\n rep_setting_keys = ['rep','freq_lims','win_len','time_step','num_coeffs',\n 'mfcc_filters','envelope_bands','use_power','num_cores',\n 'use_gammatone', 'use_window']\n\n asim_kwarg_keys = ['rep','freq_lims','win_len','time_step','num_coeffs',\n 'num_filters','use_power','num_cores','dist_func']\n\n network_setting_keys = ['dist_func', 'cluster_alg', 'one_cluster', 'threshold']\n\n specgram_setting_keys = ['spec_win_len','spec_win_type','spec_freq_steps',\n 'spec_time_steps','spec_autoscale', 'spec_dynamic_range',\n 'spec_max','spec_alpha']\n\n def __init__(self):\n self.qs = QSettings('settings.ini',QSettings.IniFormat)\n self.qs.setFallbacksEnabled(False)\n\n def __getitem__(self, key):\n if key == 'num_filters':\n if self['rep'] == 'mfcc':\n return self['mfcc_filters']\n elif self['rep'] == 'envelopes':\n return self['envelope_bands']\n\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n return tuple(type(d)(self.qs.value(k,d)) for k, d in mapped_key)\n else:\n inikey, default = mapped_key\n return type(default)(self.qs.value(inikey,default))\n\n def __setitem__(self, key, value):\n mapped_key = self.key_to_ini[key]\n if isinstance(mapped_key, list):\n if not isinstance(value,list) and not isinstance(value,tuple):\n raise(KeyError)\n if len(mapped_key) != len(value):\n raise(KeyError)\n for i,(k, d) in enumerate(mapped_key):\n self.qs.setValue(k,value[i])\n else:\n inikey, default = mapped_key\n self.qs.setValue(inikey,value)\n\n\n def update(self,setting_dict):\n for k,v in setting_dict.items():\n self[k] = v\n\n def acousticsim_kwarg(self):\n out = {x: self[x] for x in self.asim_kwarg_keys}\n out['return_rep'] = True\n return out\n\n def get_rep_settings(self):\n out = {x: self[x] for x in self.rep_setting_keys}\n return out\n\n def get_network_settings(self):\n out = {x: self[x] for x in self.network_setting_keys}\n return out\n\n def get_specgram_settings(self):\n out = {x: self[x] for x in self.specgram_setting_keys}\n return out\n\nclass PreferencesDialog(QDialog):\n\n def __init__(self, parent, settings):\n QDialog.__init__( self, parent )\n\n self.settings = settings\n\n tabWidget = QTabWidget()\n\n #Representations\n self.repWidget = RepresentationPane(self.settings.get_rep_settings())\n\n tabWidget.addTab(self.repWidget,'Representations')\n\n\n #Network Tab\n\n self.networkWidget = NetworkPane(self.settings.get_network_settings())\n tabWidget.addTab(self.networkWidget, 'Network')\n\n\n self.specWidget = SpecgramPane(self.settings.get_specgram_settings())\n tabWidget.addTab(self.specWidget,'Spectrogram')\n\n\n layout = QVBoxLayout()\n layout.addWidget(tabWidget)\n\n #Accept cancel\n self.acceptButton = QPushButton('Ok')\n self.cancelButton = QPushButton('Cancel')\n\n self.acceptButton.clicked.connect(self.accept)\n self.cancelButton.clicked.connect(self.reject)\n\n hbox = QHBoxLayout()\n hbox.addWidget(self.acceptButton)\n hbox.addWidget(self.cancelButton)\n ac = QWidget()\n ac.setLayout(hbox)\n layout.addWidget(ac)\n\n self.setLayout(layout)\n\n self.network_changed = False\n self.rep_changed = False\n self.specgram_changed = False\n\n\n def accept(self):\n self.network_changed = self.networkWidget.is_changed()\n self.rep_changed = self.repWidget.is_changed()\n self.specgram_changed = self.specWidget.is_changed()\n\n self.settings.update(self.networkWidget.get_current_state())\n self.settings.update(self.repWidget.get_current_state())\n self.settings.update(self.specWidget.get_current_state())\n\n QDialog.accept(self)\n", "step-ids": [ 20, 23, 28, 30, 31 ] }
[ 20, 23, 28, 30, 31 ]
import sys def dir_slash(): slash = '/' if 'win' in sys.platform: slash = '\\' return slash
normal
{ "blob_id": "b12c8d0cb1cd1e48df6246fe3f16467b2db296e0", "index": 745, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef dir_slash():\n slash = '/'\n if 'win' in sys.platform:\n slash = '\\\\'\n return slash\n", "step-3": "import sys\n\n\ndef dir_slash():\n slash = '/'\n if 'win' in sys.platform:\n slash = '\\\\'\n return slash\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from cell import Cell from tkinter import messagebox import time import fileTools class Playground: """ The playground for the program. All cells are stored here. This object also import/export cells to the playground :param screen: The screen object. :param mouse: The mouse object. :param keyboard: The keyboard object. :param root: The root object. Attributes: cells: All the cells that is on the playground. clickSwitch: The size of the one grid box in pixels. """ def __init__(self, root, screen, mouse, keyboard): self.root = root self.screen = screen self.mouse = mouse self.keyboard = keyboard self.cells = [] self.clickSwitch = False self.autoGenerateMode = False self.generation = 0 self.timeToCalcGeneration = 0 self.bindKeyboardKeysToFunctions() def bindKeyboardKeysToFunctions(self): """ Binds diffrent functions to keyboard presses. :return: (nothing) """ self.keyboard.bindFunctionToKey("space", self.nextGeneration) def updatePlayground(self): """ Updates the playground. Checking for user input to interact with the playground. :return: (nothing) """ self.getMouseInput() if(self.autoGenerateMode): self.nextGeneration() def getMouseInput(self): """ This method is getting the mouse and doing diffrent thing with it. For example: spawning a new cell if the user click on an grid-box. :return: (nothing) """ xPos = self.mouse.xGridPos yPos = self.mouse.yGridPos #Changing the hoverblock color depending if the mouse is hovering over an living cell or not. if(self.getCellFromPosition(xPos, yPos)): self.screen.canvas.itemconfig(self.screen.hoverBlock, fill='#ff0000') else: self.screen.canvas.itemconfig(self.screen.hoverBlock, fill='#00ff00') #Placing an cell on the playground if the user is clicking on the playground if(self.mouse.leftButton and self.clickSwitch == False): if(self.keyboard.shiftKey): clickedCell = self.getCellFromPosition(xPos, yPos) if(clickedCell == False): self.createCell(xPos, yPos) else: self.deleteCell(clickedCell) self.clickSwitch = True if (self.mouse.leftButton == False and self.clickSwitch == True): self.clickSwitch = False def deleteCell(self, cell): """ Deleting a cell from the cell-list. :param cell: The cell that is going to be delete. :return: (nothing) """ index = self.cells.index(cell) self.cells[index].delete() self.cells.remove(cell) def createCell(self, xPos, yPos): """ Creates a new cell for a given position. :param xPos: The x-position on the grid. :param yPos: the y-position on the grid :return: (nothing) """ self.cells.append(Cell(self.screen, xPos, yPos)) def getCellFromPosition(self, xPos, yPos): """ Gets a cell from a given position. :param xPos: The x-position on the grid. :param yPos: the y-position on the grid :return: Cell """ for cell in self.cells: if(xPos == cell.x and yPos == cell.y): return cell return False def clearPlayground(self): """ Removes all the cells from the playground :return: (nothing) """ for cell in self.cells: cell.delete() self.cells = [] self.generation = 0 def importPlayground(self, filepath): """ This function is importing a playground. :param filepath: The filepath to import the playground to. :return: (nothing) """ cellOutOfBound = False avgXPos = 0 avgYPos = 0 fileWrite = open(filepath, "r") cellPositions = fileWrite.readlines() self.clearPlayground() for cellPos in cellPositions: #Cleans the string cleanCellPos = fileTools.cleanString(cellPos) if(cleanCellPos == ""): continue #Check the format. cleanCellPos = self.checkFileFormat(cleanCellPos) if(cleanCellPos): cellXPos, cellYPos = cleanCellPos else: return #Checks if the coords is outside the world. if(cellXPos > self.screen.worldSize or cellYPos > self.screen.worldSize or cellXPos < 0 or cellYPos < 0): cellOutOfBound = True else: newCell = Cell(self.screen, cellXPos, cellYPos) rectCellPos = self.screen.canvas.coords(newCell.rect) avgXPos += rectCellPos[0]; avgYPos += rectCellPos[1] self.cells.append(newCell) #Print warning that some cells are not renderd. if(cellOutOfBound): messagebox.showwarning("Warning!", "Some cells are placed outside of the playground!") #Moving the user to where the cells are. avgXPos /= len(cellPositions); avgYPos /= len(cellPositions) self.screen.offsetX += avgXPos - self.screen.width/2 self.screen.offsetY += avgYPos - self.screen.height/2 def exportPlayground(self, filepath): """ This function is exporting a playground. :param filepath: The filepath to export the playground to. :return: (nothing) """ cellPositions = "" for cell in self.cells: if(cell.dead == False): cellPositions += str(cell.x) + " " + str(cell.y) + "\n" fileWrite = open(filepath, "w") fileWrite.write(cellPositions) fileWrite.close() def checkFileFormat(self, cellPos): """ Checks if the file has the right format for this program. :param fileContent: The content of the file :return: The positions in a tuple, (x, y), false if there is an error. """ try: cellPosList = cellPos.split() cellXPos = int(cellPosList[0]) cellYPos = int(cellPosList[1]) except ValueError: messagebox.showerror("Error: Wrong format", "The choosen file do not have the correct format. Be so kind to choose an other file.") return False pass return (cellXPos, cellYPos) def removeCells(self, cellArray): """ Deletes all the cells from the array and playground. :param cellArray: The array of cells to delete. :return: (nothing) """ for cell in cellArray: cell.delete() self.cells.remove(cell) def setNeighbors(self): """ Creates dead cells around all living cells and calculating all the neighbors for the dead and the living cells :return: (nothing) """ for cellIndex in range(len(self.cells)): cell = self.cells[cellIndex] #Checks the 8 cells around the living one. for neighborsX in range(cell.x - 1, cell.x + 2): for neighborsY in range(cell.y - 1, cell.y + 2): #If the position is outside the world, loop around. neighborsX = neighborsX % self.screen.worldSize neighborsY = neighborsY % self.screen.worldSize #Skipping itself. Becouse we do not want to calculate itself as a neighbor if(neighborsX == cell.x and neighborsY == cell.y): continue else: #Checks if a cell exist at neighborsX, neighborsY cellToCheck = self.getCellFromPosition(neighborsX, neighborsY) if(cellToCheck != False): #Add one to the neighbor var if there already exist and cell for the given position. cellToCheck.numOfNeighbor += 1 else: #Creates a new cell if it do not exist any. newCell = Cell(self.screen, neighborsX, neighborsY, True) newCell.numOfNeighbor += 1 self.cells.append(newCell) def checkAmountOfNeighbors(self): """ Check the amount of neighbors and kills or creates new cell depending on the amount. :return: (nothing) """ cellsToDelete = [] for cell in self.cells: if(cell.numOfNeighbor > 3 or cell.numOfNeighbor < 2 or (cell.numOfNeighbor == 2 and cell.dead == True)): cellsToDelete.append(cell) elif(cell.numOfNeighbor == 3 and cell.dead == True): cell.makeAlive() cell.numOfNeighbor = 0 self.removeCells(cellsToDelete) def nextGeneration(self): """ This method is updating the cells to the next generation. :return: (nothing) Thanks to Martins for the idea to have modolu of the current posotion. """ # Start a timer to calculate the time the render one generation. startTime = int(round(time.time() * 100000)) self.generation += 1 self.setNeighbors() self.checkAmountOfNeighbors() # Ends a timer to calculate the time the render one generation. endTime = int(round(time.time() * 100000)) self.timeToCalcGeneration = (endTime - startTime)
normal
{ "blob_id": "80d5cc9871ec753fb9239df7680ac62809baa496", "index": 8177, "step-1": "<mask token>\n\n\nclass Playground:\n <mask token>\n\n def __init__(self, root, screen, mouse, keyboard):\n self.root = root\n self.screen = screen\n self.mouse = mouse\n self.keyboard = keyboard\n self.cells = []\n self.clickSwitch = False\n self.autoGenerateMode = False\n self.generation = 0\n self.timeToCalcGeneration = 0\n self.bindKeyboardKeysToFunctions()\n\n def bindKeyboardKeysToFunctions(self):\n \"\"\" \n Binds diffrent functions to keyboard presses. \n :return: (nothing)\n \"\"\"\n self.keyboard.bindFunctionToKey('space', self.nextGeneration)\n\n def updatePlayground(self):\n \"\"\" \n Updates the playground. Checking for user input to interact with the playground.\n :return: (nothing)\n \"\"\"\n self.getMouseInput()\n if self.autoGenerateMode:\n self.nextGeneration()\n\n def getMouseInput(self):\n \"\"\"\n This method is getting the mouse and doing diffrent thing with it. For example: spawning a new cell if the user click on an grid-box.\n :return: (nothing)\n \"\"\"\n xPos = self.mouse.xGridPos\n yPos = self.mouse.yGridPos\n if self.getCellFromPosition(xPos, yPos):\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#ff0000')\n else:\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#00ff00')\n if self.mouse.leftButton and self.clickSwitch == False:\n if self.keyboard.shiftKey:\n clickedCell = self.getCellFromPosition(xPos, yPos)\n if clickedCell == False:\n self.createCell(xPos, yPos)\n else:\n self.deleteCell(clickedCell)\n self.clickSwitch = True\n if self.mouse.leftButton == False and self.clickSwitch == True:\n self.clickSwitch = False\n <mask token>\n\n def createCell(self, xPos, yPos):\n \"\"\"\n Creates a new cell for a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: (nothing)\n \"\"\"\n self.cells.append(Cell(self.screen, xPos, yPos))\n\n def getCellFromPosition(self, xPos, yPos):\n \"\"\"\n Gets a cell from a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: Cell\n \"\"\"\n for cell in self.cells:\n if xPos == cell.x and yPos == cell.y:\n return cell\n return False\n\n def clearPlayground(self):\n \"\"\"\n Removes all the cells from the playground\n :return: (nothing)\n \"\"\"\n for cell in self.cells:\n cell.delete()\n self.cells = []\n self.generation = 0\n\n def importPlayground(self, filepath):\n \"\"\"\n This function is importing a playground.\n :param filepath: The filepath to import the playground to. \n :return: (nothing)\n \"\"\"\n cellOutOfBound = False\n avgXPos = 0\n avgYPos = 0\n fileWrite = open(filepath, 'r')\n cellPositions = fileWrite.readlines()\n self.clearPlayground()\n for cellPos in cellPositions:\n cleanCellPos = fileTools.cleanString(cellPos)\n if cleanCellPos == '':\n continue\n cleanCellPos = self.checkFileFormat(cleanCellPos)\n if cleanCellPos:\n cellXPos, cellYPos = cleanCellPos\n else:\n return\n if (cellXPos > self.screen.worldSize or cellYPos > self.screen.\n worldSize or cellXPos < 0 or cellYPos < 0):\n cellOutOfBound = True\n else:\n newCell = Cell(self.screen, cellXPos, cellYPos)\n rectCellPos = self.screen.canvas.coords(newCell.rect)\n avgXPos += rectCellPos[0]\n avgYPos += rectCellPos[1]\n self.cells.append(newCell)\n if cellOutOfBound:\n messagebox.showwarning('Warning!',\n 'Some cells are placed outside of the playground!')\n avgXPos /= len(cellPositions)\n avgYPos /= len(cellPositions)\n self.screen.offsetX += avgXPos - self.screen.width / 2\n self.screen.offsetY += avgYPos - self.screen.height / 2\n <mask token>\n <mask token>\n\n def removeCells(self, cellArray):\n \"\"\"\n Deletes all the cells from the array and playground.\n :param cellArray: The array of cells to delete.\n :return: (nothing)\n \"\"\"\n for cell in cellArray:\n cell.delete()\n self.cells.remove(cell)\n <mask token>\n\n def checkAmountOfNeighbors(self):\n \"\"\"\n Check the amount of neighbors and kills or creates new cell depending on the amount.\n :return: (nothing)\n \"\"\"\n cellsToDelete = []\n for cell in self.cells:\n if (cell.numOfNeighbor > 3 or cell.numOfNeighbor < 2 or cell.\n numOfNeighbor == 2 and cell.dead == True):\n cellsToDelete.append(cell)\n elif cell.numOfNeighbor == 3 and cell.dead == True:\n cell.makeAlive()\n cell.numOfNeighbor = 0\n self.removeCells(cellsToDelete)\n\n def nextGeneration(self):\n \"\"\"\n This method is updating the cells to the next generation.\n :return: (nothing)\n\n Thanks to Martins for the idea to have modolu of the current posotion.\n \"\"\"\n startTime = int(round(time.time() * 100000))\n self.generation += 1\n self.setNeighbors()\n self.checkAmountOfNeighbors()\n endTime = int(round(time.time() * 100000))\n self.timeToCalcGeneration = endTime - startTime\n", "step-2": "<mask token>\n\n\nclass Playground:\n <mask token>\n\n def __init__(self, root, screen, mouse, keyboard):\n self.root = root\n self.screen = screen\n self.mouse = mouse\n self.keyboard = keyboard\n self.cells = []\n self.clickSwitch = False\n self.autoGenerateMode = False\n self.generation = 0\n self.timeToCalcGeneration = 0\n self.bindKeyboardKeysToFunctions()\n\n def bindKeyboardKeysToFunctions(self):\n \"\"\" \n Binds diffrent functions to keyboard presses. \n :return: (nothing)\n \"\"\"\n self.keyboard.bindFunctionToKey('space', self.nextGeneration)\n\n def updatePlayground(self):\n \"\"\" \n Updates the playground. Checking for user input to interact with the playground.\n :return: (nothing)\n \"\"\"\n self.getMouseInput()\n if self.autoGenerateMode:\n self.nextGeneration()\n\n def getMouseInput(self):\n \"\"\"\n This method is getting the mouse and doing diffrent thing with it. For example: spawning a new cell if the user click on an grid-box.\n :return: (nothing)\n \"\"\"\n xPos = self.mouse.xGridPos\n yPos = self.mouse.yGridPos\n if self.getCellFromPosition(xPos, yPos):\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#ff0000')\n else:\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#00ff00')\n if self.mouse.leftButton and self.clickSwitch == False:\n if self.keyboard.shiftKey:\n clickedCell = self.getCellFromPosition(xPos, yPos)\n if clickedCell == False:\n self.createCell(xPos, yPos)\n else:\n self.deleteCell(clickedCell)\n self.clickSwitch = True\n if self.mouse.leftButton == False and self.clickSwitch == True:\n self.clickSwitch = False\n\n def deleteCell(self, cell):\n \"\"\"\n Deleting a cell from the cell-list.\n :param cell: The cell that is going to be delete.\n :return: (nothing)\n \"\"\"\n index = self.cells.index(cell)\n self.cells[index].delete()\n self.cells.remove(cell)\n\n def createCell(self, xPos, yPos):\n \"\"\"\n Creates a new cell for a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: (nothing)\n \"\"\"\n self.cells.append(Cell(self.screen, xPos, yPos))\n\n def getCellFromPosition(self, xPos, yPos):\n \"\"\"\n Gets a cell from a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: Cell\n \"\"\"\n for cell in self.cells:\n if xPos == cell.x and yPos == cell.y:\n return cell\n return False\n\n def clearPlayground(self):\n \"\"\"\n Removes all the cells from the playground\n :return: (nothing)\n \"\"\"\n for cell in self.cells:\n cell.delete()\n self.cells = []\n self.generation = 0\n\n def importPlayground(self, filepath):\n \"\"\"\n This function is importing a playground.\n :param filepath: The filepath to import the playground to. \n :return: (nothing)\n \"\"\"\n cellOutOfBound = False\n avgXPos = 0\n avgYPos = 0\n fileWrite = open(filepath, 'r')\n cellPositions = fileWrite.readlines()\n self.clearPlayground()\n for cellPos in cellPositions:\n cleanCellPos = fileTools.cleanString(cellPos)\n if cleanCellPos == '':\n continue\n cleanCellPos = self.checkFileFormat(cleanCellPos)\n if cleanCellPos:\n cellXPos, cellYPos = cleanCellPos\n else:\n return\n if (cellXPos > self.screen.worldSize or cellYPos > self.screen.\n worldSize or cellXPos < 0 or cellYPos < 0):\n cellOutOfBound = True\n else:\n newCell = Cell(self.screen, cellXPos, cellYPos)\n rectCellPos = self.screen.canvas.coords(newCell.rect)\n avgXPos += rectCellPos[0]\n avgYPos += rectCellPos[1]\n self.cells.append(newCell)\n if cellOutOfBound:\n messagebox.showwarning('Warning!',\n 'Some cells are placed outside of the playground!')\n avgXPos /= len(cellPositions)\n avgYPos /= len(cellPositions)\n self.screen.offsetX += avgXPos - self.screen.width / 2\n self.screen.offsetY += avgYPos - self.screen.height / 2\n\n def exportPlayground(self, filepath):\n \"\"\"\n This function is exporting a playground.\n :param filepath: The filepath to export the playground to. \n :return: (nothing)\n \"\"\"\n cellPositions = ''\n for cell in self.cells:\n if cell.dead == False:\n cellPositions += str(cell.x) + ' ' + str(cell.y) + '\\n'\n fileWrite = open(filepath, 'w')\n fileWrite.write(cellPositions)\n fileWrite.close()\n\n def checkFileFormat(self, cellPos):\n \"\"\"\n Checks if the file has the right format for this program.\n :param fileContent: The content of the file\n :return: The positions in a tuple, (x, y), false if there is an error.\n \"\"\"\n try:\n cellPosList = cellPos.split()\n cellXPos = int(cellPosList[0])\n cellYPos = int(cellPosList[1])\n except ValueError:\n messagebox.showerror('Error: Wrong format',\n 'The choosen file do not have the correct format. Be so kind to choose an other file.'\n )\n return False\n pass\n return cellXPos, cellYPos\n\n def removeCells(self, cellArray):\n \"\"\"\n Deletes all the cells from the array and playground.\n :param cellArray: The array of cells to delete.\n :return: (nothing)\n \"\"\"\n for cell in cellArray:\n cell.delete()\n self.cells.remove(cell)\n\n def setNeighbors(self):\n \"\"\"\n Creates dead cells around all living cells and calculating all the neighbors for the dead and the living cells\n :return: (nothing)\n \"\"\"\n for cellIndex in range(len(self.cells)):\n cell = self.cells[cellIndex]\n for neighborsX in range(cell.x - 1, cell.x + 2):\n for neighborsY in range(cell.y - 1, cell.y + 2):\n neighborsX = neighborsX % self.screen.worldSize\n neighborsY = neighborsY % self.screen.worldSize\n if neighborsX == cell.x and neighborsY == cell.y:\n continue\n else:\n cellToCheck = self.getCellFromPosition(neighborsX,\n neighborsY)\n if cellToCheck != False:\n cellToCheck.numOfNeighbor += 1\n else:\n newCell = Cell(self.screen, neighborsX,\n neighborsY, True)\n newCell.numOfNeighbor += 1\n self.cells.append(newCell)\n\n def checkAmountOfNeighbors(self):\n \"\"\"\n Check the amount of neighbors and kills or creates new cell depending on the amount.\n :return: (nothing)\n \"\"\"\n cellsToDelete = []\n for cell in self.cells:\n if (cell.numOfNeighbor > 3 or cell.numOfNeighbor < 2 or cell.\n numOfNeighbor == 2 and cell.dead == True):\n cellsToDelete.append(cell)\n elif cell.numOfNeighbor == 3 and cell.dead == True:\n cell.makeAlive()\n cell.numOfNeighbor = 0\n self.removeCells(cellsToDelete)\n\n def nextGeneration(self):\n \"\"\"\n This method is updating the cells to the next generation.\n :return: (nothing)\n\n Thanks to Martins for the idea to have modolu of the current posotion.\n \"\"\"\n startTime = int(round(time.time() * 100000))\n self.generation += 1\n self.setNeighbors()\n self.checkAmountOfNeighbors()\n endTime = int(round(time.time() * 100000))\n self.timeToCalcGeneration = endTime - startTime\n", "step-3": "<mask token>\n\n\nclass Playground:\n \"\"\"\n The playground for the program. All cells are stored here. This object also import/export cells to the playground\n\n :param screen: The screen object.\n :param mouse: The mouse object.\n :param keyboard: The keyboard object.\n :param root: The root object.\n\n Attributes: \n cells: All the cells that is on the playground. \n clickSwitch: The size of the one grid box in pixels.\n \"\"\"\n\n def __init__(self, root, screen, mouse, keyboard):\n self.root = root\n self.screen = screen\n self.mouse = mouse\n self.keyboard = keyboard\n self.cells = []\n self.clickSwitch = False\n self.autoGenerateMode = False\n self.generation = 0\n self.timeToCalcGeneration = 0\n self.bindKeyboardKeysToFunctions()\n\n def bindKeyboardKeysToFunctions(self):\n \"\"\" \n Binds diffrent functions to keyboard presses. \n :return: (nothing)\n \"\"\"\n self.keyboard.bindFunctionToKey('space', self.nextGeneration)\n\n def updatePlayground(self):\n \"\"\" \n Updates the playground. Checking for user input to interact with the playground.\n :return: (nothing)\n \"\"\"\n self.getMouseInput()\n if self.autoGenerateMode:\n self.nextGeneration()\n\n def getMouseInput(self):\n \"\"\"\n This method is getting the mouse and doing diffrent thing with it. For example: spawning a new cell if the user click on an grid-box.\n :return: (nothing)\n \"\"\"\n xPos = self.mouse.xGridPos\n yPos = self.mouse.yGridPos\n if self.getCellFromPosition(xPos, yPos):\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#ff0000')\n else:\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#00ff00')\n if self.mouse.leftButton and self.clickSwitch == False:\n if self.keyboard.shiftKey:\n clickedCell = self.getCellFromPosition(xPos, yPos)\n if clickedCell == False:\n self.createCell(xPos, yPos)\n else:\n self.deleteCell(clickedCell)\n self.clickSwitch = True\n if self.mouse.leftButton == False and self.clickSwitch == True:\n self.clickSwitch = False\n\n def deleteCell(self, cell):\n \"\"\"\n Deleting a cell from the cell-list.\n :param cell: The cell that is going to be delete.\n :return: (nothing)\n \"\"\"\n index = self.cells.index(cell)\n self.cells[index].delete()\n self.cells.remove(cell)\n\n def createCell(self, xPos, yPos):\n \"\"\"\n Creates a new cell for a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: (nothing)\n \"\"\"\n self.cells.append(Cell(self.screen, xPos, yPos))\n\n def getCellFromPosition(self, xPos, yPos):\n \"\"\"\n Gets a cell from a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: Cell\n \"\"\"\n for cell in self.cells:\n if xPos == cell.x and yPos == cell.y:\n return cell\n return False\n\n def clearPlayground(self):\n \"\"\"\n Removes all the cells from the playground\n :return: (nothing)\n \"\"\"\n for cell in self.cells:\n cell.delete()\n self.cells = []\n self.generation = 0\n\n def importPlayground(self, filepath):\n \"\"\"\n This function is importing a playground.\n :param filepath: The filepath to import the playground to. \n :return: (nothing)\n \"\"\"\n cellOutOfBound = False\n avgXPos = 0\n avgYPos = 0\n fileWrite = open(filepath, 'r')\n cellPositions = fileWrite.readlines()\n self.clearPlayground()\n for cellPos in cellPositions:\n cleanCellPos = fileTools.cleanString(cellPos)\n if cleanCellPos == '':\n continue\n cleanCellPos = self.checkFileFormat(cleanCellPos)\n if cleanCellPos:\n cellXPos, cellYPos = cleanCellPos\n else:\n return\n if (cellXPos > self.screen.worldSize or cellYPos > self.screen.\n worldSize or cellXPos < 0 or cellYPos < 0):\n cellOutOfBound = True\n else:\n newCell = Cell(self.screen, cellXPos, cellYPos)\n rectCellPos = self.screen.canvas.coords(newCell.rect)\n avgXPos += rectCellPos[0]\n avgYPos += rectCellPos[1]\n self.cells.append(newCell)\n if cellOutOfBound:\n messagebox.showwarning('Warning!',\n 'Some cells are placed outside of the playground!')\n avgXPos /= len(cellPositions)\n avgYPos /= len(cellPositions)\n self.screen.offsetX += avgXPos - self.screen.width / 2\n self.screen.offsetY += avgYPos - self.screen.height / 2\n\n def exportPlayground(self, filepath):\n \"\"\"\n This function is exporting a playground.\n :param filepath: The filepath to export the playground to. \n :return: (nothing)\n \"\"\"\n cellPositions = ''\n for cell in self.cells:\n if cell.dead == False:\n cellPositions += str(cell.x) + ' ' + str(cell.y) + '\\n'\n fileWrite = open(filepath, 'w')\n fileWrite.write(cellPositions)\n fileWrite.close()\n\n def checkFileFormat(self, cellPos):\n \"\"\"\n Checks if the file has the right format for this program.\n :param fileContent: The content of the file\n :return: The positions in a tuple, (x, y), false if there is an error.\n \"\"\"\n try:\n cellPosList = cellPos.split()\n cellXPos = int(cellPosList[0])\n cellYPos = int(cellPosList[1])\n except ValueError:\n messagebox.showerror('Error: Wrong format',\n 'The choosen file do not have the correct format. Be so kind to choose an other file.'\n )\n return False\n pass\n return cellXPos, cellYPos\n\n def removeCells(self, cellArray):\n \"\"\"\n Deletes all the cells from the array and playground.\n :param cellArray: The array of cells to delete.\n :return: (nothing)\n \"\"\"\n for cell in cellArray:\n cell.delete()\n self.cells.remove(cell)\n\n def setNeighbors(self):\n \"\"\"\n Creates dead cells around all living cells and calculating all the neighbors for the dead and the living cells\n :return: (nothing)\n \"\"\"\n for cellIndex in range(len(self.cells)):\n cell = self.cells[cellIndex]\n for neighborsX in range(cell.x - 1, cell.x + 2):\n for neighborsY in range(cell.y - 1, cell.y + 2):\n neighborsX = neighborsX % self.screen.worldSize\n neighborsY = neighborsY % self.screen.worldSize\n if neighborsX == cell.x and neighborsY == cell.y:\n continue\n else:\n cellToCheck = self.getCellFromPosition(neighborsX,\n neighborsY)\n if cellToCheck != False:\n cellToCheck.numOfNeighbor += 1\n else:\n newCell = Cell(self.screen, neighborsX,\n neighborsY, True)\n newCell.numOfNeighbor += 1\n self.cells.append(newCell)\n\n def checkAmountOfNeighbors(self):\n \"\"\"\n Check the amount of neighbors and kills or creates new cell depending on the amount.\n :return: (nothing)\n \"\"\"\n cellsToDelete = []\n for cell in self.cells:\n if (cell.numOfNeighbor > 3 or cell.numOfNeighbor < 2 or cell.\n numOfNeighbor == 2 and cell.dead == True):\n cellsToDelete.append(cell)\n elif cell.numOfNeighbor == 3 and cell.dead == True:\n cell.makeAlive()\n cell.numOfNeighbor = 0\n self.removeCells(cellsToDelete)\n\n def nextGeneration(self):\n \"\"\"\n This method is updating the cells to the next generation.\n :return: (nothing)\n\n Thanks to Martins for the idea to have modolu of the current posotion.\n \"\"\"\n startTime = int(round(time.time() * 100000))\n self.generation += 1\n self.setNeighbors()\n self.checkAmountOfNeighbors()\n endTime = int(round(time.time() * 100000))\n self.timeToCalcGeneration = endTime - startTime\n", "step-4": "from cell import Cell\nfrom tkinter import messagebox\nimport time\nimport fileTools\n\n\nclass Playground:\n \"\"\"\n The playground for the program. All cells are stored here. This object also import/export cells to the playground\n\n :param screen: The screen object.\n :param mouse: The mouse object.\n :param keyboard: The keyboard object.\n :param root: The root object.\n\n Attributes: \n cells: All the cells that is on the playground. \n clickSwitch: The size of the one grid box in pixels.\n \"\"\"\n\n def __init__(self, root, screen, mouse, keyboard):\n self.root = root\n self.screen = screen\n self.mouse = mouse\n self.keyboard = keyboard\n self.cells = []\n self.clickSwitch = False\n self.autoGenerateMode = False\n self.generation = 0\n self.timeToCalcGeneration = 0\n self.bindKeyboardKeysToFunctions()\n\n def bindKeyboardKeysToFunctions(self):\n \"\"\" \n Binds diffrent functions to keyboard presses. \n :return: (nothing)\n \"\"\"\n self.keyboard.bindFunctionToKey('space', self.nextGeneration)\n\n def updatePlayground(self):\n \"\"\" \n Updates the playground. Checking for user input to interact with the playground.\n :return: (nothing)\n \"\"\"\n self.getMouseInput()\n if self.autoGenerateMode:\n self.nextGeneration()\n\n def getMouseInput(self):\n \"\"\"\n This method is getting the mouse and doing diffrent thing with it. For example: spawning a new cell if the user click on an grid-box.\n :return: (nothing)\n \"\"\"\n xPos = self.mouse.xGridPos\n yPos = self.mouse.yGridPos\n if self.getCellFromPosition(xPos, yPos):\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#ff0000')\n else:\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill=\n '#00ff00')\n if self.mouse.leftButton and self.clickSwitch == False:\n if self.keyboard.shiftKey:\n clickedCell = self.getCellFromPosition(xPos, yPos)\n if clickedCell == False:\n self.createCell(xPos, yPos)\n else:\n self.deleteCell(clickedCell)\n self.clickSwitch = True\n if self.mouse.leftButton == False and self.clickSwitch == True:\n self.clickSwitch = False\n\n def deleteCell(self, cell):\n \"\"\"\n Deleting a cell from the cell-list.\n :param cell: The cell that is going to be delete.\n :return: (nothing)\n \"\"\"\n index = self.cells.index(cell)\n self.cells[index].delete()\n self.cells.remove(cell)\n\n def createCell(self, xPos, yPos):\n \"\"\"\n Creates a new cell for a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: (nothing)\n \"\"\"\n self.cells.append(Cell(self.screen, xPos, yPos))\n\n def getCellFromPosition(self, xPos, yPos):\n \"\"\"\n Gets a cell from a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: Cell\n \"\"\"\n for cell in self.cells:\n if xPos == cell.x and yPos == cell.y:\n return cell\n return False\n\n def clearPlayground(self):\n \"\"\"\n Removes all the cells from the playground\n :return: (nothing)\n \"\"\"\n for cell in self.cells:\n cell.delete()\n self.cells = []\n self.generation = 0\n\n def importPlayground(self, filepath):\n \"\"\"\n This function is importing a playground.\n :param filepath: The filepath to import the playground to. \n :return: (nothing)\n \"\"\"\n cellOutOfBound = False\n avgXPos = 0\n avgYPos = 0\n fileWrite = open(filepath, 'r')\n cellPositions = fileWrite.readlines()\n self.clearPlayground()\n for cellPos in cellPositions:\n cleanCellPos = fileTools.cleanString(cellPos)\n if cleanCellPos == '':\n continue\n cleanCellPos = self.checkFileFormat(cleanCellPos)\n if cleanCellPos:\n cellXPos, cellYPos = cleanCellPos\n else:\n return\n if (cellXPos > self.screen.worldSize or cellYPos > self.screen.\n worldSize or cellXPos < 0 or cellYPos < 0):\n cellOutOfBound = True\n else:\n newCell = Cell(self.screen, cellXPos, cellYPos)\n rectCellPos = self.screen.canvas.coords(newCell.rect)\n avgXPos += rectCellPos[0]\n avgYPos += rectCellPos[1]\n self.cells.append(newCell)\n if cellOutOfBound:\n messagebox.showwarning('Warning!',\n 'Some cells are placed outside of the playground!')\n avgXPos /= len(cellPositions)\n avgYPos /= len(cellPositions)\n self.screen.offsetX += avgXPos - self.screen.width / 2\n self.screen.offsetY += avgYPos - self.screen.height / 2\n\n def exportPlayground(self, filepath):\n \"\"\"\n This function is exporting a playground.\n :param filepath: The filepath to export the playground to. \n :return: (nothing)\n \"\"\"\n cellPositions = ''\n for cell in self.cells:\n if cell.dead == False:\n cellPositions += str(cell.x) + ' ' + str(cell.y) + '\\n'\n fileWrite = open(filepath, 'w')\n fileWrite.write(cellPositions)\n fileWrite.close()\n\n def checkFileFormat(self, cellPos):\n \"\"\"\n Checks if the file has the right format for this program.\n :param fileContent: The content of the file\n :return: The positions in a tuple, (x, y), false if there is an error.\n \"\"\"\n try:\n cellPosList = cellPos.split()\n cellXPos = int(cellPosList[0])\n cellYPos = int(cellPosList[1])\n except ValueError:\n messagebox.showerror('Error: Wrong format',\n 'The choosen file do not have the correct format. Be so kind to choose an other file.'\n )\n return False\n pass\n return cellXPos, cellYPos\n\n def removeCells(self, cellArray):\n \"\"\"\n Deletes all the cells from the array and playground.\n :param cellArray: The array of cells to delete.\n :return: (nothing)\n \"\"\"\n for cell in cellArray:\n cell.delete()\n self.cells.remove(cell)\n\n def setNeighbors(self):\n \"\"\"\n Creates dead cells around all living cells and calculating all the neighbors for the dead and the living cells\n :return: (nothing)\n \"\"\"\n for cellIndex in range(len(self.cells)):\n cell = self.cells[cellIndex]\n for neighborsX in range(cell.x - 1, cell.x + 2):\n for neighborsY in range(cell.y - 1, cell.y + 2):\n neighborsX = neighborsX % self.screen.worldSize\n neighborsY = neighborsY % self.screen.worldSize\n if neighborsX == cell.x and neighborsY == cell.y:\n continue\n else:\n cellToCheck = self.getCellFromPosition(neighborsX,\n neighborsY)\n if cellToCheck != False:\n cellToCheck.numOfNeighbor += 1\n else:\n newCell = Cell(self.screen, neighborsX,\n neighborsY, True)\n newCell.numOfNeighbor += 1\n self.cells.append(newCell)\n\n def checkAmountOfNeighbors(self):\n \"\"\"\n Check the amount of neighbors and kills or creates new cell depending on the amount.\n :return: (nothing)\n \"\"\"\n cellsToDelete = []\n for cell in self.cells:\n if (cell.numOfNeighbor > 3 or cell.numOfNeighbor < 2 or cell.\n numOfNeighbor == 2 and cell.dead == True):\n cellsToDelete.append(cell)\n elif cell.numOfNeighbor == 3 and cell.dead == True:\n cell.makeAlive()\n cell.numOfNeighbor = 0\n self.removeCells(cellsToDelete)\n\n def nextGeneration(self):\n \"\"\"\n This method is updating the cells to the next generation.\n :return: (nothing)\n\n Thanks to Martins for the idea to have modolu of the current posotion.\n \"\"\"\n startTime = int(round(time.time() * 100000))\n self.generation += 1\n self.setNeighbors()\n self.checkAmountOfNeighbors()\n endTime = int(round(time.time() * 100000))\n self.timeToCalcGeneration = endTime - startTime\n", "step-5": "from cell import Cell\nfrom tkinter import messagebox\nimport time\nimport fileTools\n\nclass Playground:\n\n \"\"\"\n The playground for the program. All cells are stored here. This object also import/export cells to the playground\n\n :param screen: The screen object.\n :param mouse: The mouse object.\n :param keyboard: The keyboard object.\n :param root: The root object.\n\n Attributes: \n cells: All the cells that is on the playground. \n clickSwitch: The size of the one grid box in pixels.\n \"\"\"\n\n def __init__(self, root, screen, mouse, keyboard):\n self.root = root\n self.screen = screen\n self.mouse = mouse\n self.keyboard = keyboard\n self.cells = []\n\n self.clickSwitch = False\n self.autoGenerateMode = False\n self.generation = 0\n self.timeToCalcGeneration = 0\n\n self.bindKeyboardKeysToFunctions()\n\n \n def bindKeyboardKeysToFunctions(self):\n \"\"\" \n Binds diffrent functions to keyboard presses. \n :return: (nothing)\n \"\"\"\n self.keyboard.bindFunctionToKey(\"space\", self.nextGeneration)\n\n\n def updatePlayground(self):\n \"\"\" \n Updates the playground. Checking for user input to interact with the playground.\n :return: (nothing)\n \"\"\"\n self.getMouseInput()\n if(self.autoGenerateMode):\n self.nextGeneration()\n\n\n def getMouseInput(self):\n \"\"\"\n This method is getting the mouse and doing diffrent thing with it. For example: spawning a new cell if the user click on an grid-box.\n :return: (nothing)\n \"\"\"\n xPos = self.mouse.xGridPos\n yPos = self.mouse.yGridPos\n\n #Changing the hoverblock color depending if the mouse is hovering over an living cell or not.\n if(self.getCellFromPosition(xPos, yPos)):\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill='#ff0000')\n else:\n self.screen.canvas.itemconfig(self.screen.hoverBlock, fill='#00ff00')\n\n #Placing an cell on the playground if the user is clicking on the playground\n if(self.mouse.leftButton and self.clickSwitch == False):\n if(self.keyboard.shiftKey):\n clickedCell = self.getCellFromPosition(xPos, yPos)\n if(clickedCell == False):\n self.createCell(xPos, yPos)\n else:\n self.deleteCell(clickedCell)\n self.clickSwitch = True\n\n if (self.mouse.leftButton == False and self.clickSwitch == True):\n self.clickSwitch = False\n \n\n def deleteCell(self, cell):\n \"\"\"\n Deleting a cell from the cell-list.\n :param cell: The cell that is going to be delete.\n :return: (nothing)\n \"\"\"\n index = self.cells.index(cell)\n self.cells[index].delete()\n self.cells.remove(cell)\n\n\n def createCell(self, xPos, yPos):\n \"\"\"\n Creates a new cell for a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: (nothing)\n \"\"\"\n self.cells.append(Cell(self.screen, xPos, yPos))\n\n\n def getCellFromPosition(self, xPos, yPos):\n \"\"\"\n Gets a cell from a given position.\n :param xPos: The x-position on the grid.\n :param yPos: the y-position on the grid\n :return: Cell\n \"\"\"\n for cell in self.cells:\n if(xPos == cell.x and yPos == cell.y):\n return cell\n return False\n\n\n def clearPlayground(self):\n \"\"\"\n Removes all the cells from the playground\n :return: (nothing)\n \"\"\"\n\n for cell in self.cells:\n cell.delete()\n self.cells = []\n self.generation = 0\n\n\n def importPlayground(self, filepath):\n \"\"\"\n This function is importing a playground.\n :param filepath: The filepath to import the playground to. \n :return: (nothing)\n \"\"\"\n\n cellOutOfBound = False\n avgXPos = 0\n avgYPos = 0\n fileWrite = open(filepath, \"r\")\n cellPositions = fileWrite.readlines()\n\n self.clearPlayground()\n \n for cellPos in cellPositions:\n\n #Cleans the string\n cleanCellPos = fileTools.cleanString(cellPos)\n if(cleanCellPos == \"\"):\n continue\n\n #Check the format.\n cleanCellPos = self.checkFileFormat(cleanCellPos)\n if(cleanCellPos):\n cellXPos, cellYPos = cleanCellPos\n else:\n return\n\n #Checks if the coords is outside the world.\n if(cellXPos > self.screen.worldSize or cellYPos > self.screen.worldSize or cellXPos < 0 or cellYPos < 0):\n cellOutOfBound = True\n else:\n newCell = Cell(self.screen, cellXPos, cellYPos)\n rectCellPos = self.screen.canvas.coords(newCell.rect)\n avgXPos += rectCellPos[0]; avgYPos += rectCellPos[1]\n\n self.cells.append(newCell)\n\n #Print warning that some cells are not renderd.\n if(cellOutOfBound):\n messagebox.showwarning(\"Warning!\", \"Some cells are placed outside of the playground!\")\n\n #Moving the user to where the cells are.\n avgXPos /= len(cellPositions); avgYPos /= len(cellPositions)\n self.screen.offsetX += avgXPos - self.screen.width/2\n self.screen.offsetY += avgYPos - self.screen.height/2\n\n\n def exportPlayground(self, filepath):\n \"\"\"\n This function is exporting a playground.\n :param filepath: The filepath to export the playground to. \n :return: (nothing)\n \"\"\"\n cellPositions = \"\"\n for cell in self.cells:\n if(cell.dead == False):\n cellPositions += str(cell.x) + \" \" + str(cell.y) + \"\\n\"\n \n fileWrite = open(filepath, \"w\")\n fileWrite.write(cellPositions)\n fileWrite.close()\n \n\n def checkFileFormat(self, cellPos):\n \"\"\"\n Checks if the file has the right format for this program.\n :param fileContent: The content of the file\n :return: The positions in a tuple, (x, y), false if there is an error.\n \"\"\"\n try:\n cellPosList = cellPos.split()\n cellXPos = int(cellPosList[0])\n cellYPos = int(cellPosList[1])\n except ValueError:\n messagebox.showerror(\"Error: Wrong format\", \"The choosen file do not have the correct format. Be so kind to choose an other file.\")\n return False\n pass\n\n return (cellXPos, cellYPos)\n\n\n def removeCells(self, cellArray):\n \"\"\"\n Deletes all the cells from the array and playground.\n :param cellArray: The array of cells to delete.\n :return: (nothing)\n \"\"\"\n for cell in cellArray:\n cell.delete()\n self.cells.remove(cell)\n\n\n def setNeighbors(self):\n \"\"\"\n Creates dead cells around all living cells and calculating all the neighbors for the dead and the living cells\n :return: (nothing)\n \"\"\"\n for cellIndex in range(len(self.cells)):\n cell = self.cells[cellIndex]\n\n #Checks the 8 cells around the living one. \n for neighborsX in range(cell.x - 1, cell.x + 2):\n for neighborsY in range(cell.y - 1, cell.y + 2):\n\n #If the position is outside the world, loop around.\n neighborsX = neighborsX % self.screen.worldSize\n neighborsY = neighborsY % self.screen.worldSize\n\n #Skipping itself. Becouse we do not want to calculate itself as a neighbor\n if(neighborsX == cell.x and neighborsY == cell.y):\n continue\n else:\n #Checks if a cell exist at neighborsX, neighborsY\n cellToCheck = self.getCellFromPosition(neighborsX, neighborsY)\n if(cellToCheck != False):\n #Add one to the neighbor var if there already exist and cell for the given position.\n cellToCheck.numOfNeighbor += 1\n else:\n #Creates a new cell if it do not exist any.\n newCell = Cell(self.screen, neighborsX, neighborsY, True)\n newCell.numOfNeighbor += 1\n self.cells.append(newCell)\n\n\n def checkAmountOfNeighbors(self):\n \"\"\"\n Check the amount of neighbors and kills or creates new cell depending on the amount.\n :return: (nothing)\n \"\"\"\n cellsToDelete = []\n for cell in self.cells:\n if(cell.numOfNeighbor > 3 or cell.numOfNeighbor < 2 or (cell.numOfNeighbor == 2 and cell.dead == True)):\n cellsToDelete.append(cell)\n elif(cell.numOfNeighbor == 3 and cell.dead == True):\n cell.makeAlive()\n cell.numOfNeighbor = 0\n\n self.removeCells(cellsToDelete)\n\n def nextGeneration(self):\n \"\"\"\n This method is updating the cells to the next generation.\n :return: (nothing)\n\n Thanks to Martins for the idea to have modolu of the current posotion.\n \"\"\"\n\n # Start a timer to calculate the time the render one generation.\n startTime = int(round(time.time() * 100000))\n\n self.generation += 1\n\n self.setNeighbors()\n self.checkAmountOfNeighbors()\n\n # Ends a timer to calculate the time the render one generation.\n endTime = int(round(time.time() * 100000))\n self.timeToCalcGeneration = (endTime - startTime)\n", "step-ids": [ 12, 16, 17, 18, 19 ] }
[ 12, 16, 17, 18, 19 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @pytest.mark.slow @pytest.mark.skipif('flair' not in sys.modules, reason= 'requires the Flair library') def test_flair_simple(small_dataset): flair_model = FlairModel(model_path='ner', entities_to_keep=['PERSON']) evaluator = Evaluator(model=flair_model) evaluation_results = evaluator.evaluate_all(small_dataset) scores = evaluator.calculate_score(evaluation_results) assert_model_results_gt(scores, 'PERSON', 0) <|reserved_special_token_1|> import sys import pytest from presidio_evaluator.evaluation import Evaluator from tests.conftest import assert_model_results_gt from presidio_evaluator.models.flair_model import FlairModel @pytest.mark.slow @pytest.mark.skipif('flair' not in sys.modules, reason= 'requires the Flair library') def test_flair_simple(small_dataset): flair_model = FlairModel(model_path='ner', entities_to_keep=['PERSON']) evaluator = Evaluator(model=flair_model) evaluation_results = evaluator.evaluate_all(small_dataset) scores = evaluator.calculate_score(evaluation_results) assert_model_results_gt(scores, 'PERSON', 0) <|reserved_special_token_1|> import sys import pytest from presidio_evaluator.evaluation import Evaluator from tests.conftest import assert_model_results_gt from presidio_evaluator.models.flair_model import FlairModel @pytest.mark.slow @pytest.mark.skipif("flair" not in sys.modules, reason="requires the Flair library") def test_flair_simple(small_dataset): flair_model = FlairModel(model_path="ner", entities_to_keep=["PERSON"]) evaluator = Evaluator(model=flair_model) evaluation_results = evaluator.evaluate_all(small_dataset) scores = evaluator.calculate_score(evaluation_results) assert_model_results_gt(scores, "PERSON", 0)
flexible
{ "blob_id": "813d27e8f9c1a416dab2f891dd71e4791bb92dbb", "index": 1040, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\[email protected]\[email protected]('flair' not in sys.modules, reason=\n 'requires the Flair library')\ndef test_flair_simple(small_dataset):\n flair_model = FlairModel(model_path='ner', entities_to_keep=['PERSON'])\n evaluator = Evaluator(model=flair_model)\n evaluation_results = evaluator.evaluate_all(small_dataset)\n scores = evaluator.calculate_score(evaluation_results)\n assert_model_results_gt(scores, 'PERSON', 0)\n", "step-3": "import sys\nimport pytest\nfrom presidio_evaluator.evaluation import Evaluator\nfrom tests.conftest import assert_model_results_gt\nfrom presidio_evaluator.models.flair_model import FlairModel\n\n\[email protected]\[email protected]('flair' not in sys.modules, reason=\n 'requires the Flair library')\ndef test_flair_simple(small_dataset):\n flair_model = FlairModel(model_path='ner', entities_to_keep=['PERSON'])\n evaluator = Evaluator(model=flair_model)\n evaluation_results = evaluator.evaluate_all(small_dataset)\n scores = evaluator.calculate_score(evaluation_results)\n assert_model_results_gt(scores, 'PERSON', 0)\n", "step-4": "import sys\n\nimport pytest\n\nfrom presidio_evaluator.evaluation import Evaluator\nfrom tests.conftest import assert_model_results_gt\nfrom presidio_evaluator.models.flair_model import FlairModel\n\n\[email protected]\[email protected](\"flair\" not in sys.modules, reason=\"requires the Flair library\")\ndef test_flair_simple(small_dataset):\n\n flair_model = FlairModel(model_path=\"ner\", entities_to_keep=[\"PERSON\"])\n evaluator = Evaluator(model=flair_model)\n evaluation_results = evaluator.evaluate_all(small_dataset)\n scores = evaluator.calculate_score(evaluation_results)\n\n assert_model_results_gt(scores, \"PERSON\", 0)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import requests import os from slugify import slugify as PipSlugify import shutil # will install any valid .deb package def install_debian_package_binary(package_path): os.system("sudo dpkg -i {package_path}".format( package_path=package_path )) os.system("sudo apt-get install -f") def download_install_deb(package_path, package_url): download_file(package_path, package_url) install_debian_package_binary(package_path) remove_file(package_path) def install_apt_packages(packages): if not isinstance(packages, basestring): packages = " ".join(packages) os.system("sudo apt-get install -y {packages}".format(packages=packages)) # download a file available at source_url to target_path on the file system. def download_file(target_path, source_url): try: # NOTE the stream=True parameter r = requests.get(source_url, stream=True) with open(target_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return True # TODO: better exception handling except: return False def write_file(path, data, mode='w'): if os.path.exists(path) and mode is not 'a': pathBAK = path + ".bak" os.rename(path, pathBAK) with open(path, mode) as handle: handle.write(data) def remove_file(path, replace_with_backup=False): # make a backup backup_path = path + ".bak" shutil.copy(path, backup_path) # remove the file if os.path.exists(path): os.remove(path) # replace existing with backup if replace_with_backup and os.path.exists(backup_path): os.rename(path, backup_path) # abstract the library choice/implementation of slugify from the installer def slugify(*args, **kwargs): return PipSlugify(*args, **kwargs) def copy_and_backup_original(from_path, to_path): if os.path.exists(to_path): rename = to_path + ".bak" os.rename(to_path, rename) shutil.copytree(from_path, to_path)
normal
{ "blob_id": "f546eb40ee8a7308ded62532731561029e5ec335", "index": 7870, "step-1": "<mask token>\n\n\ndef download_install_deb(package_path, package_url):\n download_file(package_path, package_url)\n install_debian_package_binary(package_path)\n remove_file(package_path)\n\n\n<mask token>\n\n\ndef write_file(path, data, mode='w'):\n if os.path.exists(path) and mode is not 'a':\n pathBAK = path + '.bak'\n os.rename(path, pathBAK)\n with open(path, mode) as handle:\n handle.write(data)\n\n\ndef remove_file(path, replace_with_backup=False):\n backup_path = path + '.bak'\n shutil.copy(path, backup_path)\n if os.path.exists(path):\n os.remove(path)\n if replace_with_backup and os.path.exists(backup_path):\n os.rename(path, backup_path)\n\n\ndef slugify(*args, **kwargs):\n return PipSlugify(*args, **kwargs)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef download_install_deb(package_path, package_url):\n download_file(package_path, package_url)\n install_debian_package_binary(package_path)\n remove_file(package_path)\n\n\ndef install_apt_packages(packages):\n if not isinstance(packages, basestring):\n packages = ' '.join(packages)\n os.system('sudo apt-get install -y {packages}'.format(packages=packages))\n\n\n<mask token>\n\n\ndef write_file(path, data, mode='w'):\n if os.path.exists(path) and mode is not 'a':\n pathBAK = path + '.bak'\n os.rename(path, pathBAK)\n with open(path, mode) as handle:\n handle.write(data)\n\n\ndef remove_file(path, replace_with_backup=False):\n backup_path = path + '.bak'\n shutil.copy(path, backup_path)\n if os.path.exists(path):\n os.remove(path)\n if replace_with_backup and os.path.exists(backup_path):\n os.rename(path, backup_path)\n\n\ndef slugify(*args, **kwargs):\n return PipSlugify(*args, **kwargs)\n\n\ndef copy_and_backup_original(from_path, to_path):\n if os.path.exists(to_path):\n rename = to_path + '.bak'\n os.rename(to_path, rename)\n shutil.copytree(from_path, to_path)\n", "step-3": "<mask token>\n\n\ndef download_install_deb(package_path, package_url):\n download_file(package_path, package_url)\n install_debian_package_binary(package_path)\n remove_file(package_path)\n\n\ndef install_apt_packages(packages):\n if not isinstance(packages, basestring):\n packages = ' '.join(packages)\n os.system('sudo apt-get install -y {packages}'.format(packages=packages))\n\n\ndef download_file(target_path, source_url):\n try:\n r = requests.get(source_url, stream=True)\n with open(target_path, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n f.flush()\n return True\n except:\n return False\n\n\ndef write_file(path, data, mode='w'):\n if os.path.exists(path) and mode is not 'a':\n pathBAK = path + '.bak'\n os.rename(path, pathBAK)\n with open(path, mode) as handle:\n handle.write(data)\n\n\ndef remove_file(path, replace_with_backup=False):\n backup_path = path + '.bak'\n shutil.copy(path, backup_path)\n if os.path.exists(path):\n os.remove(path)\n if replace_with_backup and os.path.exists(backup_path):\n os.rename(path, backup_path)\n\n\ndef slugify(*args, **kwargs):\n return PipSlugify(*args, **kwargs)\n\n\ndef copy_and_backup_original(from_path, to_path):\n if os.path.exists(to_path):\n rename = to_path + '.bak'\n os.rename(to_path, rename)\n shutil.copytree(from_path, to_path)\n", "step-4": "<mask token>\n\n\ndef install_debian_package_binary(package_path):\n os.system('sudo dpkg -i {package_path}'.format(package_path=package_path))\n os.system('sudo apt-get install -f')\n\n\ndef download_install_deb(package_path, package_url):\n download_file(package_path, package_url)\n install_debian_package_binary(package_path)\n remove_file(package_path)\n\n\ndef install_apt_packages(packages):\n if not isinstance(packages, basestring):\n packages = ' '.join(packages)\n os.system('sudo apt-get install -y {packages}'.format(packages=packages))\n\n\ndef download_file(target_path, source_url):\n try:\n r = requests.get(source_url, stream=True)\n with open(target_path, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n f.flush()\n return True\n except:\n return False\n\n\ndef write_file(path, data, mode='w'):\n if os.path.exists(path) and mode is not 'a':\n pathBAK = path + '.bak'\n os.rename(path, pathBAK)\n with open(path, mode) as handle:\n handle.write(data)\n\n\ndef remove_file(path, replace_with_backup=False):\n backup_path = path + '.bak'\n shutil.copy(path, backup_path)\n if os.path.exists(path):\n os.remove(path)\n if replace_with_backup and os.path.exists(backup_path):\n os.rename(path, backup_path)\n\n\ndef slugify(*args, **kwargs):\n return PipSlugify(*args, **kwargs)\n\n\ndef copy_and_backup_original(from_path, to_path):\n if os.path.exists(to_path):\n rename = to_path + '.bak'\n os.rename(to_path, rename)\n shutil.copytree(from_path, to_path)\n", "step-5": "import requests\nimport os\nfrom slugify import slugify as PipSlugify\nimport shutil\n\n# will install any valid .deb package\ndef install_debian_package_binary(package_path):\n os.system(\"sudo dpkg -i {package_path}\".format(\n package_path=package_path\n ))\n os.system(\"sudo apt-get install -f\")\n\ndef download_install_deb(package_path, package_url):\n download_file(package_path, package_url)\n install_debian_package_binary(package_path)\n remove_file(package_path)\n\ndef install_apt_packages(packages):\n if not isinstance(packages, basestring):\n packages = \" \".join(packages)\n os.system(\"sudo apt-get install -y {packages}\".format(packages=packages))\n\n# download a file available at source_url to target_path on the file system.\ndef download_file(target_path, source_url):\n try:\n # NOTE the stream=True parameter\n r = requests.get(source_url, stream=True)\n with open(target_path, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024): \n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n f.flush()\n return True\n # TODO: better exception handling\n except:\n return False\n\n\ndef write_file(path, data, mode='w'):\n if os.path.exists(path) and mode is not 'a':\n pathBAK = path + \".bak\"\n os.rename(path, pathBAK)\n with open(path, mode) as handle:\n handle.write(data)\n\ndef remove_file(path, replace_with_backup=False):\n # make a backup\n backup_path = path + \".bak\"\n shutil.copy(path, backup_path)\n # remove the file\n if os.path.exists(path):\n os.remove(path)\n # replace existing with backup\n if replace_with_backup and os.path.exists(backup_path):\n os.rename(path, backup_path)\n\n# abstract the library choice/implementation of slugify from the installer\ndef slugify(*args, **kwargs):\n return PipSlugify(*args, **kwargs)\n\ndef copy_and_backup_original(from_path, to_path):\n if os.path.exists(to_path):\n rename = to_path + \".bak\"\n os.rename(to_path, rename)\n shutil.copytree(from_path, to_path)\n ", "step-ids": [ 4, 6, 7, 8, 10 ] }
[ 4, 6, 7, 8, 10 ]
""" Listing 1.36 Python extends the basic grouping syntax to add named groups. Using names to refer to groups makes it easier to modify the pattern over time, without having to also modify the code using the match results. To set the name of a group, use the syntax (?P<name>pattern) Use groupdict() to retrieve the dictionary mapping group names to substrings from the match. Named patterns are included in the ordered sequence returned by groups() as well. """ import re def main(): text = "This is some text -- with punctuation." print(text) print() patterns = [ r"^(?P<first_word>\w+)", r"(?P<last_word>\w+)\S*$", r"(?P<t_word>\bt\w+)\W+(?P<other_word>\w+)", r"(?P<ends_with_t>\w+t)\b" ] for pattern in patterns: regex = re.compile(pattern) match = regex.search(text) print(f"'{pattern}'") print(f" ", match.groups()) print(f" ", match.groupdict()) print() if __name__ == "__main__": main()
normal
{ "blob_id": "be6a2e45f735fe578392b03c3030890b6cd5b4bc", "index": 2865, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n text = 'This is some text -- with punctuation.'\n print(text)\n print()\n patterns = ['^(?P<first_word>\\\\w+)', '(?P<last_word>\\\\w+)\\\\S*$',\n '(?P<t_word>\\\\bt\\\\w+)\\\\W+(?P<other_word>\\\\w+)',\n '(?P<ends_with_t>\\\\w+t)\\\\b']\n for pattern in patterns:\n regex = re.compile(pattern)\n match = regex.search(text)\n print(f\"'{pattern}'\")\n print(f' ', match.groups())\n print(f' ', match.groupdict())\n print()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef main():\n text = 'This is some text -- with punctuation.'\n print(text)\n print()\n patterns = ['^(?P<first_word>\\\\w+)', '(?P<last_word>\\\\w+)\\\\S*$',\n '(?P<t_word>\\\\bt\\\\w+)\\\\W+(?P<other_word>\\\\w+)',\n '(?P<ends_with_t>\\\\w+t)\\\\b']\n for pattern in patterns:\n regex = re.compile(pattern)\n match = regex.search(text)\n print(f\"'{pattern}'\")\n print(f' ', match.groups())\n print(f' ', match.groupdict())\n print()\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "<mask token>\nimport re\n\n\ndef main():\n text = 'This is some text -- with punctuation.'\n print(text)\n print()\n patterns = ['^(?P<first_word>\\\\w+)', '(?P<last_word>\\\\w+)\\\\S*$',\n '(?P<t_word>\\\\bt\\\\w+)\\\\W+(?P<other_word>\\\\w+)',\n '(?P<ends_with_t>\\\\w+t)\\\\b']\n for pattern in patterns:\n regex = re.compile(pattern)\n match = regex.search(text)\n print(f\"'{pattern}'\")\n print(f' ', match.groups())\n print(f' ', match.groupdict())\n print()\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "\"\"\"\nListing 1.36\n\nPython extends the basic grouping syntax to add named groups. Using\nnames to refer to groups makes it easier to modify the pattern over\ntime, without having to also modify the code using the match results.\n\nTo set the name of a group, use the syntax (?P<name>pattern)\n\nUse groupdict() to retrieve the dictionary mapping group names to\nsubstrings from the match. Named patterns are included in the\nordered sequence returned by groups() as well.\n\"\"\"\nimport re\n\n\ndef main():\n text = \"This is some text -- with punctuation.\"\n print(text)\n print()\n\n patterns = [\n r\"^(?P<first_word>\\w+)\",\n r\"(?P<last_word>\\w+)\\S*$\",\n r\"(?P<t_word>\\bt\\w+)\\W+(?P<other_word>\\w+)\",\n r\"(?P<ends_with_t>\\w+t)\\b\"\n ]\n\n for pattern in patterns:\n regex = re.compile(pattern)\n match = regex.search(text)\n print(f\"'{pattern}'\")\n print(f\" \", match.groups())\n print(f\" \", match.groupdict())\n print()\n\n\nif __name__ == \"__main__\":\n main()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
""" You are given pre-order traversal with a slight modification. It includes null pointers when a particular node has nil left/right child. Reconstruct the binary tree with this information. Ex. [H, B, F, None, None, E, A, None, None, None, C, None, D, None, G, I, None, None, None] H / \ B C / \ \ F E D / \ A G / I """ # time: O(n) def contruct_tree(pre_order, index=0): index += 1 if index >= len(pre_order): raise IndexError('wtf is wrong with you?') root = pre_order[index] if root is None: return (None, index) node = BST(root) node.left, index = construct(pre_order, index) node.right, index = construct(pre_order, index) return (node, index) # my solution without recursion # works? def contruct_tree(pre_order): tree = BST(pre_order[0]) curr = tree stack = [] i = 0 while i < len(pre_order)-1: if curr is not None: curr.left = L[i+1] stack.append(curr) cur = curr.left else: curr = stack.pop() curr.right = L[i+1] cur = curr.right return tree
normal
{ "blob_id": "3aee336956ac6f962c34f51a27dc4abebf2cc7c8", "index": 8474, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef contruct_tree(pre_order, index=0):\n index += 1\n if index >= len(pre_order):\n raise IndexError('wtf is wrong with you?')\n root = pre_order[index]\n if root is None:\n return None, index\n node = BST(root)\n node.left, index = construct(pre_order, index)\n node.right, index = construct(pre_order, index)\n return node, index\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef contruct_tree(pre_order, index=0):\n index += 1\n if index >= len(pre_order):\n raise IndexError('wtf is wrong with you?')\n root = pre_order[index]\n if root is None:\n return None, index\n node = BST(root)\n node.left, index = construct(pre_order, index)\n node.right, index = construct(pre_order, index)\n return node, index\n\n\ndef contruct_tree(pre_order):\n tree = BST(pre_order[0])\n curr = tree\n stack = []\n i = 0\n while i < len(pre_order) - 1:\n if curr is not None:\n curr.left = L[i + 1]\n stack.append(curr)\n cur = curr.left\n else:\n curr = stack.pop()\n curr.right = L[i + 1]\n cur = curr.right\n return tree\n", "step-4": "\"\"\"\nYou are given pre-order traversal with a slight modification. \nIt includes null pointers when a particular node has nil left/right child. \nReconstruct the binary tree with this information.\n\nEx. [H, B, F, None, None, E, A, None, None, None, C, None, D, None, G, I, None, None, None]\n\n H\n / \\\n B C\n / \\ \\\nF E D\n / \\\n A G\n /\n I\n\"\"\"\n\n# time: O(n)\ndef contruct_tree(pre_order, index=0):\n index += 1\n if index >= len(pre_order):\n raise IndexError('wtf is wrong with you?')\n\n root = pre_order[index]\n if root is None:\n return (None, index)\n\n\n node = BST(root)\n node.left, index = construct(pre_order, index)\n node.right, index = construct(pre_order, index)\n\n return (node, index)\n\n\n# my solution without recursion\n# works?\n\ndef contruct_tree(pre_order):\n tree = BST(pre_order[0])\n curr = tree\n stack = []\n i = 0\n while i < len(pre_order)-1:\n if curr is not None:\n curr.left = L[i+1]\n stack.append(curr)\n cur = curr.left\n else:\n curr = stack.pop()\n curr.right = L[i+1]\n cur = curr.right\n\n return tree\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# -*- coding:utf-8 -*- from common import * import itertools def iteration_spider(): max_errors = 5 num_errors = 0 for page in itertools.count(1): url = 'http://example.webscraping.com/view/-{}'.format(page) html = download(url) if html is None: num_errors += 1 if num_errors == max_errors: break else: num_errors = 0 if __name__ == '__main__': iteration_spider()
normal
{ "blob_id": "0eaba8f570772de864f52168a597b47a4150d015", "index": 5924, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef iteration_spider():\n max_errors = 5\n num_errors = 0\n for page in itertools.count(1):\n url = 'http://example.webscraping.com/view/-{}'.format(page)\n html = download(url)\n if html is None:\n num_errors += 1\n if num_errors == max_errors:\n break\n else:\n num_errors = 0\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef iteration_spider():\n max_errors = 5\n num_errors = 0\n for page in itertools.count(1):\n url = 'http://example.webscraping.com/view/-{}'.format(page)\n html = download(url)\n if html is None:\n num_errors += 1\n if num_errors == max_errors:\n break\n else:\n num_errors = 0\n\n\nif __name__ == '__main__':\n iteration_spider()\n", "step-4": "from common import *\nimport itertools\n\n\ndef iteration_spider():\n max_errors = 5\n num_errors = 0\n for page in itertools.count(1):\n url = 'http://example.webscraping.com/view/-{}'.format(page)\n html = download(url)\n if html is None:\n num_errors += 1\n if num_errors == max_errors:\n break\n else:\n num_errors = 0\n\n\nif __name__ == '__main__':\n iteration_spider()\n", "step-5": "# -*- coding:utf-8 -*-\n\nfrom common import *\nimport itertools\n\ndef iteration_spider():\n\tmax_errors = 5\n\tnum_errors = 0\n\tfor page in itertools.count(1):\n\t\turl = 'http://example.webscraping.com/view/-{}'.format(page)\n\t\thtml = download(url)\n\t\tif html is None:\n\t\t\tnum_errors += 1\n\t\t\tif num_errors == max_errors:\n\t\t\t\tbreak\n\t\telse:\n\t\t\tnum_errors = 0\n\t\t\t\n\nif __name__ == '__main__':\n\titeration_spider()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/local/autopkg/python """ JamfScriptUploader processor for uploading items to Jamf Pro using AutoPkg by G Pugh """ import os.path import sys from time import sleep from autopkglib import ProcessorError # pylint: disable=import-error # to use a base module in AutoPkg we need to add this path to the sys.path. # this violates flake8 E402 (PEP8 imports) but is unavoidable, so the following # imports require noqa comments for E402 sys.path.insert(0, os.path.dirname(__file__)) from JamfUploaderLib.JamfUploaderBase import JamfUploaderBase # noqa: E402 __all__ = ["JamfScriptUploader"] class JamfScriptUploader(JamfUploaderBase): description = ( "A processor for AutoPkg that will upload a script to a Jamf Cloud or " "on-prem server." ) input_variables = { "JSS_URL": { "required": True, "description": "URL to a Jamf Pro server that the API user has write access " "to, optionally set as a key in the com.github.autopkg " "preference file.", }, "API_USERNAME": { "required": True, "description": "Username of account with appropriate access to " "jss, optionally set as a key in the com.github.autopkg " "preference file.", }, "API_PASSWORD": { "required": True, "description": "Password of api user, optionally set as a key in " "the com.github.autopkg preference file.", }, "script_path": { "required": False, "description": "Full path to the script to be uploaded", }, "script_name": { "required": False, "description": "Name of the script in Jamf", }, "script_category": { "required": False, "description": "Script category", "default": "", }, "script_priority": { "required": False, "description": "Script priority (BEFORE or AFTER)", "default": "AFTER", }, "osrequirements": { "required": False, "description": "Script OS requirements", "default": "", }, "script_info": { "required": False, "description": "Script info field", "default": "", }, "script_notes": { "required": False, "description": "Script notes field", "default": "", }, "script_parameter4": { "required": False, "description": "Script parameter 4 title", "default": "", }, "script_parameter5": { "required": False, "description": "Script parameter 5 title", "default": "", }, "script_parameter6": { "required": False, "description": "Script parameter 6 title", "default": "", }, "script_parameter7": { "required": False, "description": "Script parameter 7 title", "default": "", }, "script_parameter8": { "required": False, "description": "Script parameter 8 title", "default": "", }, "script_parameter9": { "required": False, "description": "Script parameter 9 title", "default": "", }, "script_parameter10": { "required": False, "description": "Script parameter 10 title", "default": "", }, "script_parameter11": { "required": False, "description": "Script parameter 11 title", "default": "", }, "replace_script": { "required": False, "description": "Overwrite an existing script if True.", "default": False, }, "sleep": { "required": False, "description": "Pause after running this processor for specified seconds.", "default": "0", }, } output_variables = { "script_name": { "required": False, "description": "Name of the uploaded script", }, "jamfscriptuploader_summary_result": { "description": "Description of interesting results.", }, } def upload_script( self, jamf_url, script_name, script_path, category_id, script_category, script_info, script_notes, script_priority, script_parameter4, script_parameter5, script_parameter6, script_parameter7, script_parameter8, script_parameter9, script_parameter10, script_parameter11, script_os_requirements, token, obj_id=0, ): """Update script metadata.""" # import script from file and replace any keys in the script if os.path.exists(script_path): with open(script_path, "r") as file: script_contents = file.read() else: raise ProcessorError("Script does not exist!") # substitute user-assignable keys script_contents = self.substitute_assignable_keys(script_contents) # priority has to be in upper case. Let's make it nice for the user if script_priority: script_priority = script_priority.upper() # build the object script_data = { "name": script_name, "info": script_info, "notes": script_notes, "priority": script_priority, "categoryId": category_id, "categoryName": script_category, "parameter4": script_parameter4, "parameter5": script_parameter5, "parameter6": script_parameter6, "parameter7": script_parameter7, "parameter8": script_parameter8, "parameter9": script_parameter9, "parameter10": script_parameter10, "parameter11": script_parameter11, "osRequirements": script_os_requirements, "scriptContents": script_contents, } self.output( "Script data:", verbose_level=2, ) self.output( script_data, verbose_level=2, ) script_json = self.write_json_file(script_data) self.output("Uploading script..") # if we find an object ID we put, if not, we post object_type = "script" if obj_id: url = "{}/{}/{}".format(jamf_url, self.api_endpoints(object_type), obj_id) else: url = "{}/{}".format(jamf_url, self.api_endpoints(object_type)) count = 0 while True: count += 1 self.output( "Script upload attempt {}".format(count), verbose_level=2, ) request = "PUT" if obj_id else "POST" r = self.curl(request=request, url=url, token=token, data=script_json) # check HTTP response if self.status_check(r, "Script", script_name, request) == "break": break if count > 5: self.output("Script upload did not succeed after 5 attempts") self.output("\nHTTP POST Response Code: {}".format(r.status_code)) raise ProcessorError("ERROR: Script upload failed ") if int(self.sleep) > 30: sleep(int(self.sleep)) else: sleep(30) return r def main(self): """Do the main thing here""" self.jamf_url = self.env.get("JSS_URL") self.jamf_user = self.env.get("API_USERNAME") self.jamf_password = self.env.get("API_PASSWORD") self.script_path = self.env.get("script_path") self.script_name = self.env.get("script_name") self.script_category = self.env.get("script_category") self.script_priority = self.env.get("script_priority") self.osrequirements = self.env.get("osrequirements") self.script_info = self.env.get("script_info") self.script_notes = self.env.get("script_notes") self.script_parameter4 = self.env.get("script_parameter4") self.script_parameter5 = self.env.get("script_parameter5") self.script_parameter6 = self.env.get("script_parameter6") self.script_parameter7 = self.env.get("script_parameter7") self.script_parameter8 = self.env.get("script_parameter8") self.script_parameter9 = self.env.get("script_parameter9") self.script_parameter10 = self.env.get("script_parameter10") self.script_parameter11 = self.env.get("script_parameter11") self.replace = self.env.get("replace_script") self.sleep = self.env.get("sleep") # handle setting replace in overrides if not self.replace or self.replace == "False": self.replace = False # clear any pre-existing summary result if "jamfscriptuploader_summary_result" in self.env: del self.env["jamfscriptuploader_summary_result"] script_uploaded = False # obtain the relevant credentials token = self.handle_uapi_auth(self.jamf_url, self.jamf_user, self.jamf_password) # get the id for a category if supplied if self.script_category: self.output("Checking categories for {}".format(self.script_category)) # check for existing category - requires obj_name obj_type = "category" obj_name = self.script_category category_id = self.get_uapi_obj_id_from_name( self.jamf_url, obj_type, obj_name, token, ) if not category_id: self.output("WARNING: Category not found!") category_id = "-1" else: self.output( "Category {} found: ID={}".format(self.script_category, category_id) ) else: self.script_category = "" category_id = "-1" # handle files with a relative path if not self.script_path.startswith("/"): found_template = self.get_path_to_file(self.script_path) if found_template: self.script_path = found_template else: raise ProcessorError(f"ERROR: Script file {self.script_path} not found") # now start the process of uploading the object if not self.script_name: self.script_name = os.path.basename(self.script_path) # check for existing script self.output( "Checking for existing '{}' on {}".format(self.script_name, self.jamf_url) ) self.output( "Full path: {}".format(self.script_path), verbose_level=2, ) obj_type = "script" obj_name = self.script_name obj_id = self.get_uapi_obj_id_from_name( self.jamf_url, obj_type, obj_name, token, ) if obj_id: self.output( "Script '{}' already exists: ID {}".format(self.script_name, obj_id) ) if self.replace: self.output( "Replacing existing script as 'replace_script' is set to {}".format( self.replace ), verbose_level=1, ) else: self.output( "Not replacing existing script. Use replace_script='True' to enforce.", verbose_level=1, ) return # post the script self.upload_script( self.jamf_url, self.script_name, self.script_path, category_id, self.script_category, self.script_info, self.script_notes, self.script_priority, self.script_parameter4, self.script_parameter5, self.script_parameter6, self.script_parameter7, self.script_parameter8, self.script_parameter9, self.script_parameter10, self.script_parameter11, self.osrequirements, token, obj_id, ) script_uploaded = True # output the summary self.env["script_name"] = self.script_name self.env["script_uploaded"] = script_uploaded if script_uploaded: self.env["jamfscriptuploader_summary_result"] = { "summary_text": "The following scripts were created or updated in Jamf Pro:", "report_fields": [ "script", "path", "category", "priority", "os_req", "info", "notes", "P4", "P5", "P6", "P7", "P8", "P9", "P10", "P11", ], "data": { "script": self.script_name, "path": self.script_path, "category": self.script_category, "priority": str(self.script_priority), "info": self.script_info, "os_req": self.osrequirements, "notes": self.script_notes, "P4": self.script_parameter4, "P5": self.script_parameter5, "P6": self.script_parameter6, "P7": self.script_parameter7, "P8": self.script_parameter8, "P9": self.script_parameter9, "P10": self.script_parameter10, "P11": self.script_parameter11, }, } if __name__ == "__main__": PROCESSOR = JamfScriptUploader() PROCESSOR.execute_shell()
normal
{ "blob_id": "35d99713df754052a006f76bb6f3cfe9cf875c0b", "index": 3993, "step-1": "<mask token>\n\n\nclass JamfScriptUploader(JamfUploaderBase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass JamfScriptUploader(JamfUploaderBase):\n description = (\n 'A processor for AutoPkg that will upload a script to a Jamf Cloud or on-prem server.'\n )\n input_variables = {'JSS_URL': {'required': True, 'description':\n 'URL to a Jamf Pro server that the API user has write access to, optionally set as a key in the com.github.autopkg preference file.'\n }, 'API_USERNAME': {'required': True, 'description':\n 'Username of account with appropriate access to jss, optionally set as a key in the com.github.autopkg preference file.'\n }, 'API_PASSWORD': {'required': True, 'description':\n 'Password of api user, optionally set as a key in the com.github.autopkg preference file.'\n }, 'script_path': {'required': False, 'description':\n 'Full path to the script to be uploaded'}, 'script_name': {\n 'required': False, 'description': 'Name of the script in Jamf'},\n 'script_category': {'required': False, 'description':\n 'Script category', 'default': ''}, 'script_priority': {'required': \n False, 'description': 'Script priority (BEFORE or AFTER)',\n 'default': 'AFTER'}, 'osrequirements': {'required': False,\n 'description': 'Script OS requirements', 'default': ''},\n 'script_info': {'required': False, 'description':\n 'Script info field', 'default': ''}, 'script_notes': {'required': \n False, 'description': 'Script notes field', 'default': ''},\n 'script_parameter4': {'required': False, 'description':\n 'Script parameter 4 title', 'default': ''}, 'script_parameter5': {\n 'required': False, 'description': 'Script parameter 5 title',\n 'default': ''}, 'script_parameter6': {'required': False,\n 'description': 'Script parameter 6 title', 'default': ''},\n 'script_parameter7': {'required': False, 'description':\n 'Script parameter 7 title', 'default': ''}, 'script_parameter8': {\n 'required': False, 'description': 'Script parameter 8 title',\n 'default': ''}, 'script_parameter9': {'required': False,\n 'description': 'Script parameter 9 title', 'default': ''},\n 'script_parameter10': {'required': False, 'description':\n 'Script parameter 10 title', 'default': ''}, 'script_parameter11':\n {'required': False, 'description': 'Script parameter 11 title',\n 'default': ''}, 'replace_script': {'required': False, 'description':\n 'Overwrite an existing script if True.', 'default': False}, 'sleep':\n {'required': False, 'description':\n 'Pause after running this processor for specified seconds.',\n 'default': '0'}}\n output_variables = {'script_name': {'required': False, 'description':\n 'Name of the uploaded script'}, 'jamfscriptuploader_summary_result':\n {'description': 'Description of interesting results.'}}\n\n def upload_script(self, jamf_url, script_name, script_path, category_id,\n script_category, script_info, script_notes, script_priority,\n script_parameter4, script_parameter5, script_parameter6,\n script_parameter7, script_parameter8, script_parameter9,\n script_parameter10, script_parameter11, script_os_requirements,\n token, obj_id=0):\n \"\"\"Update script metadata.\"\"\"\n if os.path.exists(script_path):\n with open(script_path, 'r') as file:\n script_contents = file.read()\n else:\n raise ProcessorError('Script does not exist!')\n script_contents = self.substitute_assignable_keys(script_contents)\n if script_priority:\n script_priority = script_priority.upper()\n script_data = {'name': script_name, 'info': script_info, 'notes':\n script_notes, 'priority': script_priority, 'categoryId':\n category_id, 'categoryName': script_category, 'parameter4':\n script_parameter4, 'parameter5': script_parameter5,\n 'parameter6': script_parameter6, 'parameter7':\n script_parameter7, 'parameter8': script_parameter8,\n 'parameter9': script_parameter9, 'parameter10':\n script_parameter10, 'parameter11': script_parameter11,\n 'osRequirements': script_os_requirements, 'scriptContents':\n script_contents}\n self.output('Script data:', verbose_level=2)\n self.output(script_data, verbose_level=2)\n script_json = self.write_json_file(script_data)\n self.output('Uploading script..')\n object_type = 'script'\n if obj_id:\n url = '{}/{}/{}'.format(jamf_url, self.api_endpoints(\n object_type), obj_id)\n else:\n url = '{}/{}'.format(jamf_url, self.api_endpoints(object_type))\n count = 0\n while True:\n count += 1\n self.output('Script upload attempt {}'.format(count),\n verbose_level=2)\n request = 'PUT' if obj_id else 'POST'\n r = self.curl(request=request, url=url, token=token, data=\n script_json)\n if self.status_check(r, 'Script', script_name, request) == 'break':\n break\n if count > 5:\n self.output('Script upload did not succeed after 5 attempts')\n self.output('\\nHTTP POST Response Code: {}'.format(r.\n status_code))\n raise ProcessorError('ERROR: Script upload failed ')\n if int(self.sleep) > 30:\n sleep(int(self.sleep))\n else:\n sleep(30)\n return r\n\n def main(self):\n \"\"\"Do the main thing here\"\"\"\n self.jamf_url = self.env.get('JSS_URL')\n self.jamf_user = self.env.get('API_USERNAME')\n self.jamf_password = self.env.get('API_PASSWORD')\n self.script_path = self.env.get('script_path')\n self.script_name = self.env.get('script_name')\n self.script_category = self.env.get('script_category')\n self.script_priority = self.env.get('script_priority')\n self.osrequirements = self.env.get('osrequirements')\n self.script_info = self.env.get('script_info')\n self.script_notes = self.env.get('script_notes')\n self.script_parameter4 = self.env.get('script_parameter4')\n self.script_parameter5 = self.env.get('script_parameter5')\n self.script_parameter6 = self.env.get('script_parameter6')\n self.script_parameter7 = self.env.get('script_parameter7')\n self.script_parameter8 = self.env.get('script_parameter8')\n self.script_parameter9 = self.env.get('script_parameter9')\n self.script_parameter10 = self.env.get('script_parameter10')\n self.script_parameter11 = self.env.get('script_parameter11')\n self.replace = self.env.get('replace_script')\n self.sleep = self.env.get('sleep')\n if not self.replace or self.replace == 'False':\n self.replace = False\n if 'jamfscriptuploader_summary_result' in self.env:\n del self.env['jamfscriptuploader_summary_result']\n script_uploaded = False\n token = self.handle_uapi_auth(self.jamf_url, self.jamf_user, self.\n jamf_password)\n if self.script_category:\n self.output('Checking categories for {}'.format(self.\n script_category))\n obj_type = 'category'\n obj_name = self.script_category\n category_id = self.get_uapi_obj_id_from_name(self.jamf_url,\n obj_type, obj_name, token)\n if not category_id:\n self.output('WARNING: Category not found!')\n category_id = '-1'\n else:\n self.output('Category {} found: ID={}'.format(self.\n script_category, category_id))\n else:\n self.script_category = ''\n category_id = '-1'\n if not self.script_path.startswith('/'):\n found_template = self.get_path_to_file(self.script_path)\n if found_template:\n self.script_path = found_template\n else:\n raise ProcessorError(\n f'ERROR: Script file {self.script_path} not found')\n if not self.script_name:\n self.script_name = os.path.basename(self.script_path)\n self.output(\"Checking for existing '{}' on {}\".format(self.\n script_name, self.jamf_url))\n self.output('Full path: {}'.format(self.script_path), verbose_level=2)\n obj_type = 'script'\n obj_name = self.script_name\n obj_id = self.get_uapi_obj_id_from_name(self.jamf_url, obj_type,\n obj_name, token)\n if obj_id:\n self.output(\"Script '{}' already exists: ID {}\".format(self.\n script_name, obj_id))\n if self.replace:\n self.output(\n \"Replacing existing script as 'replace_script' is set to {}\"\n .format(self.replace), verbose_level=1)\n else:\n self.output(\n \"Not replacing existing script. Use replace_script='True' to enforce.\"\n , verbose_level=1)\n return\n self.upload_script(self.jamf_url, self.script_name, self.\n script_path, category_id, self.script_category, self.\n script_info, self.script_notes, self.script_priority, self.\n script_parameter4, self.script_parameter5, self.\n script_parameter6, self.script_parameter7, self.\n script_parameter8, self.script_parameter9, self.\n script_parameter10, self.script_parameter11, self.\n osrequirements, token, obj_id)\n script_uploaded = True\n self.env['script_name'] = self.script_name\n self.env['script_uploaded'] = script_uploaded\n if script_uploaded:\n self.env['jamfscriptuploader_summary_result'] = {'summary_text':\n 'The following scripts were created or updated in Jamf Pro:',\n 'report_fields': ['script', 'path', 'category', 'priority',\n 'os_req', 'info', 'notes', 'P4', 'P5', 'P6', 'P7', 'P8',\n 'P9', 'P10', 'P11'], 'data': {'script': self.script_name,\n 'path': self.script_path, 'category': self.script_category,\n 'priority': str(self.script_priority), 'info': self.\n script_info, 'os_req': self.osrequirements, 'notes': self.\n script_notes, 'P4': self.script_parameter4, 'P5': self.\n script_parameter5, 'P6': self.script_parameter6, 'P7': self\n .script_parameter7, 'P8': self.script_parameter8, 'P9':\n self.script_parameter9, 'P10': self.script_parameter10,\n 'P11': self.script_parameter11}}\n\n\n<mask token>\n", "step-3": "<mask token>\nsys.path.insert(0, os.path.dirname(__file__))\n<mask token>\n\n\nclass JamfScriptUploader(JamfUploaderBase):\n description = (\n 'A processor for AutoPkg that will upload a script to a Jamf Cloud or on-prem server.'\n )\n input_variables = {'JSS_URL': {'required': True, 'description':\n 'URL to a Jamf Pro server that the API user has write access to, optionally set as a key in the com.github.autopkg preference file.'\n }, 'API_USERNAME': {'required': True, 'description':\n 'Username of account with appropriate access to jss, optionally set as a key in the com.github.autopkg preference file.'\n }, 'API_PASSWORD': {'required': True, 'description':\n 'Password of api user, optionally set as a key in the com.github.autopkg preference file.'\n }, 'script_path': {'required': False, 'description':\n 'Full path to the script to be uploaded'}, 'script_name': {\n 'required': False, 'description': 'Name of the script in Jamf'},\n 'script_category': {'required': False, 'description':\n 'Script category', 'default': ''}, 'script_priority': {'required': \n False, 'description': 'Script priority (BEFORE or AFTER)',\n 'default': 'AFTER'}, 'osrequirements': {'required': False,\n 'description': 'Script OS requirements', 'default': ''},\n 'script_info': {'required': False, 'description':\n 'Script info field', 'default': ''}, 'script_notes': {'required': \n False, 'description': 'Script notes field', 'default': ''},\n 'script_parameter4': {'required': False, 'description':\n 'Script parameter 4 title', 'default': ''}, 'script_parameter5': {\n 'required': False, 'description': 'Script parameter 5 title',\n 'default': ''}, 'script_parameter6': {'required': False,\n 'description': 'Script parameter 6 title', 'default': ''},\n 'script_parameter7': {'required': False, 'description':\n 'Script parameter 7 title', 'default': ''}, 'script_parameter8': {\n 'required': False, 'description': 'Script parameter 8 title',\n 'default': ''}, 'script_parameter9': {'required': False,\n 'description': 'Script parameter 9 title', 'default': ''},\n 'script_parameter10': {'required': False, 'description':\n 'Script parameter 10 title', 'default': ''}, 'script_parameter11':\n {'required': False, 'description': 'Script parameter 11 title',\n 'default': ''}, 'replace_script': {'required': False, 'description':\n 'Overwrite an existing script if True.', 'default': False}, 'sleep':\n {'required': False, 'description':\n 'Pause after running this processor for specified seconds.',\n 'default': '0'}}\n output_variables = {'script_name': {'required': False, 'description':\n 'Name of the uploaded script'}, 'jamfscriptuploader_summary_result':\n {'description': 'Description of interesting results.'}}\n\n def upload_script(self, jamf_url, script_name, script_path, category_id,\n script_category, script_info, script_notes, script_priority,\n script_parameter4, script_parameter5, script_parameter6,\n script_parameter7, script_parameter8, script_parameter9,\n script_parameter10, script_parameter11, script_os_requirements,\n token, obj_id=0):\n \"\"\"Update script metadata.\"\"\"\n if os.path.exists(script_path):\n with open(script_path, 'r') as file:\n script_contents = file.read()\n else:\n raise ProcessorError('Script does not exist!')\n script_contents = self.substitute_assignable_keys(script_contents)\n if script_priority:\n script_priority = script_priority.upper()\n script_data = {'name': script_name, 'info': script_info, 'notes':\n script_notes, 'priority': script_priority, 'categoryId':\n category_id, 'categoryName': script_category, 'parameter4':\n script_parameter4, 'parameter5': script_parameter5,\n 'parameter6': script_parameter6, 'parameter7':\n script_parameter7, 'parameter8': script_parameter8,\n 'parameter9': script_parameter9, 'parameter10':\n script_parameter10, 'parameter11': script_parameter11,\n 'osRequirements': script_os_requirements, 'scriptContents':\n script_contents}\n self.output('Script data:', verbose_level=2)\n self.output(script_data, verbose_level=2)\n script_json = self.write_json_file(script_data)\n self.output('Uploading script..')\n object_type = 'script'\n if obj_id:\n url = '{}/{}/{}'.format(jamf_url, self.api_endpoints(\n object_type), obj_id)\n else:\n url = '{}/{}'.format(jamf_url, self.api_endpoints(object_type))\n count = 0\n while True:\n count += 1\n self.output('Script upload attempt {}'.format(count),\n verbose_level=2)\n request = 'PUT' if obj_id else 'POST'\n r = self.curl(request=request, url=url, token=token, data=\n script_json)\n if self.status_check(r, 'Script', script_name, request) == 'break':\n break\n if count > 5:\n self.output('Script upload did not succeed after 5 attempts')\n self.output('\\nHTTP POST Response Code: {}'.format(r.\n status_code))\n raise ProcessorError('ERROR: Script upload failed ')\n if int(self.sleep) > 30:\n sleep(int(self.sleep))\n else:\n sleep(30)\n return r\n\n def main(self):\n \"\"\"Do the main thing here\"\"\"\n self.jamf_url = self.env.get('JSS_URL')\n self.jamf_user = self.env.get('API_USERNAME')\n self.jamf_password = self.env.get('API_PASSWORD')\n self.script_path = self.env.get('script_path')\n self.script_name = self.env.get('script_name')\n self.script_category = self.env.get('script_category')\n self.script_priority = self.env.get('script_priority')\n self.osrequirements = self.env.get('osrequirements')\n self.script_info = self.env.get('script_info')\n self.script_notes = self.env.get('script_notes')\n self.script_parameter4 = self.env.get('script_parameter4')\n self.script_parameter5 = self.env.get('script_parameter5')\n self.script_parameter6 = self.env.get('script_parameter6')\n self.script_parameter7 = self.env.get('script_parameter7')\n self.script_parameter8 = self.env.get('script_parameter8')\n self.script_parameter9 = self.env.get('script_parameter9')\n self.script_parameter10 = self.env.get('script_parameter10')\n self.script_parameter11 = self.env.get('script_parameter11')\n self.replace = self.env.get('replace_script')\n self.sleep = self.env.get('sleep')\n if not self.replace or self.replace == 'False':\n self.replace = False\n if 'jamfscriptuploader_summary_result' in self.env:\n del self.env['jamfscriptuploader_summary_result']\n script_uploaded = False\n token = self.handle_uapi_auth(self.jamf_url, self.jamf_user, self.\n jamf_password)\n if self.script_category:\n self.output('Checking categories for {}'.format(self.\n script_category))\n obj_type = 'category'\n obj_name = self.script_category\n category_id = self.get_uapi_obj_id_from_name(self.jamf_url,\n obj_type, obj_name, token)\n if not category_id:\n self.output('WARNING: Category not found!')\n category_id = '-1'\n else:\n self.output('Category {} found: ID={}'.format(self.\n script_category, category_id))\n else:\n self.script_category = ''\n category_id = '-1'\n if not self.script_path.startswith('/'):\n found_template = self.get_path_to_file(self.script_path)\n if found_template:\n self.script_path = found_template\n else:\n raise ProcessorError(\n f'ERROR: Script file {self.script_path} not found')\n if not self.script_name:\n self.script_name = os.path.basename(self.script_path)\n self.output(\"Checking for existing '{}' on {}\".format(self.\n script_name, self.jamf_url))\n self.output('Full path: {}'.format(self.script_path), verbose_level=2)\n obj_type = 'script'\n obj_name = self.script_name\n obj_id = self.get_uapi_obj_id_from_name(self.jamf_url, obj_type,\n obj_name, token)\n if obj_id:\n self.output(\"Script '{}' already exists: ID {}\".format(self.\n script_name, obj_id))\n if self.replace:\n self.output(\n \"Replacing existing script as 'replace_script' is set to {}\"\n .format(self.replace), verbose_level=1)\n else:\n self.output(\n \"Not replacing existing script. Use replace_script='True' to enforce.\"\n , verbose_level=1)\n return\n self.upload_script(self.jamf_url, self.script_name, self.\n script_path, category_id, self.script_category, self.\n script_info, self.script_notes, self.script_priority, self.\n script_parameter4, self.script_parameter5, self.\n script_parameter6, self.script_parameter7, self.\n script_parameter8, self.script_parameter9, self.\n script_parameter10, self.script_parameter11, self.\n osrequirements, token, obj_id)\n script_uploaded = True\n self.env['script_name'] = self.script_name\n self.env['script_uploaded'] = script_uploaded\n if script_uploaded:\n self.env['jamfscriptuploader_summary_result'] = {'summary_text':\n 'The following scripts were created or updated in Jamf Pro:',\n 'report_fields': ['script', 'path', 'category', 'priority',\n 'os_req', 'info', 'notes', 'P4', 'P5', 'P6', 'P7', 'P8',\n 'P9', 'P10', 'P11'], 'data': {'script': self.script_name,\n 'path': self.script_path, 'category': self.script_category,\n 'priority': str(self.script_priority), 'info': self.\n script_info, 'os_req': self.osrequirements, 'notes': self.\n script_notes, 'P4': self.script_parameter4, 'P5': self.\n script_parameter5, 'P6': self.script_parameter6, 'P7': self\n .script_parameter7, 'P8': self.script_parameter8, 'P9':\n self.script_parameter9, 'P10': self.script_parameter10,\n 'P11': self.script_parameter11}}\n\n\nif __name__ == '__main__':\n PROCESSOR = JamfScriptUploader()\n PROCESSOR.execute_shell()\n", "step-4": "<mask token>\nimport os.path\nimport sys\nfrom time import sleep\nfrom autopkglib import ProcessorError\nsys.path.insert(0, os.path.dirname(__file__))\nfrom JamfUploaderLib.JamfUploaderBase import JamfUploaderBase\n__all__ = ['JamfScriptUploader']\n\n\nclass JamfScriptUploader(JamfUploaderBase):\n description = (\n 'A processor for AutoPkg that will upload a script to a Jamf Cloud or on-prem server.'\n )\n input_variables = {'JSS_URL': {'required': True, 'description':\n 'URL to a Jamf Pro server that the API user has write access to, optionally set as a key in the com.github.autopkg preference file.'\n }, 'API_USERNAME': {'required': True, 'description':\n 'Username of account with appropriate access to jss, optionally set as a key in the com.github.autopkg preference file.'\n }, 'API_PASSWORD': {'required': True, 'description':\n 'Password of api user, optionally set as a key in the com.github.autopkg preference file.'\n }, 'script_path': {'required': False, 'description':\n 'Full path to the script to be uploaded'}, 'script_name': {\n 'required': False, 'description': 'Name of the script in Jamf'},\n 'script_category': {'required': False, 'description':\n 'Script category', 'default': ''}, 'script_priority': {'required': \n False, 'description': 'Script priority (BEFORE or AFTER)',\n 'default': 'AFTER'}, 'osrequirements': {'required': False,\n 'description': 'Script OS requirements', 'default': ''},\n 'script_info': {'required': False, 'description':\n 'Script info field', 'default': ''}, 'script_notes': {'required': \n False, 'description': 'Script notes field', 'default': ''},\n 'script_parameter4': {'required': False, 'description':\n 'Script parameter 4 title', 'default': ''}, 'script_parameter5': {\n 'required': False, 'description': 'Script parameter 5 title',\n 'default': ''}, 'script_parameter6': {'required': False,\n 'description': 'Script parameter 6 title', 'default': ''},\n 'script_parameter7': {'required': False, 'description':\n 'Script parameter 7 title', 'default': ''}, 'script_parameter8': {\n 'required': False, 'description': 'Script parameter 8 title',\n 'default': ''}, 'script_parameter9': {'required': False,\n 'description': 'Script parameter 9 title', 'default': ''},\n 'script_parameter10': {'required': False, 'description':\n 'Script parameter 10 title', 'default': ''}, 'script_parameter11':\n {'required': False, 'description': 'Script parameter 11 title',\n 'default': ''}, 'replace_script': {'required': False, 'description':\n 'Overwrite an existing script if True.', 'default': False}, 'sleep':\n {'required': False, 'description':\n 'Pause after running this processor for specified seconds.',\n 'default': '0'}}\n output_variables = {'script_name': {'required': False, 'description':\n 'Name of the uploaded script'}, 'jamfscriptuploader_summary_result':\n {'description': 'Description of interesting results.'}}\n\n def upload_script(self, jamf_url, script_name, script_path, category_id,\n script_category, script_info, script_notes, script_priority,\n script_parameter4, script_parameter5, script_parameter6,\n script_parameter7, script_parameter8, script_parameter9,\n script_parameter10, script_parameter11, script_os_requirements,\n token, obj_id=0):\n \"\"\"Update script metadata.\"\"\"\n if os.path.exists(script_path):\n with open(script_path, 'r') as file:\n script_contents = file.read()\n else:\n raise ProcessorError('Script does not exist!')\n script_contents = self.substitute_assignable_keys(script_contents)\n if script_priority:\n script_priority = script_priority.upper()\n script_data = {'name': script_name, 'info': script_info, 'notes':\n script_notes, 'priority': script_priority, 'categoryId':\n category_id, 'categoryName': script_category, 'parameter4':\n script_parameter4, 'parameter5': script_parameter5,\n 'parameter6': script_parameter6, 'parameter7':\n script_parameter7, 'parameter8': script_parameter8,\n 'parameter9': script_parameter9, 'parameter10':\n script_parameter10, 'parameter11': script_parameter11,\n 'osRequirements': script_os_requirements, 'scriptContents':\n script_contents}\n self.output('Script data:', verbose_level=2)\n self.output(script_data, verbose_level=2)\n script_json = self.write_json_file(script_data)\n self.output('Uploading script..')\n object_type = 'script'\n if obj_id:\n url = '{}/{}/{}'.format(jamf_url, self.api_endpoints(\n object_type), obj_id)\n else:\n url = '{}/{}'.format(jamf_url, self.api_endpoints(object_type))\n count = 0\n while True:\n count += 1\n self.output('Script upload attempt {}'.format(count),\n verbose_level=2)\n request = 'PUT' if obj_id else 'POST'\n r = self.curl(request=request, url=url, token=token, data=\n script_json)\n if self.status_check(r, 'Script', script_name, request) == 'break':\n break\n if count > 5:\n self.output('Script upload did not succeed after 5 attempts')\n self.output('\\nHTTP POST Response Code: {}'.format(r.\n status_code))\n raise ProcessorError('ERROR: Script upload failed ')\n if int(self.sleep) > 30:\n sleep(int(self.sleep))\n else:\n sleep(30)\n return r\n\n def main(self):\n \"\"\"Do the main thing here\"\"\"\n self.jamf_url = self.env.get('JSS_URL')\n self.jamf_user = self.env.get('API_USERNAME')\n self.jamf_password = self.env.get('API_PASSWORD')\n self.script_path = self.env.get('script_path')\n self.script_name = self.env.get('script_name')\n self.script_category = self.env.get('script_category')\n self.script_priority = self.env.get('script_priority')\n self.osrequirements = self.env.get('osrequirements')\n self.script_info = self.env.get('script_info')\n self.script_notes = self.env.get('script_notes')\n self.script_parameter4 = self.env.get('script_parameter4')\n self.script_parameter5 = self.env.get('script_parameter5')\n self.script_parameter6 = self.env.get('script_parameter6')\n self.script_parameter7 = self.env.get('script_parameter7')\n self.script_parameter8 = self.env.get('script_parameter8')\n self.script_parameter9 = self.env.get('script_parameter9')\n self.script_parameter10 = self.env.get('script_parameter10')\n self.script_parameter11 = self.env.get('script_parameter11')\n self.replace = self.env.get('replace_script')\n self.sleep = self.env.get('sleep')\n if not self.replace or self.replace == 'False':\n self.replace = False\n if 'jamfscriptuploader_summary_result' in self.env:\n del self.env['jamfscriptuploader_summary_result']\n script_uploaded = False\n token = self.handle_uapi_auth(self.jamf_url, self.jamf_user, self.\n jamf_password)\n if self.script_category:\n self.output('Checking categories for {}'.format(self.\n script_category))\n obj_type = 'category'\n obj_name = self.script_category\n category_id = self.get_uapi_obj_id_from_name(self.jamf_url,\n obj_type, obj_name, token)\n if not category_id:\n self.output('WARNING: Category not found!')\n category_id = '-1'\n else:\n self.output('Category {} found: ID={}'.format(self.\n script_category, category_id))\n else:\n self.script_category = ''\n category_id = '-1'\n if not self.script_path.startswith('/'):\n found_template = self.get_path_to_file(self.script_path)\n if found_template:\n self.script_path = found_template\n else:\n raise ProcessorError(\n f'ERROR: Script file {self.script_path} not found')\n if not self.script_name:\n self.script_name = os.path.basename(self.script_path)\n self.output(\"Checking for existing '{}' on {}\".format(self.\n script_name, self.jamf_url))\n self.output('Full path: {}'.format(self.script_path), verbose_level=2)\n obj_type = 'script'\n obj_name = self.script_name\n obj_id = self.get_uapi_obj_id_from_name(self.jamf_url, obj_type,\n obj_name, token)\n if obj_id:\n self.output(\"Script '{}' already exists: ID {}\".format(self.\n script_name, obj_id))\n if self.replace:\n self.output(\n \"Replacing existing script as 'replace_script' is set to {}\"\n .format(self.replace), verbose_level=1)\n else:\n self.output(\n \"Not replacing existing script. Use replace_script='True' to enforce.\"\n , verbose_level=1)\n return\n self.upload_script(self.jamf_url, self.script_name, self.\n script_path, category_id, self.script_category, self.\n script_info, self.script_notes, self.script_priority, self.\n script_parameter4, self.script_parameter5, self.\n script_parameter6, self.script_parameter7, self.\n script_parameter8, self.script_parameter9, self.\n script_parameter10, self.script_parameter11, self.\n osrequirements, token, obj_id)\n script_uploaded = True\n self.env['script_name'] = self.script_name\n self.env['script_uploaded'] = script_uploaded\n if script_uploaded:\n self.env['jamfscriptuploader_summary_result'] = {'summary_text':\n 'The following scripts were created or updated in Jamf Pro:',\n 'report_fields': ['script', 'path', 'category', 'priority',\n 'os_req', 'info', 'notes', 'P4', 'P5', 'P6', 'P7', 'P8',\n 'P9', 'P10', 'P11'], 'data': {'script': self.script_name,\n 'path': self.script_path, 'category': self.script_category,\n 'priority': str(self.script_priority), 'info': self.\n script_info, 'os_req': self.osrequirements, 'notes': self.\n script_notes, 'P4': self.script_parameter4, 'P5': self.\n script_parameter5, 'P6': self.script_parameter6, 'P7': self\n .script_parameter7, 'P8': self.script_parameter8, 'P9':\n self.script_parameter9, 'P10': self.script_parameter10,\n 'P11': self.script_parameter11}}\n\n\nif __name__ == '__main__':\n PROCESSOR = JamfScriptUploader()\n PROCESSOR.execute_shell()\n", "step-5": "#!/usr/local/autopkg/python\n\n\"\"\"\nJamfScriptUploader processor for uploading items to Jamf Pro using AutoPkg\n by G Pugh\n\"\"\"\n\nimport os.path\nimport sys\n\nfrom time import sleep\nfrom autopkglib import ProcessorError # pylint: disable=import-error\n\n# to use a base module in AutoPkg we need to add this path to the sys.path.\n# this violates flake8 E402 (PEP8 imports) but is unavoidable, so the following\n# imports require noqa comments for E402\nsys.path.insert(0, os.path.dirname(__file__))\n\nfrom JamfUploaderLib.JamfUploaderBase import JamfUploaderBase # noqa: E402\n\n__all__ = [\"JamfScriptUploader\"]\n\n\nclass JamfScriptUploader(JamfUploaderBase):\n description = (\n \"A processor for AutoPkg that will upload a script to a Jamf Cloud or \"\n \"on-prem server.\"\n )\n input_variables = {\n \"JSS_URL\": {\n \"required\": True,\n \"description\": \"URL to a Jamf Pro server that the API user has write access \"\n \"to, optionally set as a key in the com.github.autopkg \"\n \"preference file.\",\n },\n \"API_USERNAME\": {\n \"required\": True,\n \"description\": \"Username of account with appropriate access to \"\n \"jss, optionally set as a key in the com.github.autopkg \"\n \"preference file.\",\n },\n \"API_PASSWORD\": {\n \"required\": True,\n \"description\": \"Password of api user, optionally set as a key in \"\n \"the com.github.autopkg preference file.\",\n },\n \"script_path\": {\n \"required\": False,\n \"description\": \"Full path to the script to be uploaded\",\n },\n \"script_name\": {\n \"required\": False,\n \"description\": \"Name of the script in Jamf\",\n },\n \"script_category\": {\n \"required\": False,\n \"description\": \"Script category\",\n \"default\": \"\",\n },\n \"script_priority\": {\n \"required\": False,\n \"description\": \"Script priority (BEFORE or AFTER)\",\n \"default\": \"AFTER\",\n },\n \"osrequirements\": {\n \"required\": False,\n \"description\": \"Script OS requirements\",\n \"default\": \"\",\n },\n \"script_info\": {\n \"required\": False,\n \"description\": \"Script info field\",\n \"default\": \"\",\n },\n \"script_notes\": {\n \"required\": False,\n \"description\": \"Script notes field\",\n \"default\": \"\",\n },\n \"script_parameter4\": {\n \"required\": False,\n \"description\": \"Script parameter 4 title\",\n \"default\": \"\",\n },\n \"script_parameter5\": {\n \"required\": False,\n \"description\": \"Script parameter 5 title\",\n \"default\": \"\",\n },\n \"script_parameter6\": {\n \"required\": False,\n \"description\": \"Script parameter 6 title\",\n \"default\": \"\",\n },\n \"script_parameter7\": {\n \"required\": False,\n \"description\": \"Script parameter 7 title\",\n \"default\": \"\",\n },\n \"script_parameter8\": {\n \"required\": False,\n \"description\": \"Script parameter 8 title\",\n \"default\": \"\",\n },\n \"script_parameter9\": {\n \"required\": False,\n \"description\": \"Script parameter 9 title\",\n \"default\": \"\",\n },\n \"script_parameter10\": {\n \"required\": False,\n \"description\": \"Script parameter 10 title\",\n \"default\": \"\",\n },\n \"script_parameter11\": {\n \"required\": False,\n \"description\": \"Script parameter 11 title\",\n \"default\": \"\",\n },\n \"replace_script\": {\n \"required\": False,\n \"description\": \"Overwrite an existing script if True.\",\n \"default\": False,\n },\n \"sleep\": {\n \"required\": False,\n \"description\": \"Pause after running this processor for specified seconds.\",\n \"default\": \"0\",\n },\n }\n\n output_variables = {\n \"script_name\": {\n \"required\": False,\n \"description\": \"Name of the uploaded script\",\n },\n \"jamfscriptuploader_summary_result\": {\n \"description\": \"Description of interesting results.\",\n },\n }\n\n def upload_script(\n self,\n jamf_url,\n script_name,\n script_path,\n category_id,\n script_category,\n script_info,\n script_notes,\n script_priority,\n script_parameter4,\n script_parameter5,\n script_parameter6,\n script_parameter7,\n script_parameter8,\n script_parameter9,\n script_parameter10,\n script_parameter11,\n script_os_requirements,\n token,\n obj_id=0,\n ):\n \"\"\"Update script metadata.\"\"\"\n\n # import script from file and replace any keys in the script\n if os.path.exists(script_path):\n with open(script_path, \"r\") as file:\n script_contents = file.read()\n else:\n raise ProcessorError(\"Script does not exist!\")\n\n # substitute user-assignable keys\n script_contents = self.substitute_assignable_keys(script_contents)\n\n # priority has to be in upper case. Let's make it nice for the user\n if script_priority:\n script_priority = script_priority.upper()\n\n # build the object\n script_data = {\n \"name\": script_name,\n \"info\": script_info,\n \"notes\": script_notes,\n \"priority\": script_priority,\n \"categoryId\": category_id,\n \"categoryName\": script_category,\n \"parameter4\": script_parameter4,\n \"parameter5\": script_parameter5,\n \"parameter6\": script_parameter6,\n \"parameter7\": script_parameter7,\n \"parameter8\": script_parameter8,\n \"parameter9\": script_parameter9,\n \"parameter10\": script_parameter10,\n \"parameter11\": script_parameter11,\n \"osRequirements\": script_os_requirements,\n \"scriptContents\": script_contents,\n }\n\n self.output(\n \"Script data:\",\n verbose_level=2,\n )\n self.output(\n script_data,\n verbose_level=2,\n )\n\n script_json = self.write_json_file(script_data)\n\n self.output(\"Uploading script..\")\n\n # if we find an object ID we put, if not, we post\n object_type = \"script\"\n if obj_id:\n url = \"{}/{}/{}\".format(jamf_url, self.api_endpoints(object_type), obj_id)\n else:\n url = \"{}/{}\".format(jamf_url, self.api_endpoints(object_type))\n\n count = 0\n while True:\n count += 1\n self.output(\n \"Script upload attempt {}\".format(count),\n verbose_level=2,\n )\n request = \"PUT\" if obj_id else \"POST\"\n r = self.curl(request=request, url=url, token=token, data=script_json)\n # check HTTP response\n if self.status_check(r, \"Script\", script_name, request) == \"break\":\n break\n if count > 5:\n self.output(\"Script upload did not succeed after 5 attempts\")\n self.output(\"\\nHTTP POST Response Code: {}\".format(r.status_code))\n raise ProcessorError(\"ERROR: Script upload failed \")\n if int(self.sleep) > 30:\n sleep(int(self.sleep))\n else:\n sleep(30)\n return r\n\n def main(self):\n \"\"\"Do the main thing here\"\"\"\n self.jamf_url = self.env.get(\"JSS_URL\")\n self.jamf_user = self.env.get(\"API_USERNAME\")\n self.jamf_password = self.env.get(\"API_PASSWORD\")\n self.script_path = self.env.get(\"script_path\")\n self.script_name = self.env.get(\"script_name\")\n self.script_category = self.env.get(\"script_category\")\n self.script_priority = self.env.get(\"script_priority\")\n self.osrequirements = self.env.get(\"osrequirements\")\n self.script_info = self.env.get(\"script_info\")\n self.script_notes = self.env.get(\"script_notes\")\n self.script_parameter4 = self.env.get(\"script_parameter4\")\n self.script_parameter5 = self.env.get(\"script_parameter5\")\n self.script_parameter6 = self.env.get(\"script_parameter6\")\n self.script_parameter7 = self.env.get(\"script_parameter7\")\n self.script_parameter8 = self.env.get(\"script_parameter8\")\n self.script_parameter9 = self.env.get(\"script_parameter9\")\n self.script_parameter10 = self.env.get(\"script_parameter10\")\n self.script_parameter11 = self.env.get(\"script_parameter11\")\n self.replace = self.env.get(\"replace_script\")\n self.sleep = self.env.get(\"sleep\")\n # handle setting replace in overrides\n if not self.replace or self.replace == \"False\":\n self.replace = False\n\n # clear any pre-existing summary result\n if \"jamfscriptuploader_summary_result\" in self.env:\n del self.env[\"jamfscriptuploader_summary_result\"]\n script_uploaded = False\n\n # obtain the relevant credentials\n token = self.handle_uapi_auth(self.jamf_url, self.jamf_user, self.jamf_password)\n\n # get the id for a category if supplied\n if self.script_category:\n self.output(\"Checking categories for {}\".format(self.script_category))\n\n # check for existing category - requires obj_name\n obj_type = \"category\"\n obj_name = self.script_category\n category_id = self.get_uapi_obj_id_from_name(\n self.jamf_url,\n obj_type,\n obj_name,\n token,\n )\n\n if not category_id:\n self.output(\"WARNING: Category not found!\")\n category_id = \"-1\"\n else:\n self.output(\n \"Category {} found: ID={}\".format(self.script_category, category_id)\n )\n else:\n self.script_category = \"\"\n category_id = \"-1\"\n\n # handle files with a relative path\n if not self.script_path.startswith(\"/\"):\n found_template = self.get_path_to_file(self.script_path)\n if found_template:\n self.script_path = found_template\n else:\n raise ProcessorError(f\"ERROR: Script file {self.script_path} not found\")\n\n # now start the process of uploading the object\n if not self.script_name:\n self.script_name = os.path.basename(self.script_path)\n\n # check for existing script\n self.output(\n \"Checking for existing '{}' on {}\".format(self.script_name, self.jamf_url)\n )\n self.output(\n \"Full path: {}\".format(self.script_path),\n verbose_level=2,\n )\n obj_type = \"script\"\n obj_name = self.script_name\n obj_id = self.get_uapi_obj_id_from_name(\n self.jamf_url,\n obj_type,\n obj_name,\n token,\n )\n\n if obj_id:\n self.output(\n \"Script '{}' already exists: ID {}\".format(self.script_name, obj_id)\n )\n if self.replace:\n self.output(\n \"Replacing existing script as 'replace_script' is set to {}\".format(\n self.replace\n ),\n verbose_level=1,\n )\n else:\n self.output(\n \"Not replacing existing script. Use replace_script='True' to enforce.\",\n verbose_level=1,\n )\n return\n\n # post the script\n self.upload_script(\n self.jamf_url,\n self.script_name,\n self.script_path,\n category_id,\n self.script_category,\n self.script_info,\n self.script_notes,\n self.script_priority,\n self.script_parameter4,\n self.script_parameter5,\n self.script_parameter6,\n self.script_parameter7,\n self.script_parameter8,\n self.script_parameter9,\n self.script_parameter10,\n self.script_parameter11,\n self.osrequirements,\n token,\n obj_id,\n )\n script_uploaded = True\n\n # output the summary\n self.env[\"script_name\"] = self.script_name\n self.env[\"script_uploaded\"] = script_uploaded\n if script_uploaded:\n self.env[\"jamfscriptuploader_summary_result\"] = {\n \"summary_text\": \"The following scripts were created or updated in Jamf Pro:\",\n \"report_fields\": [\n \"script\",\n \"path\",\n \"category\",\n \"priority\",\n \"os_req\",\n \"info\",\n \"notes\",\n \"P4\",\n \"P5\",\n \"P6\",\n \"P7\",\n \"P8\",\n \"P9\",\n \"P10\",\n \"P11\",\n ],\n \"data\": {\n \"script\": self.script_name,\n \"path\": self.script_path,\n \"category\": self.script_category,\n \"priority\": str(self.script_priority),\n \"info\": self.script_info,\n \"os_req\": self.osrequirements,\n \"notes\": self.script_notes,\n \"P4\": self.script_parameter4,\n \"P5\": self.script_parameter5,\n \"P6\": self.script_parameter6,\n \"P7\": self.script_parameter7,\n \"P8\": self.script_parameter8,\n \"P9\": self.script_parameter9,\n \"P10\": self.script_parameter10,\n \"P11\": self.script_parameter11,\n },\n }\n\n\nif __name__ == \"__main__\":\n PROCESSOR = JamfScriptUploader()\n PROCESSOR.execute_shell()\n", "step-ids": [ 1, 4, 5, 7, 8 ] }
[ 1, 4, 5, 7, 8 ]
<|reserved_special_token_0|> class MorningGreeting(MappedAsDataclass, Model): <|reserved_special_token_0|> id: Mapped[int] = mapped_column(init=False, primary_key=True) platform: Mapped[str] bot_id: Mapped[str] group_id: Mapped[str] = mapped_column(default='') guild_id: Mapped[str] = mapped_column(default='') channel_id: Mapped[str] = mapped_column(default='') <|reserved_special_token_1|> <|reserved_special_token_0|> class MorningGreeting(MappedAsDataclass, Model): __table_args__ = UniqueConstraint('platform', 'bot_id', 'group_id', 'guild_id', 'channel_id', name='unique_morning_greeting'), id: Mapped[int] = mapped_column(init=False, primary_key=True) platform: Mapped[str] bot_id: Mapped[str] group_id: Mapped[str] = mapped_column(default='') guild_id: Mapped[str] = mapped_column(default='') channel_id: Mapped[str] = mapped_column(default='') <|reserved_special_token_1|> <|reserved_special_token_0|> Model = get_plugin_data().Model class MorningGreeting(MappedAsDataclass, Model): __table_args__ = UniqueConstraint('platform', 'bot_id', 'group_id', 'guild_id', 'channel_id', name='unique_morning_greeting'), id: Mapped[int] = mapped_column(init=False, primary_key=True) platform: Mapped[str] bot_id: Mapped[str] group_id: Mapped[str] = mapped_column(default='') guild_id: Mapped[str] = mapped_column(default='') channel_id: Mapped[str] = mapped_column(default='') <|reserved_special_token_1|> from nonebot_plugin_datastore import get_plugin_data from sqlalchemy import UniqueConstraint from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column Model = get_plugin_data().Model class MorningGreeting(MappedAsDataclass, Model): __table_args__ = UniqueConstraint('platform', 'bot_id', 'group_id', 'guild_id', 'channel_id', name='unique_morning_greeting'), id: Mapped[int] = mapped_column(init=False, primary_key=True) platform: Mapped[str] bot_id: Mapped[str] group_id: Mapped[str] = mapped_column(default='') guild_id: Mapped[str] = mapped_column(default='') channel_id: Mapped[str] = mapped_column(default='') <|reserved_special_token_1|> from nonebot_plugin_datastore import get_plugin_data from sqlalchemy import UniqueConstraint from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column Model = get_plugin_data().Model class MorningGreeting(MappedAsDataclass, Model): __table_args__ = ( UniqueConstraint( "platform", "bot_id", "group_id", "guild_id", "channel_id", name="unique_morning_greeting", ), ) id: Mapped[int] = mapped_column(init=False, primary_key=True) platform: Mapped[str] bot_id: Mapped[str] group_id: Mapped[str] = mapped_column(default="") guild_id: Mapped[str] = mapped_column(default="") channel_id: Mapped[str] = mapped_column(default="")
flexible
{ "blob_id": "28e5667db4a620ec627cd94154a024b4c8dbc5f7", "index": 6171, "step-1": "<mask token>\n\n\nclass MorningGreeting(MappedAsDataclass, Model):\n <mask token>\n id: Mapped[int] = mapped_column(init=False, primary_key=True)\n platform: Mapped[str]\n bot_id: Mapped[str]\n group_id: Mapped[str] = mapped_column(default='')\n guild_id: Mapped[str] = mapped_column(default='')\n channel_id: Mapped[str] = mapped_column(default='')\n", "step-2": "<mask token>\n\n\nclass MorningGreeting(MappedAsDataclass, Model):\n __table_args__ = UniqueConstraint('platform', 'bot_id', 'group_id',\n 'guild_id', 'channel_id', name='unique_morning_greeting'),\n id: Mapped[int] = mapped_column(init=False, primary_key=True)\n platform: Mapped[str]\n bot_id: Mapped[str]\n group_id: Mapped[str] = mapped_column(default='')\n guild_id: Mapped[str] = mapped_column(default='')\n channel_id: Mapped[str] = mapped_column(default='')\n", "step-3": "<mask token>\nModel = get_plugin_data().Model\n\n\nclass MorningGreeting(MappedAsDataclass, Model):\n __table_args__ = UniqueConstraint('platform', 'bot_id', 'group_id',\n 'guild_id', 'channel_id', name='unique_morning_greeting'),\n id: Mapped[int] = mapped_column(init=False, primary_key=True)\n platform: Mapped[str]\n bot_id: Mapped[str]\n group_id: Mapped[str] = mapped_column(default='')\n guild_id: Mapped[str] = mapped_column(default='')\n channel_id: Mapped[str] = mapped_column(default='')\n", "step-4": "from nonebot_plugin_datastore import get_plugin_data\nfrom sqlalchemy import UniqueConstraint\nfrom sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column\nModel = get_plugin_data().Model\n\n\nclass MorningGreeting(MappedAsDataclass, Model):\n __table_args__ = UniqueConstraint('platform', 'bot_id', 'group_id',\n 'guild_id', 'channel_id', name='unique_morning_greeting'),\n id: Mapped[int] = mapped_column(init=False, primary_key=True)\n platform: Mapped[str]\n bot_id: Mapped[str]\n group_id: Mapped[str] = mapped_column(default='')\n guild_id: Mapped[str] = mapped_column(default='')\n channel_id: Mapped[str] = mapped_column(default='')\n", "step-5": "from nonebot_plugin_datastore import get_plugin_data\nfrom sqlalchemy import UniqueConstraint\nfrom sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column\n\nModel = get_plugin_data().Model\n\n\nclass MorningGreeting(MappedAsDataclass, Model):\n __table_args__ = (\n UniqueConstraint(\n \"platform\",\n \"bot_id\",\n \"group_id\",\n \"guild_id\",\n \"channel_id\",\n name=\"unique_morning_greeting\",\n ),\n )\n\n id: Mapped[int] = mapped_column(init=False, primary_key=True)\n platform: Mapped[str]\n bot_id: Mapped[str]\n group_id: Mapped[str] = mapped_column(default=\"\")\n guild_id: Mapped[str] = mapped_column(default=\"\")\n channel_id: Mapped[str] = mapped_column(default=\"\")\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
''' Created on Dec 2, 2013 A reference entity implementation for Power devices that can be controlled via RF communication. @author: rycus ''' from entities import Entity, EntityType from entities import STATE_UNKNOWN, STATE_OFF, STATE_ON from entities import COMMAND_ON, COMMAND_OFF class GenericPower(Entity): ''' This type of entites are able to report their states as logical on (0x01) or off (0x00) state, and accept commands to switch this state. ''' def __init__(self, unique_id, entity_type=EntityType.find(100), name='Unnamed entity', state=STATE_UNKNOWN, state_value=None, last_checkin=0): Entity.__init__(self, unique_id, entity_type, name=name, state=state, state_value=state_value, last_checkin=last_checkin) def state_changed(self, state_message): Entity.state_changed(self, state_message) state = state_message[0] if state == 0x00: if 0 != self.state_value: self.set_state(STATE_OFF, 0) return True elif state == 0x01: if 1 != self.state_value: self.set_state(STATE_ON, 1) return True return False def control(self, controller, command, value=None): if command.id == COMMAND_ON.id: controller.send_message(self.unique_id, [ chr(0x00), chr(0x01) ]) self.log_command('Turning the power on') return elif command.id == COMMAND_OFF.id: controller.send_message(self.unique_id, [ chr(0x00), chr(0x00) ]) self.log_command('Turning the power off') return Entity.control(self, command, value=value) def describe_state(self): return str(self.state) # register type EntityType.register(100, 'Power', GenericPower, [COMMAND_ON, COMMAND_OFF], '#99CC00', 'power.png')
normal
{ "blob_id": "18e76df1693d4fc27620a0cf491c33197caa5d15", "index": 4055, "step-1": "<mask token>\n\n\nclass GenericPower(Entity):\n <mask token>\n\n def __init__(self, unique_id, entity_type=EntityType.find(100), name=\n 'Unnamed entity', state=STATE_UNKNOWN, state_value=None, last_checkin=0\n ):\n Entity.__init__(self, unique_id, entity_type, name=name, state=\n state, state_value=state_value, last_checkin=last_checkin)\n\n def state_changed(self, state_message):\n Entity.state_changed(self, state_message)\n state = state_message[0]\n if state == 0:\n if 0 != self.state_value:\n self.set_state(STATE_OFF, 0)\n return True\n elif state == 1:\n if 1 != self.state_value:\n self.set_state(STATE_ON, 1)\n return True\n return False\n\n def control(self, controller, command, value=None):\n if command.id == COMMAND_ON.id:\n controller.send_message(self.unique_id, [chr(0), chr(1)])\n self.log_command('Turning the power on')\n return\n elif command.id == COMMAND_OFF.id:\n controller.send_message(self.unique_id, [chr(0), chr(0)])\n self.log_command('Turning the power off')\n return\n Entity.control(self, command, value=value)\n\n def describe_state(self):\n return str(self.state)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass GenericPower(Entity):\n \"\"\" This type of entites are able to report their states as logical\n on (0x01) or off (0x00) state, and accept commands to switch this state. \"\"\"\n\n def __init__(self, unique_id, entity_type=EntityType.find(100), name=\n 'Unnamed entity', state=STATE_UNKNOWN, state_value=None, last_checkin=0\n ):\n Entity.__init__(self, unique_id, entity_type, name=name, state=\n state, state_value=state_value, last_checkin=last_checkin)\n\n def state_changed(self, state_message):\n Entity.state_changed(self, state_message)\n state = state_message[0]\n if state == 0:\n if 0 != self.state_value:\n self.set_state(STATE_OFF, 0)\n return True\n elif state == 1:\n if 1 != self.state_value:\n self.set_state(STATE_ON, 1)\n return True\n return False\n\n def control(self, controller, command, value=None):\n if command.id == COMMAND_ON.id:\n controller.send_message(self.unique_id, [chr(0), chr(1)])\n self.log_command('Turning the power on')\n return\n elif command.id == COMMAND_OFF.id:\n controller.send_message(self.unique_id, [chr(0), chr(0)])\n self.log_command('Turning the power off')\n return\n Entity.control(self, command, value=value)\n\n def describe_state(self):\n return str(self.state)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass GenericPower(Entity):\n \"\"\" This type of entites are able to report their states as logical\n on (0x01) or off (0x00) state, and accept commands to switch this state. \"\"\"\n\n def __init__(self, unique_id, entity_type=EntityType.find(100), name=\n 'Unnamed entity', state=STATE_UNKNOWN, state_value=None, last_checkin=0\n ):\n Entity.__init__(self, unique_id, entity_type, name=name, state=\n state, state_value=state_value, last_checkin=last_checkin)\n\n def state_changed(self, state_message):\n Entity.state_changed(self, state_message)\n state = state_message[0]\n if state == 0:\n if 0 != self.state_value:\n self.set_state(STATE_OFF, 0)\n return True\n elif state == 1:\n if 1 != self.state_value:\n self.set_state(STATE_ON, 1)\n return True\n return False\n\n def control(self, controller, command, value=None):\n if command.id == COMMAND_ON.id:\n controller.send_message(self.unique_id, [chr(0), chr(1)])\n self.log_command('Turning the power on')\n return\n elif command.id == COMMAND_OFF.id:\n controller.send_message(self.unique_id, [chr(0), chr(0)])\n self.log_command('Turning the power off')\n return\n Entity.control(self, command, value=value)\n\n def describe_state(self):\n return str(self.state)\n\n\nEntityType.register(100, 'Power', GenericPower, [COMMAND_ON, COMMAND_OFF],\n '#99CC00', 'power.png')\n", "step-4": "<mask token>\nfrom entities import Entity, EntityType\nfrom entities import STATE_UNKNOWN, STATE_OFF, STATE_ON\nfrom entities import COMMAND_ON, COMMAND_OFF\n\n\nclass GenericPower(Entity):\n \"\"\" This type of entites are able to report their states as logical\n on (0x01) or off (0x00) state, and accept commands to switch this state. \"\"\"\n\n def __init__(self, unique_id, entity_type=EntityType.find(100), name=\n 'Unnamed entity', state=STATE_UNKNOWN, state_value=None, last_checkin=0\n ):\n Entity.__init__(self, unique_id, entity_type, name=name, state=\n state, state_value=state_value, last_checkin=last_checkin)\n\n def state_changed(self, state_message):\n Entity.state_changed(self, state_message)\n state = state_message[0]\n if state == 0:\n if 0 != self.state_value:\n self.set_state(STATE_OFF, 0)\n return True\n elif state == 1:\n if 1 != self.state_value:\n self.set_state(STATE_ON, 1)\n return True\n return False\n\n def control(self, controller, command, value=None):\n if command.id == COMMAND_ON.id:\n controller.send_message(self.unique_id, [chr(0), chr(1)])\n self.log_command('Turning the power on')\n return\n elif command.id == COMMAND_OFF.id:\n controller.send_message(self.unique_id, [chr(0), chr(0)])\n self.log_command('Turning the power off')\n return\n Entity.control(self, command, value=value)\n\n def describe_state(self):\n return str(self.state)\n\n\nEntityType.register(100, 'Power', GenericPower, [COMMAND_ON, COMMAND_OFF],\n '#99CC00', 'power.png')\n", "step-5": "'''\nCreated on Dec 2, 2013\n\nA reference entity implementation for Power devices\nthat can be controlled via RF communication.\n\n@author: rycus\n'''\n\nfrom entities import Entity, EntityType\nfrom entities import STATE_UNKNOWN, STATE_OFF, STATE_ON\nfrom entities import COMMAND_ON, COMMAND_OFF\n\nclass GenericPower(Entity):\n ''' This type of entites are able to report their states as logical\n on (0x01) or off (0x00) state, and accept commands to switch this state. '''\n \n def __init__(self, unique_id, entity_type=EntityType.find(100), name='Unnamed entity', state=STATE_UNKNOWN, state_value=None, last_checkin=0):\n Entity.__init__(self, unique_id, entity_type, name=name, state=state, state_value=state_value, last_checkin=last_checkin)\n\n def state_changed(self, state_message):\n Entity.state_changed(self, state_message)\n \n state = state_message[0]\n if state == 0x00:\n if 0 != self.state_value:\n self.set_state(STATE_OFF, 0)\n return True\n elif state == 0x01:\n if 1 != self.state_value:\n self.set_state(STATE_ON, 1)\n return True\n \n return False\n\n def control(self, controller, command, value=None):\n if command.id == COMMAND_ON.id:\n controller.send_message(self.unique_id, [ chr(0x00), chr(0x01) ])\n self.log_command('Turning the power on')\n return\n elif command.id == COMMAND_OFF.id:\n controller.send_message(self.unique_id, [ chr(0x00), chr(0x00) ])\n self.log_command('Turning the power off')\n return \n \n Entity.control(self, command, value=value)\n \n def describe_state(self):\n return str(self.state)\n\n# register type\nEntityType.register(100, 'Power', GenericPower, [COMMAND_ON, COMMAND_OFF], '#99CC00', 'power.png')\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> class Group(Actor): """Represents a formal or informal collective of Actors.""" pass class Organization(Actor): """Represents an organization.""" pass class Person(Actor): """Represents an individual person.""" pass class Service(Actor): """Represents a service of any kind.""" pass <|reserved_special_token_1|> <|reserved_special_token_0|> class Application(Actor): """Describes a software application.""" pass class Group(Actor): """Represents a formal or informal collective of Actors.""" pass class Organization(Actor): """Represents an organization.""" pass class Person(Actor): """Represents an individual person.""" pass class Service(Actor): """Represents a service of any kind.""" pass <|reserved_special_token_1|> <|reserved_special_token_0|> class Actor(Object): <|reserved_special_token_0|> pass class Application(Actor): """Describes a software application.""" pass class Group(Actor): """Represents a formal or informal collective of Actors.""" pass class Organization(Actor): """Represents an organization.""" pass class Person(Actor): """Represents an individual person.""" pass class Service(Actor): """Represents a service of any kind.""" pass <|reserved_special_token_1|> <|reserved_special_token_0|> class Actor(Object): """Describes a generic actor.""" pass class Application(Actor): """Describes a software application.""" pass class Group(Actor): """Represents a formal or informal collective of Actors.""" pass class Organization(Actor): """Represents an organization.""" pass class Person(Actor): """Represents an individual person.""" pass class Service(Actor): """Represents a service of any kind.""" pass <|reserved_special_token_1|> from activitystreams.core import Object class Actor(Object): """Describes a generic actor.""" pass class Application(Actor): """Describes a software application.""" pass class Group(Actor): """Represents a formal or informal collective of Actors.""" pass class Organization(Actor): """Represents an organization.""" pass class Person(Actor): """Represents an individual person.""" pass class Service(Actor): """Represents a service of any kind.""" pass
flexible
{ "blob_id": "b92f24cddae7b392af2417b39bb4f58e3f661cc6", "index": 2785, "step-1": "<mask token>\n\n\nclass Group(Actor):\n \"\"\"Represents a formal or informal collective of Actors.\"\"\"\n pass\n\n\nclass Organization(Actor):\n \"\"\"Represents an organization.\"\"\"\n pass\n\n\nclass Person(Actor):\n \"\"\"Represents an individual person.\"\"\"\n pass\n\n\nclass Service(Actor):\n \"\"\"Represents a service of any kind.\"\"\"\n pass\n", "step-2": "<mask token>\n\n\nclass Application(Actor):\n \"\"\"Describes a software application.\"\"\"\n pass\n\n\nclass Group(Actor):\n \"\"\"Represents a formal or informal collective of Actors.\"\"\"\n pass\n\n\nclass Organization(Actor):\n \"\"\"Represents an organization.\"\"\"\n pass\n\n\nclass Person(Actor):\n \"\"\"Represents an individual person.\"\"\"\n pass\n\n\nclass Service(Actor):\n \"\"\"Represents a service of any kind.\"\"\"\n pass\n", "step-3": "<mask token>\n\n\nclass Actor(Object):\n <mask token>\n pass\n\n\nclass Application(Actor):\n \"\"\"Describes a software application.\"\"\"\n pass\n\n\nclass Group(Actor):\n \"\"\"Represents a formal or informal collective of Actors.\"\"\"\n pass\n\n\nclass Organization(Actor):\n \"\"\"Represents an organization.\"\"\"\n pass\n\n\nclass Person(Actor):\n \"\"\"Represents an individual person.\"\"\"\n pass\n\n\nclass Service(Actor):\n \"\"\"Represents a service of any kind.\"\"\"\n pass\n", "step-4": "<mask token>\n\n\nclass Actor(Object):\n \"\"\"Describes a generic actor.\"\"\"\n pass\n\n\nclass Application(Actor):\n \"\"\"Describes a software application.\"\"\"\n pass\n\n\nclass Group(Actor):\n \"\"\"Represents a formal or informal collective of Actors.\"\"\"\n pass\n\n\nclass Organization(Actor):\n \"\"\"Represents an organization.\"\"\"\n pass\n\n\nclass Person(Actor):\n \"\"\"Represents an individual person.\"\"\"\n pass\n\n\nclass Service(Actor):\n \"\"\"Represents a service of any kind.\"\"\"\n pass\n", "step-5": "from activitystreams.core import Object\n\n\nclass Actor(Object):\n \"\"\"Describes a generic actor.\"\"\"\n pass\n\n\nclass Application(Actor):\n \"\"\"Describes a software application.\"\"\"\n pass\n\n\nclass Group(Actor):\n \"\"\"Represents a formal or informal collective of Actors.\"\"\"\n pass\n\n\nclass Organization(Actor):\n \"\"\"Represents an organization.\"\"\"\n pass\n\n\nclass Person(Actor):\n \"\"\"Represents an individual person.\"\"\"\n pass\n\n\nclass Service(Actor):\n \"\"\"Represents a service of any kind.\"\"\"\n pass\n", "step-ids": [ 8, 10, 11, 12, 13 ] }
[ 8, 10, 11, 12, 13 ]
''' Calculations used by algorithms All calculations for training shall have a standard API that takes in `batch` from algorithm.sample() method and return np array for calculation. `batch` is a dict containing keys to any data type you wish, e.g. {rewards: np.array([...])} ''' from slm_lab.lib import logger, util import numpy as np import torch import pydash as ps logger = logger.get_logger(__name__) # Policy Gradient calc # advantage functions def calc_returns(batch, gamma): ''' Calculate the simple returns (full rollout) for advantage i.e. sum discounted rewards up till termination ''' rewards = batch['rewards'] assert not np.any(np.isnan(rewards)) # handle epi-end, to not sum past current episode not_dones = 1 - batch['dones'] T = len(rewards) rets = np.empty(T, 'float32') future_ret = 0.0 for t in reversed(range(T)): future_ret = rewards[t] + gamma * future_ret * not_dones[t] rets[t] = future_ret rets = torch.from_numpy(rets).float() return rets def calc_gammas(batch, gamma): '''Calculate the gammas to the right power for multiplication with rewards''' news = torch.cat([torch.ones((1,)), batch['dones'][:-1]]) gammas = torch.empty_like(news) cur_gamma = 1.0 for t, new in enumerate(news): cur_gamma = new * 1.0 + (1 - new) * cur_gamma * gamma gammas[t] = cur_gamma return gammas def calc_nstep_returns(batch, gamma, n, v_preds): ''' Calculate the n-step returns for advantage see n-step return in: http://www-anw.cs.umass.edu/~barto/courses/cs687/Chapter%207.pdf i.e. for each timestep t: sum discounted rewards up till step n (0 to n-1 that is), then add v_pred for n as final term ''' rets = calc_returns(batch, gamma) rets_len = len(rets) # to subtract by offsetting n-steps tail_rets = torch.cat([rets[n:], torch.zeros((n,))])[:rets_len] # to add back the subtracted with v_pred at n gammas = calc_gammas(batch, gamma) final_terms = gammas * v_preds final_terms = torch.cat([final_terms[n:], torch.zeros((n,))])[:rets_len] nstep_rets = rets - tail_rets + final_terms assert not np.isnan(nstep_rets).any(), f'N-step returns has nan: {nstep_rets}' return nstep_rets def calc_gaes(rewards, v_preds, next_v_preds, gamma, lam): ''' Calculate GAE See http://www.breloff.com/DeepRL-OnlineGAE/ for clear example. v_preds are values predicted for current states next_v_preds are values predicted for next states NOTE for standardization trick, do it out of here ''' T = len(rewards) assert not np.any(np.isnan(rewards)) assert T == len(v_preds) gaes = np.empty(T, 'float32') future_gae = 0.0 for t in reversed(range(T)): delta = rewards[t] + gamma * next_v_preds[t] - v_preds[t] gaes[t] = future_gae = delta + gamma * lam * future_gae assert not np.isnan(gaes).any(), f'GAE has nan: {gaes}' gaes = torch.from_numpy(gaes).float() return gaes
normal
{ "blob_id": "07095bc815f5342b66ef4ca74b769321f3ef2ec5", "index": 7240, "step-1": "<mask token>\n\n\ndef calc_returns(batch, gamma):\n \"\"\"\n Calculate the simple returns (full rollout) for advantage\n i.e. sum discounted rewards up till termination\n \"\"\"\n rewards = batch['rewards']\n assert not np.any(np.isnan(rewards))\n not_dones = 1 - batch['dones']\n T = len(rewards)\n rets = np.empty(T, 'float32')\n future_ret = 0.0\n for t in reversed(range(T)):\n future_ret = rewards[t] + gamma * future_ret * not_dones[t]\n rets[t] = future_ret\n rets = torch.from_numpy(rets).float()\n return rets\n\n\n<mask token>\n\n\ndef calc_nstep_returns(batch, gamma, n, v_preds):\n \"\"\"\n Calculate the n-step returns for advantage\n see n-step return in: http://www-anw.cs.umass.edu/~barto/courses/cs687/Chapter%207.pdf\n i.e. for each timestep t:\n sum discounted rewards up till step n (0 to n-1 that is),\n then add v_pred for n as final term\n \"\"\"\n rets = calc_returns(batch, gamma)\n rets_len = len(rets)\n tail_rets = torch.cat([rets[n:], torch.zeros((n,))])[:rets_len]\n gammas = calc_gammas(batch, gamma)\n final_terms = gammas * v_preds\n final_terms = torch.cat([final_terms[n:], torch.zeros((n,))])[:rets_len]\n nstep_rets = rets - tail_rets + final_terms\n assert not np.isnan(nstep_rets).any(\n ), f'N-step returns has nan: {nstep_rets}'\n return nstep_rets\n\n\ndef calc_gaes(rewards, v_preds, next_v_preds, gamma, lam):\n \"\"\"\n Calculate GAE\n See http://www.breloff.com/DeepRL-OnlineGAE/ for clear example.\n v_preds are values predicted for current states\n next_v_preds are values predicted for next states\n NOTE for standardization trick, do it out of here\n \"\"\"\n T = len(rewards)\n assert not np.any(np.isnan(rewards))\n assert T == len(v_preds)\n gaes = np.empty(T, 'float32')\n future_gae = 0.0\n for t in reversed(range(T)):\n delta = rewards[t] + gamma * next_v_preds[t] - v_preds[t]\n gaes[t] = future_gae = delta + gamma * lam * future_gae\n assert not np.isnan(gaes).any(), f'GAE has nan: {gaes}'\n gaes = torch.from_numpy(gaes).float()\n return gaes\n", "step-2": "<mask token>\n\n\ndef calc_returns(batch, gamma):\n \"\"\"\n Calculate the simple returns (full rollout) for advantage\n i.e. sum discounted rewards up till termination\n \"\"\"\n rewards = batch['rewards']\n assert not np.any(np.isnan(rewards))\n not_dones = 1 - batch['dones']\n T = len(rewards)\n rets = np.empty(T, 'float32')\n future_ret = 0.0\n for t in reversed(range(T)):\n future_ret = rewards[t] + gamma * future_ret * not_dones[t]\n rets[t] = future_ret\n rets = torch.from_numpy(rets).float()\n return rets\n\n\ndef calc_gammas(batch, gamma):\n \"\"\"Calculate the gammas to the right power for multiplication with rewards\"\"\"\n news = torch.cat([torch.ones((1,)), batch['dones'][:-1]])\n gammas = torch.empty_like(news)\n cur_gamma = 1.0\n for t, new in enumerate(news):\n cur_gamma = new * 1.0 + (1 - new) * cur_gamma * gamma\n gammas[t] = cur_gamma\n return gammas\n\n\ndef calc_nstep_returns(batch, gamma, n, v_preds):\n \"\"\"\n Calculate the n-step returns for advantage\n see n-step return in: http://www-anw.cs.umass.edu/~barto/courses/cs687/Chapter%207.pdf\n i.e. for each timestep t:\n sum discounted rewards up till step n (0 to n-1 that is),\n then add v_pred for n as final term\n \"\"\"\n rets = calc_returns(batch, gamma)\n rets_len = len(rets)\n tail_rets = torch.cat([rets[n:], torch.zeros((n,))])[:rets_len]\n gammas = calc_gammas(batch, gamma)\n final_terms = gammas * v_preds\n final_terms = torch.cat([final_terms[n:], torch.zeros((n,))])[:rets_len]\n nstep_rets = rets - tail_rets + final_terms\n assert not np.isnan(nstep_rets).any(\n ), f'N-step returns has nan: {nstep_rets}'\n return nstep_rets\n\n\ndef calc_gaes(rewards, v_preds, next_v_preds, gamma, lam):\n \"\"\"\n Calculate GAE\n See http://www.breloff.com/DeepRL-OnlineGAE/ for clear example.\n v_preds are values predicted for current states\n next_v_preds are values predicted for next states\n NOTE for standardization trick, do it out of here\n \"\"\"\n T = len(rewards)\n assert not np.any(np.isnan(rewards))\n assert T == len(v_preds)\n gaes = np.empty(T, 'float32')\n future_gae = 0.0\n for t in reversed(range(T)):\n delta = rewards[t] + gamma * next_v_preds[t] - v_preds[t]\n gaes[t] = future_gae = delta + gamma * lam * future_gae\n assert not np.isnan(gaes).any(), f'GAE has nan: {gaes}'\n gaes = torch.from_numpy(gaes).float()\n return gaes\n", "step-3": "<mask token>\nlogger = logger.get_logger(__name__)\n\n\ndef calc_returns(batch, gamma):\n \"\"\"\n Calculate the simple returns (full rollout) for advantage\n i.e. sum discounted rewards up till termination\n \"\"\"\n rewards = batch['rewards']\n assert not np.any(np.isnan(rewards))\n not_dones = 1 - batch['dones']\n T = len(rewards)\n rets = np.empty(T, 'float32')\n future_ret = 0.0\n for t in reversed(range(T)):\n future_ret = rewards[t] + gamma * future_ret * not_dones[t]\n rets[t] = future_ret\n rets = torch.from_numpy(rets).float()\n return rets\n\n\ndef calc_gammas(batch, gamma):\n \"\"\"Calculate the gammas to the right power for multiplication with rewards\"\"\"\n news = torch.cat([torch.ones((1,)), batch['dones'][:-1]])\n gammas = torch.empty_like(news)\n cur_gamma = 1.0\n for t, new in enumerate(news):\n cur_gamma = new * 1.0 + (1 - new) * cur_gamma * gamma\n gammas[t] = cur_gamma\n return gammas\n\n\ndef calc_nstep_returns(batch, gamma, n, v_preds):\n \"\"\"\n Calculate the n-step returns for advantage\n see n-step return in: http://www-anw.cs.umass.edu/~barto/courses/cs687/Chapter%207.pdf\n i.e. for each timestep t:\n sum discounted rewards up till step n (0 to n-1 that is),\n then add v_pred for n as final term\n \"\"\"\n rets = calc_returns(batch, gamma)\n rets_len = len(rets)\n tail_rets = torch.cat([rets[n:], torch.zeros((n,))])[:rets_len]\n gammas = calc_gammas(batch, gamma)\n final_terms = gammas * v_preds\n final_terms = torch.cat([final_terms[n:], torch.zeros((n,))])[:rets_len]\n nstep_rets = rets - tail_rets + final_terms\n assert not np.isnan(nstep_rets).any(\n ), f'N-step returns has nan: {nstep_rets}'\n return nstep_rets\n\n\ndef calc_gaes(rewards, v_preds, next_v_preds, gamma, lam):\n \"\"\"\n Calculate GAE\n See http://www.breloff.com/DeepRL-OnlineGAE/ for clear example.\n v_preds are values predicted for current states\n next_v_preds are values predicted for next states\n NOTE for standardization trick, do it out of here\n \"\"\"\n T = len(rewards)\n assert not np.any(np.isnan(rewards))\n assert T == len(v_preds)\n gaes = np.empty(T, 'float32')\n future_gae = 0.0\n for t in reversed(range(T)):\n delta = rewards[t] + gamma * next_v_preds[t] - v_preds[t]\n gaes[t] = future_gae = delta + gamma * lam * future_gae\n assert not np.isnan(gaes).any(), f'GAE has nan: {gaes}'\n gaes = torch.from_numpy(gaes).float()\n return gaes\n", "step-4": "<mask token>\nfrom slm_lab.lib import logger, util\nimport numpy as np\nimport torch\nimport pydash as ps\nlogger = logger.get_logger(__name__)\n\n\ndef calc_returns(batch, gamma):\n \"\"\"\n Calculate the simple returns (full rollout) for advantage\n i.e. sum discounted rewards up till termination\n \"\"\"\n rewards = batch['rewards']\n assert not np.any(np.isnan(rewards))\n not_dones = 1 - batch['dones']\n T = len(rewards)\n rets = np.empty(T, 'float32')\n future_ret = 0.0\n for t in reversed(range(T)):\n future_ret = rewards[t] + gamma * future_ret * not_dones[t]\n rets[t] = future_ret\n rets = torch.from_numpy(rets).float()\n return rets\n\n\ndef calc_gammas(batch, gamma):\n \"\"\"Calculate the gammas to the right power for multiplication with rewards\"\"\"\n news = torch.cat([torch.ones((1,)), batch['dones'][:-1]])\n gammas = torch.empty_like(news)\n cur_gamma = 1.0\n for t, new in enumerate(news):\n cur_gamma = new * 1.0 + (1 - new) * cur_gamma * gamma\n gammas[t] = cur_gamma\n return gammas\n\n\ndef calc_nstep_returns(batch, gamma, n, v_preds):\n \"\"\"\n Calculate the n-step returns for advantage\n see n-step return in: http://www-anw.cs.umass.edu/~barto/courses/cs687/Chapter%207.pdf\n i.e. for each timestep t:\n sum discounted rewards up till step n (0 to n-1 that is),\n then add v_pred for n as final term\n \"\"\"\n rets = calc_returns(batch, gamma)\n rets_len = len(rets)\n tail_rets = torch.cat([rets[n:], torch.zeros((n,))])[:rets_len]\n gammas = calc_gammas(batch, gamma)\n final_terms = gammas * v_preds\n final_terms = torch.cat([final_terms[n:], torch.zeros((n,))])[:rets_len]\n nstep_rets = rets - tail_rets + final_terms\n assert not np.isnan(nstep_rets).any(\n ), f'N-step returns has nan: {nstep_rets}'\n return nstep_rets\n\n\ndef calc_gaes(rewards, v_preds, next_v_preds, gamma, lam):\n \"\"\"\n Calculate GAE\n See http://www.breloff.com/DeepRL-OnlineGAE/ for clear example.\n v_preds are values predicted for current states\n next_v_preds are values predicted for next states\n NOTE for standardization trick, do it out of here\n \"\"\"\n T = len(rewards)\n assert not np.any(np.isnan(rewards))\n assert T == len(v_preds)\n gaes = np.empty(T, 'float32')\n future_gae = 0.0\n for t in reversed(range(T)):\n delta = rewards[t] + gamma * next_v_preds[t] - v_preds[t]\n gaes[t] = future_gae = delta + gamma * lam * future_gae\n assert not np.isnan(gaes).any(), f'GAE has nan: {gaes}'\n gaes = torch.from_numpy(gaes).float()\n return gaes\n", "step-5": "'''\nCalculations used by algorithms\nAll calculations for training shall have a standard API that takes in `batch` from algorithm.sample() method and return np array for calculation.\n`batch` is a dict containing keys to any data type you wish, e.g. {rewards: np.array([...])}\n'''\nfrom slm_lab.lib import logger, util\nimport numpy as np\nimport torch\nimport pydash as ps\n\nlogger = logger.get_logger(__name__)\n\n# Policy Gradient calc\n# advantage functions\n\n\ndef calc_returns(batch, gamma):\n '''\n Calculate the simple returns (full rollout) for advantage\n i.e. sum discounted rewards up till termination\n '''\n rewards = batch['rewards']\n assert not np.any(np.isnan(rewards))\n # handle epi-end, to not sum past current episode\n not_dones = 1 - batch['dones']\n T = len(rewards)\n rets = np.empty(T, 'float32')\n future_ret = 0.0\n for t in reversed(range(T)):\n future_ret = rewards[t] + gamma * future_ret * not_dones[t]\n rets[t] = future_ret\n rets = torch.from_numpy(rets).float()\n return rets\n\n\ndef calc_gammas(batch, gamma):\n '''Calculate the gammas to the right power for multiplication with rewards'''\n news = torch.cat([torch.ones((1,)), batch['dones'][:-1]])\n gammas = torch.empty_like(news)\n cur_gamma = 1.0\n for t, new in enumerate(news):\n cur_gamma = new * 1.0 + (1 - new) * cur_gamma * gamma\n gammas[t] = cur_gamma\n return gammas\n\n\ndef calc_nstep_returns(batch, gamma, n, v_preds):\n '''\n Calculate the n-step returns for advantage\n see n-step return in: http://www-anw.cs.umass.edu/~barto/courses/cs687/Chapter%207.pdf\n i.e. for each timestep t:\n sum discounted rewards up till step n (0 to n-1 that is),\n then add v_pred for n as final term\n '''\n rets = calc_returns(batch, gamma)\n rets_len = len(rets)\n # to subtract by offsetting n-steps\n tail_rets = torch.cat([rets[n:], torch.zeros((n,))])[:rets_len]\n\n # to add back the subtracted with v_pred at n\n gammas = calc_gammas(batch, gamma)\n final_terms = gammas * v_preds\n final_terms = torch.cat([final_terms[n:], torch.zeros((n,))])[:rets_len]\n\n nstep_rets = rets - tail_rets + final_terms\n assert not np.isnan(nstep_rets).any(), f'N-step returns has nan: {nstep_rets}'\n return nstep_rets\n\n\ndef calc_gaes(rewards, v_preds, next_v_preds, gamma, lam):\n '''\n Calculate GAE\n See http://www.breloff.com/DeepRL-OnlineGAE/ for clear example.\n v_preds are values predicted for current states\n next_v_preds are values predicted for next states\n NOTE for standardization trick, do it out of here\n '''\n T = len(rewards)\n assert not np.any(np.isnan(rewards))\n assert T == len(v_preds)\n gaes = np.empty(T, 'float32')\n future_gae = 0.0\n for t in reversed(range(T)):\n delta = rewards[t] + gamma * next_v_preds[t] - v_preds[t]\n gaes[t] = future_gae = delta + gamma * lam * future_gae\n assert not np.isnan(gaes).any(), f'GAE has nan: {gaes}'\n gaes = torch.from_numpy(gaes).float()\n return gaes\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> class Player: <|reserved_special_token_0|> def hit(self): self.cards += random.randint(1, 11) def deal(self): self.cards = random.randint(1, 11) + random.randint(1, 11) self.dealer = random.randint(1, 11) <|reserved_special_token_0|> def reset(self): self.dealer = 0 self.cards = 0 <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Player: <|reserved_special_token_0|> def hit(self): self.cards += random.randint(1, 11) def deal(self): self.cards = random.randint(1, 11) + random.randint(1, 11) self.dealer = random.randint(1, 11) def stick(self): pass def reset(self): self.dealer = 0 self.cards = 0 <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Player: def __init__(self) ->None: q = None policy = None returns = None cards = 0 dealer = 0 def hit(self): self.cards += random.randint(1, 11) def deal(self): self.cards = random.randint(1, 11) + random.randint(1, 11) self.dealer = random.randint(1, 11) def stick(self): pass def reset(self): self.dealer = 0 self.cards = 0 def episode(self): self.reset() self.deal() if __name__ == '__main__': pass <|reserved_special_token_1|> import random class Player: def __init__(self) ->None: q = None policy = None returns = None cards = 0 dealer = 0 def hit(self): self.cards += random.randint(1, 11) def deal(self): self.cards = random.randint(1, 11) + random.randint(1, 11) self.dealer = random.randint(1, 11) def stick(self): pass def reset(self): self.dealer = 0 self.cards = 0 def episode(self): self.reset() self.deal() if __name__ == '__main__': pass <|reserved_special_token_1|> #finding optimal betting strategy for the blackjack game using Monte Carlo ES method import random class Player(): def __init__(self) -> None: q = None policy = None returns = None cards = 0 dealer = 0 def hit(self): self.cards += random.randint(1,11) def deal(self): self.cards = random.randint(1,11) + random.randint(1,11) self.dealer = random.randint(1,11) def stick(self): pass def reset(self): self.dealer = 0 self.cards = 0 def episode(self): self.reset() self.deal() #take action based on policy #Initialize, for all s ∈ S, a ∈ A(s): #Q(s, a) ← arbitrary #π(s) ← arbitrary #Returns(s, a) ← empty list #Repeat forever: #Choose S0 ∈ S and A0 ∈ A(S0) s.t. all pairs have probability > 0 #Generate an episode starting from S0, A0, following π #For each pair s, a appearing in the episode: #G ← return following the first occurrence of s, a #Append G to Returns(s, a) #Q(s, a) ← average(Returns(s, a)) #For each s in the episode: #π(s) ← argmaxa Q(s, a) if __name__=="__main__": pass
flexible
{ "blob_id": "db159cfb198311b0369f65eb9e10947c4d28c695", "index": 2919, "step-1": "<mask token>\n\n\nclass Player:\n <mask token>\n\n def hit(self):\n self.cards += random.randint(1, 11)\n\n def deal(self):\n self.cards = random.randint(1, 11) + random.randint(1, 11)\n self.dealer = random.randint(1, 11)\n <mask token>\n\n def reset(self):\n self.dealer = 0\n self.cards = 0\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Player:\n <mask token>\n\n def hit(self):\n self.cards += random.randint(1, 11)\n\n def deal(self):\n self.cards = random.randint(1, 11) + random.randint(1, 11)\n self.dealer = random.randint(1, 11)\n\n def stick(self):\n pass\n\n def reset(self):\n self.dealer = 0\n self.cards = 0\n <mask token>\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Player:\n\n def __init__(self) ->None:\n q = None\n policy = None\n returns = None\n cards = 0\n dealer = 0\n\n def hit(self):\n self.cards += random.randint(1, 11)\n\n def deal(self):\n self.cards = random.randint(1, 11) + random.randint(1, 11)\n self.dealer = random.randint(1, 11)\n\n def stick(self):\n pass\n\n def reset(self):\n self.dealer = 0\n self.cards = 0\n\n def episode(self):\n self.reset()\n self.deal()\n\n\nif __name__ == '__main__':\n pass\n", "step-4": "import random\n\n\nclass Player:\n\n def __init__(self) ->None:\n q = None\n policy = None\n returns = None\n cards = 0\n dealer = 0\n\n def hit(self):\n self.cards += random.randint(1, 11)\n\n def deal(self):\n self.cards = random.randint(1, 11) + random.randint(1, 11)\n self.dealer = random.randint(1, 11)\n\n def stick(self):\n pass\n\n def reset(self):\n self.dealer = 0\n self.cards = 0\n\n def episode(self):\n self.reset()\n self.deal()\n\n\nif __name__ == '__main__':\n pass\n", "step-5": "#finding optimal betting strategy for the blackjack game using Monte Carlo ES method\nimport random\n\nclass Player():\n def __init__(self) -> None:\n q = None\n policy = None\n returns = None\n cards = 0\n dealer = 0\n\n def hit(self):\n self.cards += random.randint(1,11)\n\n def deal(self):\n self.cards = random.randint(1,11) + random.randint(1,11)\n self.dealer = random.randint(1,11)\n\n def stick(self):\n pass\n\n def reset(self):\n self.dealer = 0\n self.cards = 0\n\n def episode(self):\n self.reset()\n self.deal()\n #take action based on policy\n\n#Initialize, for all s ∈ S, a ∈ A(s):\n#Q(s, a) ← arbitrary\n#π(s) ← arbitrary\n#Returns(s, a) ← empty list\n#Repeat forever:\n#Choose S0 ∈ S and A0 ∈ A(S0) s.t. all pairs have probability > 0\n#Generate an episode starting from S0, A0, following π\n#For each pair s, a appearing in the episode:\n#G ← return following the first occurrence of s, a\n#Append G to Returns(s, a)\n#Q(s, a) ← average(Returns(s, a))\n#For each s in the episode:\n#π(s) ← argmaxa Q(s, a)\n\n\nif __name__==\"__main__\":\n pass\n ", "step-ids": [ 4, 5, 8, 9, 10 ] }
[ 4, 5, 8, 9, 10 ]
<|reserved_special_token_0|> class Ball(Turtle): def __init__(self, x, y, dx, dy, r): Turtle.__init__(self) self.pu() self.goto(x, y) self.dx = dx self.dy = dy self.r = r self.shape('circle') self.shapesize(r / 10) r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) self.color(r, g, b) def move(self, screen_width, screen_hight): current_x = self.xcor() new_x = current_x + self.dx current_y = self.ycor() new_y = current_y + self.dy right_side_ball = new_x + self.r left_side_ball = new_x - self.r bottom_ball = new_y - self.r upper_ball_side = new_y + self.r self.goto(new_x, new_y) if (bottom_ball < -screen_hight / 2 or upper_ball_side > screen_hight / 2): self.dy *= -1 if (left_side_ball < -screen_width / 2 or right_side_ball > screen_width / 2): self.dx *= -1 <|reserved_special_token_0|> def move_all_balls(BALLS): for index in range(len(BALLS)): BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> colormode(255) class Ball(Turtle): def __init__(self, x, y, dx, dy, r): Turtle.__init__(self) self.pu() self.goto(x, y) self.dx = dx self.dy = dy self.r = r self.shape('circle') self.shapesize(r / 10) r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) self.color(r, g, b) def move(self, screen_width, screen_hight): current_x = self.xcor() new_x = current_x + self.dx current_y = self.ycor() new_y = current_y + self.dy right_side_ball = new_x + self.r left_side_ball = new_x - self.r bottom_ball = new_y - self.r upper_ball_side = new_y + self.r self.goto(new_x, new_y) if (bottom_ball < -screen_hight / 2 or upper_ball_side > screen_hight / 2): self.dy *= -1 if (left_side_ball < -screen_width / 2 or right_side_ball > screen_width / 2): self.dx *= -1 tracer(0) ht() <|reserved_special_token_0|> for i in range(NUMBER_OF_BALLS): x = random.randint(int(-SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS), int( SCREEN_WIDTH / 2 - MAXIMUM_BALL_RADIUS)) y = random.randint(-SCREEN_HEIGHT / 2 + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT / 2 - MAXIMUM_BALL_RADIUS) dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY) dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX) r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS) while dx == 0: dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX) while dy == 0: dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY) new_ball = Ball(x, y, dx, dy, r) BALLS.append(new_ball) def move_all_balls(BALLS): for index in range(len(BALLS)): BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT) mainloop() <|reserved_special_token_1|> <|reserved_special_token_0|> colormode(255) class Ball(Turtle): def __init__(self, x, y, dx, dy, r): Turtle.__init__(self) self.pu() self.goto(x, y) self.dx = dx self.dy = dy self.r = r self.shape('circle') self.shapesize(r / 10) r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) self.color(r, g, b) def move(self, screen_width, screen_hight): current_x = self.xcor() new_x = current_x + self.dx current_y = self.ycor() new_y = current_y + self.dy right_side_ball = new_x + self.r left_side_ball = new_x - self.r bottom_ball = new_y - self.r upper_ball_side = new_y + self.r self.goto(new_x, new_y) if (bottom_ball < -screen_hight / 2 or upper_ball_side > screen_hight / 2): self.dy *= -1 if (left_side_ball < -screen_width / 2 or right_side_ball > screen_width / 2): self.dx *= -1 tracer(0) ht() RUNNING = True SLEEP = 0.0077 SCREEN_WIDTH = getcanvas().winfo_width() / 2 SCREEN_HEIGHT = getcanvas().winfo_height() / 2 MY_BALL = 0, 0, 0.5, -0.4, 30 NUMBER_OF_BALLS = 5 MINIMUM_BALL_RADIUS = 10 MAXIMUM_BALL_RADIUS = 100 MINIMUM_BALL_DX = -5 MAXIMUM_BALL_DX = 5 MINIMUM_BALL_DY = -5 MAXIMUM_BALL_DY = 5 BALLS = [] for i in range(NUMBER_OF_BALLS): x = random.randint(int(-SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS), int( SCREEN_WIDTH / 2 - MAXIMUM_BALL_RADIUS)) y = random.randint(-SCREEN_HEIGHT / 2 + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT / 2 - MAXIMUM_BALL_RADIUS) dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY) dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX) r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS) while dx == 0: dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX) while dy == 0: dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY) new_ball = Ball(x, y, dx, dy, r) BALLS.append(new_ball) def move_all_balls(BALLS): for index in range(len(BALLS)): BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT) mainloop() <|reserved_special_token_1|> from turtle import * import time import random colormode(255) class Ball(Turtle): def __init__(self, x, y, dx, dy, r): Turtle.__init__(self) self.pu() self.goto(x, y) self.dx = dx self.dy = dy self.r = r self.shape('circle') self.shapesize(r / 10) r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) self.color(r, g, b) def move(self, screen_width, screen_hight): current_x = self.xcor() new_x = current_x + self.dx current_y = self.ycor() new_y = current_y + self.dy right_side_ball = new_x + self.r left_side_ball = new_x - self.r bottom_ball = new_y - self.r upper_ball_side = new_y + self.r self.goto(new_x, new_y) if (bottom_ball < -screen_hight / 2 or upper_ball_side > screen_hight / 2): self.dy *= -1 if (left_side_ball < -screen_width / 2 or right_side_ball > screen_width / 2): self.dx *= -1 tracer(0) ht() RUNNING = True SLEEP = 0.0077 SCREEN_WIDTH = getcanvas().winfo_width() / 2 SCREEN_HEIGHT = getcanvas().winfo_height() / 2 MY_BALL = 0, 0, 0.5, -0.4, 30 NUMBER_OF_BALLS = 5 MINIMUM_BALL_RADIUS = 10 MAXIMUM_BALL_RADIUS = 100 MINIMUM_BALL_DX = -5 MAXIMUM_BALL_DX = 5 MINIMUM_BALL_DY = -5 MAXIMUM_BALL_DY = 5 BALLS = [] for i in range(NUMBER_OF_BALLS): x = random.randint(int(-SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS), int( SCREEN_WIDTH / 2 - MAXIMUM_BALL_RADIUS)) y = random.randint(-SCREEN_HEIGHT / 2 + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT / 2 - MAXIMUM_BALL_RADIUS) dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY) dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX) r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS) while dx == 0: dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX) while dy == 0: dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY) new_ball = Ball(x, y, dx, dy, r) BALLS.append(new_ball) def move_all_balls(BALLS): for index in range(len(BALLS)): BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT) mainloop() <|reserved_special_token_1|> from turtle import * import time import random colormode(255) class Ball(Turtle): def __init__(self, x,y,dx,dy,r): Turtle.__init__(self) self.pu() self.goto(x,y) self.dx = dx self.dy = dy self.r = r self.shape("circle") self.shapesize(r/10) r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) self.color(r,g,b) def move(self,screen_width, screen_hight): current_x = self.xcor() new_x = current_x + self.dx current_y = self.ycor() new_y = current_y + self.dy right_side_ball = new_x + self.r left_side_ball = new_x - self.r bottom_ball = new_y - self.r upper_ball_side = new_y + self.r self.goto(new_x, new_y) if bottom_ball < -screen_hight/2 or upper_ball_side > screen_hight/2: self.dy *= -1 if left_side_ball < -screen_width/2 or right_side_ball > screen_width/2: self.dx *= -1 tracer(0) ht() RUNNING = True SLEEP = 0.0077 SCREEN_WIDTH = getcanvas().winfo_width()/2 SCREEN_HEIGHT = getcanvas().winfo_height()/2 MY_BALL = (0,0,0.5,-0.4,30) NUMBER_OF_BALLS = 5 MINIMUM_BALL_RADIUS = 10 MAXIMUM_BALL_RADIUS = 100 MINIMUM_BALL_DX = -5 MAXIMUM_BALL_DX = 5 MINIMUM_BALL_DY = -5 MAXIMUM_BALL_DY = 5 BALLS = [] for i in range(NUMBER_OF_BALLS): x = random.randint(int(- SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS) , int(SCREEN_WIDTH/2 - MAXIMUM_BALL_RADIUS)) y = random.randint(-SCREEN_HEIGHT/2 + MAXIMUM_BALL_RADIUS , SCREEN_HEIGHT/2 - MAXIMUM_BALL_RADIUS) dy = random.randint(MINIMUM_BALL_DY , MAXIMUM_BALL_DY) dx = random.randint(MINIMUM_BALL_DX , MAXIMUM_BALL_DX) r = random.randint(MINIMUM_BALL_RADIUS , MAXIMUM_BALL_RADIUS) while dx == 0: dx = random.randint(MINIMUM_BALL_DX , MAXIMUM_BALL_DX) while dy == 0: dy = random.randint(MINIMUM_BALL_DY , MAXIMUM_BALL_DY) new_ball = Ball(x,y,dx,dy,r) BALLS.append(new_ball) def move_all_balls(BALLS): for index in range(len(BALLS)): BALLS[index].move(SCREEN_WIDTH , SCREEN_HEIGHT) #move_all_balls(BALLS) mainloop()
flexible
{ "blob_id": "17cd6746e58a7f33bc239c1420d51c6810ed02d8", "index": 3575, "step-1": "<mask token>\n\n\nclass Ball(Turtle):\n\n def __init__(self, x, y, dx, dy, r):\n Turtle.__init__(self)\n self.pu()\n self.goto(x, y)\n self.dx = dx\n self.dy = dy\n self.r = r\n self.shape('circle')\n self.shapesize(r / 10)\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n self.color(r, g, b)\n\n def move(self, screen_width, screen_hight):\n current_x = self.xcor()\n new_x = current_x + self.dx\n current_y = self.ycor()\n new_y = current_y + self.dy\n right_side_ball = new_x + self.r\n left_side_ball = new_x - self.r\n bottom_ball = new_y - self.r\n upper_ball_side = new_y + self.r\n self.goto(new_x, new_y)\n if (bottom_ball < -screen_hight / 2 or upper_ball_side > \n screen_hight / 2):\n self.dy *= -1\n if (left_side_ball < -screen_width / 2 or right_side_ball > \n screen_width / 2):\n self.dx *= -1\n\n\n<mask token>\n\n\ndef move_all_balls(BALLS):\n for index in range(len(BALLS)):\n BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT)\n\n\n<mask token>\n", "step-2": "<mask token>\ncolormode(255)\n\n\nclass Ball(Turtle):\n\n def __init__(self, x, y, dx, dy, r):\n Turtle.__init__(self)\n self.pu()\n self.goto(x, y)\n self.dx = dx\n self.dy = dy\n self.r = r\n self.shape('circle')\n self.shapesize(r / 10)\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n self.color(r, g, b)\n\n def move(self, screen_width, screen_hight):\n current_x = self.xcor()\n new_x = current_x + self.dx\n current_y = self.ycor()\n new_y = current_y + self.dy\n right_side_ball = new_x + self.r\n left_side_ball = new_x - self.r\n bottom_ball = new_y - self.r\n upper_ball_side = new_y + self.r\n self.goto(new_x, new_y)\n if (bottom_ball < -screen_hight / 2 or upper_ball_side > \n screen_hight / 2):\n self.dy *= -1\n if (left_side_ball < -screen_width / 2 or right_side_ball > \n screen_width / 2):\n self.dx *= -1\n\n\ntracer(0)\nht()\n<mask token>\nfor i in range(NUMBER_OF_BALLS):\n x = random.randint(int(-SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS), int(\n SCREEN_WIDTH / 2 - MAXIMUM_BALL_RADIUS))\n y = random.randint(-SCREEN_HEIGHT / 2 + MAXIMUM_BALL_RADIUS, \n SCREEN_HEIGHT / 2 - MAXIMUM_BALL_RADIUS)\n dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)\n dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)\n r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)\n while dx == 0:\n dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)\n while dy == 0:\n dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)\n new_ball = Ball(x, y, dx, dy, r)\n BALLS.append(new_ball)\n\n\ndef move_all_balls(BALLS):\n for index in range(len(BALLS)):\n BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT)\n\n\nmainloop()\n", "step-3": "<mask token>\ncolormode(255)\n\n\nclass Ball(Turtle):\n\n def __init__(self, x, y, dx, dy, r):\n Turtle.__init__(self)\n self.pu()\n self.goto(x, y)\n self.dx = dx\n self.dy = dy\n self.r = r\n self.shape('circle')\n self.shapesize(r / 10)\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n self.color(r, g, b)\n\n def move(self, screen_width, screen_hight):\n current_x = self.xcor()\n new_x = current_x + self.dx\n current_y = self.ycor()\n new_y = current_y + self.dy\n right_side_ball = new_x + self.r\n left_side_ball = new_x - self.r\n bottom_ball = new_y - self.r\n upper_ball_side = new_y + self.r\n self.goto(new_x, new_y)\n if (bottom_ball < -screen_hight / 2 or upper_ball_side > \n screen_hight / 2):\n self.dy *= -1\n if (left_side_ball < -screen_width / 2 or right_side_ball > \n screen_width / 2):\n self.dx *= -1\n\n\ntracer(0)\nht()\nRUNNING = True\nSLEEP = 0.0077\nSCREEN_WIDTH = getcanvas().winfo_width() / 2\nSCREEN_HEIGHT = getcanvas().winfo_height() / 2\nMY_BALL = 0, 0, 0.5, -0.4, 30\nNUMBER_OF_BALLS = 5\nMINIMUM_BALL_RADIUS = 10\nMAXIMUM_BALL_RADIUS = 100\nMINIMUM_BALL_DX = -5\nMAXIMUM_BALL_DX = 5\nMINIMUM_BALL_DY = -5\nMAXIMUM_BALL_DY = 5\nBALLS = []\nfor i in range(NUMBER_OF_BALLS):\n x = random.randint(int(-SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS), int(\n SCREEN_WIDTH / 2 - MAXIMUM_BALL_RADIUS))\n y = random.randint(-SCREEN_HEIGHT / 2 + MAXIMUM_BALL_RADIUS, \n SCREEN_HEIGHT / 2 - MAXIMUM_BALL_RADIUS)\n dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)\n dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)\n r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)\n while dx == 0:\n dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)\n while dy == 0:\n dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)\n new_ball = Ball(x, y, dx, dy, r)\n BALLS.append(new_ball)\n\n\ndef move_all_balls(BALLS):\n for index in range(len(BALLS)):\n BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT)\n\n\nmainloop()\n", "step-4": "from turtle import *\nimport time\nimport random\ncolormode(255)\n\n\nclass Ball(Turtle):\n\n def __init__(self, x, y, dx, dy, r):\n Turtle.__init__(self)\n self.pu()\n self.goto(x, y)\n self.dx = dx\n self.dy = dy\n self.r = r\n self.shape('circle')\n self.shapesize(r / 10)\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n self.color(r, g, b)\n\n def move(self, screen_width, screen_hight):\n current_x = self.xcor()\n new_x = current_x + self.dx\n current_y = self.ycor()\n new_y = current_y + self.dy\n right_side_ball = new_x + self.r\n left_side_ball = new_x - self.r\n bottom_ball = new_y - self.r\n upper_ball_side = new_y + self.r\n self.goto(new_x, new_y)\n if (bottom_ball < -screen_hight / 2 or upper_ball_side > \n screen_hight / 2):\n self.dy *= -1\n if (left_side_ball < -screen_width / 2 or right_side_ball > \n screen_width / 2):\n self.dx *= -1\n\n\ntracer(0)\nht()\nRUNNING = True\nSLEEP = 0.0077\nSCREEN_WIDTH = getcanvas().winfo_width() / 2\nSCREEN_HEIGHT = getcanvas().winfo_height() / 2\nMY_BALL = 0, 0, 0.5, -0.4, 30\nNUMBER_OF_BALLS = 5\nMINIMUM_BALL_RADIUS = 10\nMAXIMUM_BALL_RADIUS = 100\nMINIMUM_BALL_DX = -5\nMAXIMUM_BALL_DX = 5\nMINIMUM_BALL_DY = -5\nMAXIMUM_BALL_DY = 5\nBALLS = []\nfor i in range(NUMBER_OF_BALLS):\n x = random.randint(int(-SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS), int(\n SCREEN_WIDTH / 2 - MAXIMUM_BALL_RADIUS))\n y = random.randint(-SCREEN_HEIGHT / 2 + MAXIMUM_BALL_RADIUS, \n SCREEN_HEIGHT / 2 - MAXIMUM_BALL_RADIUS)\n dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)\n dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)\n r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)\n while dx == 0:\n dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)\n while dy == 0:\n dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)\n new_ball = Ball(x, y, dx, dy, r)\n BALLS.append(new_ball)\n\n\ndef move_all_balls(BALLS):\n for index in range(len(BALLS)):\n BALLS[index].move(SCREEN_WIDTH, SCREEN_HEIGHT)\n\n\nmainloop()\n", "step-5": "from turtle import *\nimport time\nimport random\ncolormode(255)\n\nclass Ball(Turtle):\n def __init__(self, x,y,dx,dy,r):\n Turtle.__init__(self)\n self.pu()\n self.goto(x,y)\n self.dx = dx\n self.dy = dy\n self.r = r\n self.shape(\"circle\")\n self.shapesize(r/10)\n r = random.randint(0,255)\n g = random.randint(0,255)\n b = random.randint(0,255)\n self.color(r,g,b)\n def move(self,screen_width, screen_hight):\n current_x = self.xcor()\n new_x = current_x + self.dx\n current_y = self.ycor()\n new_y = current_y + self.dy\n right_side_ball = new_x + self.r\n left_side_ball = new_x - self.r\n bottom_ball = new_y - self.r\n upper_ball_side = new_y + self.r\n self.goto(new_x, new_y)\n if bottom_ball < -screen_hight/2 or upper_ball_side > screen_hight/2:\n self.dy *= -1\n if left_side_ball < -screen_width/2 or right_side_ball > screen_width/2:\n self.dx *= -1\n\ntracer(0)\nht()\nRUNNING = True\nSLEEP = 0.0077\nSCREEN_WIDTH = getcanvas().winfo_width()/2\nSCREEN_HEIGHT = getcanvas().winfo_height()/2\n\nMY_BALL = (0,0,0.5,-0.4,30)\nNUMBER_OF_BALLS = 5\nMINIMUM_BALL_RADIUS = 10\nMAXIMUM_BALL_RADIUS = 100\nMINIMUM_BALL_DX = -5\nMAXIMUM_BALL_DX = 5\nMINIMUM_BALL_DY = -5\nMAXIMUM_BALL_DY = 5\n\nBALLS = []\n\nfor i in range(NUMBER_OF_BALLS):\n x = random.randint(int(- SCREEN_WIDTH / 2 + MAXIMUM_BALL_RADIUS) , int(SCREEN_WIDTH/2 - MAXIMUM_BALL_RADIUS))\n y = random.randint(-SCREEN_HEIGHT/2 + MAXIMUM_BALL_RADIUS , SCREEN_HEIGHT/2 - MAXIMUM_BALL_RADIUS)\n dy = random.randint(MINIMUM_BALL_DY , MAXIMUM_BALL_DY)\n dx = random.randint(MINIMUM_BALL_DX , MAXIMUM_BALL_DX)\n r = random.randint(MINIMUM_BALL_RADIUS , MAXIMUM_BALL_RADIUS)\n while dx == 0:\n dx = random.randint(MINIMUM_BALL_DX , MAXIMUM_BALL_DX)\n while dy == 0:\n dy = random.randint(MINIMUM_BALL_DY , MAXIMUM_BALL_DY)\n new_ball = Ball(x,y,dx,dy,r)\n BALLS.append(new_ball)\n\ndef move_all_balls(BALLS):\n for index in range(len(BALLS)):\n BALLS[index].move(SCREEN_WIDTH , SCREEN_HEIGHT)\n\n#move_all_balls(BALLS)\n\nmainloop()\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
print raw_input().count(raw_input())
normal
{ "blob_id": "2d4b0e7b430ffb5d236300079ded4b848e6c6485", "index": 3602, "step-1": "print raw_input().count(raw_input())", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> from .FactorWarData import Get_FactorWar_Data
flexible
{ "blob_id": "5aa55a96e414ad6b3ceebbcbd71c23a1fd69f0d1", "index": 6400, "step-1": "<mask token>\n", "step-2": "from .FactorWarData import Get_FactorWar_Data\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
from zipfile import ZipFile import reference_new_stdds import reader import os def runall(path): print("==========================") """get the current path """ abs_file_path = os.path.abspath(__file__) parent_dir = os.path.dirname(abs_file_path) parent_dir = os.path.dirname(parent_dir) """ path that stores xml files""" xml_path = parent_dir.replace("\\", "/") + "/Examples/xmls/"+path # print(xml_path) """ call RIE module""" ref_list = reference_new_stdds.get_contri_info(xml_path) reference_new_stdds.write_excel(ref_list) """ call reader module""" reader.write_csv(path) # Create a zip file with ZipFile(parent_dir.replace("\\", "/")+'/Output/xmlOutput/XMLOutput.zip', 'w') as zipObj: # # Add multiple files to the zip zipObj.write(parent_dir.replace("\\", "/")+'/Output/xmlOutput/TNC_Taxonomic_name_usage_XmlOutput.csv', "TNC_Taxonomic_name_usage_XmlOutput.csv") zipObj.write(parent_dir.replace("\\", "/")+'/Output/xmlOutput/TNC_Typification_XmlOutput.csv', "TNC_Typification_XmlOutput.csv") zipObj.write(parent_dir.replace("\\", "/")+'/Output/xmlOutput/{}_XmlOutput.csv'.format(path.replace(".xml","")), "{}_XmlOutput.csv".format(path.replace(".xml",""))) zipObj.write(parent_dir.replace("\\", "/") + '/Output/xmlOutput/BibliographicResource.csv', "BibliographicResource.csv") runall("A_new_genus_and_two_new_species_of_miniature_clingfishes.xml")
normal
{ "blob_id": "1158ab95ac67d62459284267a8cc9f587daf89b1", "index": 9329, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef runall(path):\n print('==========================')\n \"\"\"get the current path \"\"\"\n abs_file_path = os.path.abspath(__file__)\n parent_dir = os.path.dirname(abs_file_path)\n parent_dir = os.path.dirname(parent_dir)\n \"\"\" path that stores xml files\"\"\"\n xml_path = parent_dir.replace('\\\\', '/') + '/Examples/xmls/' + path\n \"\"\" call RIE module\"\"\"\n ref_list = reference_new_stdds.get_contri_info(xml_path)\n reference_new_stdds.write_excel(ref_list)\n \"\"\" call reader module\"\"\"\n reader.write_csv(path)\n with ZipFile(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/XMLOutput.zip', 'w') as zipObj:\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/TNC_Taxonomic_name_usage_XmlOutput.csv',\n 'TNC_Taxonomic_name_usage_XmlOutput.csv')\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/TNC_Typification_XmlOutput.csv',\n 'TNC_Typification_XmlOutput.csv')\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/{}_XmlOutput.csv'.format(path.replace('.xml',\n '')), '{}_XmlOutput.csv'.format(path.replace('.xml', '')))\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/BibliographicResource.csv',\n 'BibliographicResource.csv')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef runall(path):\n print('==========================')\n \"\"\"get the current path \"\"\"\n abs_file_path = os.path.abspath(__file__)\n parent_dir = os.path.dirname(abs_file_path)\n parent_dir = os.path.dirname(parent_dir)\n \"\"\" path that stores xml files\"\"\"\n xml_path = parent_dir.replace('\\\\', '/') + '/Examples/xmls/' + path\n \"\"\" call RIE module\"\"\"\n ref_list = reference_new_stdds.get_contri_info(xml_path)\n reference_new_stdds.write_excel(ref_list)\n \"\"\" call reader module\"\"\"\n reader.write_csv(path)\n with ZipFile(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/XMLOutput.zip', 'w') as zipObj:\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/TNC_Taxonomic_name_usage_XmlOutput.csv',\n 'TNC_Taxonomic_name_usage_XmlOutput.csv')\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/TNC_Typification_XmlOutput.csv',\n 'TNC_Typification_XmlOutput.csv')\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/{}_XmlOutput.csv'.format(path.replace('.xml',\n '')), '{}_XmlOutput.csv'.format(path.replace('.xml', '')))\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/BibliographicResource.csv',\n 'BibliographicResource.csv')\n\n\nrunall('A_new_genus_and_two_new_species_of_miniature_clingfishes.xml')\n", "step-4": "from zipfile import ZipFile\nimport reference_new_stdds\nimport reader\nimport os\n\n\ndef runall(path):\n print('==========================')\n \"\"\"get the current path \"\"\"\n abs_file_path = os.path.abspath(__file__)\n parent_dir = os.path.dirname(abs_file_path)\n parent_dir = os.path.dirname(parent_dir)\n \"\"\" path that stores xml files\"\"\"\n xml_path = parent_dir.replace('\\\\', '/') + '/Examples/xmls/' + path\n \"\"\" call RIE module\"\"\"\n ref_list = reference_new_stdds.get_contri_info(xml_path)\n reference_new_stdds.write_excel(ref_list)\n \"\"\" call reader module\"\"\"\n reader.write_csv(path)\n with ZipFile(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/XMLOutput.zip', 'w') as zipObj:\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/TNC_Taxonomic_name_usage_XmlOutput.csv',\n 'TNC_Taxonomic_name_usage_XmlOutput.csv')\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/TNC_Typification_XmlOutput.csv',\n 'TNC_Typification_XmlOutput.csv')\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/{}_XmlOutput.csv'.format(path.replace('.xml',\n '')), '{}_XmlOutput.csv'.format(path.replace('.xml', '')))\n zipObj.write(parent_dir.replace('\\\\', '/') +\n '/Output/xmlOutput/BibliographicResource.csv',\n 'BibliographicResource.csv')\n\n\nrunall('A_new_genus_and_two_new_species_of_miniature_clingfishes.xml')\n", "step-5": "from zipfile import ZipFile\n\nimport reference_new_stdds\n\nimport reader\nimport os\n\ndef runall(path):\n print(\"==========================\")\n \"\"\"get the current path \"\"\"\n abs_file_path = os.path.abspath(__file__)\n parent_dir = os.path.dirname(abs_file_path)\n parent_dir = os.path.dirname(parent_dir)\n\n \"\"\" path that stores xml files\"\"\"\n xml_path = parent_dir.replace(\"\\\\\", \"/\") + \"/Examples/xmls/\"+path\n # print(xml_path)\n\n \"\"\" call RIE module\"\"\"\n ref_list = reference_new_stdds.get_contri_info(xml_path)\n reference_new_stdds.write_excel(ref_list)\n \"\"\" call reader module\"\"\"\n reader.write_csv(path)\n\n # Create a zip file\n with ZipFile(parent_dir.replace(\"\\\\\", \"/\")+'/Output/xmlOutput/XMLOutput.zip', 'w') as zipObj:\n\n # # Add multiple files to the zip\n zipObj.write(parent_dir.replace(\"\\\\\", \"/\")+'/Output/xmlOutput/TNC_Taxonomic_name_usage_XmlOutput.csv', \"TNC_Taxonomic_name_usage_XmlOutput.csv\")\n zipObj.write(parent_dir.replace(\"\\\\\", \"/\")+'/Output/xmlOutput/TNC_Typification_XmlOutput.csv', \"TNC_Typification_XmlOutput.csv\")\n zipObj.write(parent_dir.replace(\"\\\\\", \"/\")+'/Output/xmlOutput/{}_XmlOutput.csv'.format(path.replace(\".xml\",\"\")), \"{}_XmlOutput.csv\".format(path.replace(\".xml\",\"\")))\n zipObj.write(parent_dir.replace(\"\\\\\", \"/\") + '/Output/xmlOutput/BibliographicResource.csv', \"BibliographicResource.csv\")\n\n\n\nrunall(\"A_new_genus_and_two_new_species_of_miniature_clingfishes.xml\")\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python """ Expression Parser Tree for fully parenthesized input expression """ from bintree import BinaryTree from stackModule import Stack def buildParseTree(expression): expList = expression.split() empTree = BinaryTree('') parentStack = Stack() parentStack.push(empTree) currentNode = empTree for item in expList: if item == '(': currentNode.insertLeft('') parentStack.push(currentNode) currentNode = currentNode.getLeftChild() elif item not in ['+', '-', '*', '/', ')']: currentNode.setRootValue(int(item)) currentNode = parentStack.pop() elif item in ['+', '-', '*', '/']: currentNode.setRootValue(item) currentNode.insertRight('') parentStack.push(currentNode) currentNode = currentNode.getRightChild() elif item == ')': currentNode = parentStack.pop() else: raise ValueError return empTree import operator def evaluate(parseTree): opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv} leftC = parseTree.getLeftChild() rightC = parseTree.getRightChild() if leftC and rightC: fn = opers[parseTree.getRootValue()] return fn(evaluate(leftC),evaluate(rightC)) else: return parseTree.getRootValue() def postOrderTraversal(parseTree): if parseTree != None: postOrderTraversal(parseTree.getLeftChild()) postOrderTraversal(parseTree.getRightChild()) print parseTree.getRootValue() def preOrderTraversal(parseTree): if parseTree !=None: print parseTree.getRootValue() preOrderTraversal(parseTree.getLeftChild()) preOrderTraversal(parseTree.getRightChild()) def inOrderTraversal(parseTree): if parseTree !=None: inOrderTraversal(parseTree.getLeftChild()) print parseTree.getRootValue() inOrderTraversal(parseTree.getRightChild()) def iterInOrder(currentTree): pStack = Stack() print "\nPrinting in order traversal\n" while currentTree != None or not pStack.isEmpty(): if currentTree !=None: pStack.push(currentTree) currentTree = currentTree.getLeftChild() else: currentTree = pStack.pop() print currentTree.getRootValue() currentTree = currentTree.getRightChild() pt = buildParseTree("( ( 10 + 5 ) * 3 )") print "\nGiven Expression evaluates to %d\n" % evaluate(pt) preOrderTraversal(pt) postOrderTraversal(pt) inOrderTraversal(pt) iterInOrder(pt)
normal
{ "blob_id": "e18ebf961c2daa7dd127d08f85edb6ea519e3470", "index": 8359, "step-1": "#!/usr/bin/python\n\n\"\"\"\nExpression Parser Tree for fully parenthesized input expression\n\"\"\"\n\nfrom bintree import BinaryTree\nfrom stackModule import Stack\n\ndef buildParseTree(expression):\n expList = expression.split()\n empTree = BinaryTree('')\n parentStack = Stack()\n parentStack.push(empTree)\n currentNode = empTree\n\n for item in expList:\n if item == '(':\n currentNode.insertLeft('')\n parentStack.push(currentNode)\n currentNode = currentNode.getLeftChild()\n elif item not in ['+', '-', '*', '/', ')']:\n currentNode.setRootValue(int(item))\n currentNode = parentStack.pop()\n elif item in ['+', '-', '*', '/']:\n currentNode.setRootValue(item)\n currentNode.insertRight('')\n parentStack.push(currentNode)\n currentNode = currentNode.getRightChild()\n elif item == ')':\n currentNode = parentStack.pop()\n else:\n raise ValueError\n return empTree\n\nimport operator\n\ndef evaluate(parseTree):\n opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}\n\n leftC = parseTree.getLeftChild()\n rightC = parseTree.getRightChild()\n\n if leftC and rightC:\n fn = opers[parseTree.getRootValue()]\n return fn(evaluate(leftC),evaluate(rightC))\n else:\n return parseTree.getRootValue()\n\ndef postOrderTraversal(parseTree):\n\n if parseTree != None:\n postOrderTraversal(parseTree.getLeftChild())\n postOrderTraversal(parseTree.getRightChild())\n print parseTree.getRootValue()\n\ndef preOrderTraversal(parseTree):\n\n if parseTree !=None:\n print parseTree.getRootValue()\n preOrderTraversal(parseTree.getLeftChild())\n preOrderTraversal(parseTree.getRightChild())\n\ndef inOrderTraversal(parseTree):\n\n if parseTree !=None:\n inOrderTraversal(parseTree.getLeftChild())\n print parseTree.getRootValue()\n inOrderTraversal(parseTree.getRightChild())\n\n\ndef iterInOrder(currentTree):\n pStack = Stack()\n print \"\\nPrinting in order traversal\\n\"\n while currentTree != None or not pStack.isEmpty():\n if currentTree !=None:\n pStack.push(currentTree)\n currentTree = currentTree.getLeftChild()\n else:\n currentTree = pStack.pop()\n print currentTree.getRootValue()\n currentTree = currentTree.getRightChild()\n\n\npt = buildParseTree(\"( ( 10 + 5 ) * 3 )\")\nprint \"\\nGiven Expression evaluates to %d\\n\" % evaluate(pt)\npreOrderTraversal(pt)\npostOrderTraversal(pt)\ninOrderTraversal(pt)\niterInOrder(pt)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> def setStep(w1, w2, w3, w4): GPIO.output(A1Pin, w1) GPIO.output(A2Pin, w2) GPIO.output(B1Pin, w3) GPIO.output(B2Pin, w4) def wheel(pos): if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos * 3) b = 0 elif pos < 170: pos -= 85 r = int(255 - pos * 3) g = 0 b = int(pos * 3) else: pos -= 170 r = 0 g = int(pos * 3) b = int(255 - pos * 3) return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): pixel_index = i * 256 // num_pixels + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(wait) <|reserved_special_token_0|> def backwards(list, count): w1 = list[count][0] w2 = list[count][1] w3 = list[count][2] w4 = list[count][3] setStep(w1, w2, w3, w4) count += 1 if count >= 8: count = 0 return count <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) <|reserved_special_token_0|> GPIO.setup(enable_pin, GPIO.OUT) GPIO.setup(A1Pin, GPIO.OUT) GPIO.setup(A2Pin, GPIO.OUT) GPIO.setup(B1Pin, GPIO.OUT) GPIO.setup(B2Pin, GPIO.OUT) GPIO.output(enable_pin, 1) <|reserved_special_token_0|> def setStep(w1, w2, w3, w4): GPIO.output(A1Pin, w1) GPIO.output(A2Pin, w2) GPIO.output(B1Pin, w3) GPIO.output(B2Pin, w4) def wheel(pos): if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos * 3) b = 0 elif pos < 170: pos -= 85 r = int(255 - pos * 3) g = 0 b = int(pos * 3) else: pos -= 170 r = 0 g = int(pos * 3) b = int(255 - pos * 3) return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): pixel_index = i * 256 // num_pixels + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(wait) <|reserved_special_token_0|> def backwards(list, count): w1 = list[count][0] w2 = list[count][1] w3 = list[count][2] w4 = list[count][3] setStep(w1, w2, w3, w4) count += 1 if count >= 8: count = 0 return count for i in range(60): pixel[i] = 200, 100, 0 time.sleep(0.02) while True: for j in range(255): for i in range(num_pixels): pixel_index = i * 256 // num_pixels + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(0.005) if GPIO.input(20) == GPIO.HIGH: count = backwards(stepList, count) print('Pin 20') if GPIO.input(13) == GPIO.HIGH: print('Here comes the sun') os.system('python3 song2.py') if GPIO.input(19) == GPIO.HIGH: print('Button - September') os.system('python3 song4.py') if GPIO.input(26) == GPIO.HIGH: print('Button (26) 4 - Wonderwall') os.system('python3 song1.py') if GPIO.input(16) == GPIO.HIGH: print('Button (16) 6 - Shape of You') os.system('python3 song5.py') <|reserved_special_token_1|> <|reserved_special_token_0|> GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) enable_pin = 24 A1Pin = 23 A2Pin = 22 B1Pin = 27 B2Pin = 17 GPIO.setup(enable_pin, GPIO.OUT) GPIO.setup(A1Pin, GPIO.OUT) GPIO.setup(A2Pin, GPIO.OUT) GPIO.setup(B1Pin, GPIO.OUT) GPIO.setup(B2Pin, GPIO.OUT) GPIO.output(enable_pin, 1) pixel_pin = board.D21 num_pixels = 60 ORDER = neopixel.GRB CLEAR = 0, 0, 0 pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.03, auto_write=False, pixel_order=ORDER) pixel = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.1, pixel_order=ORDER) def setStep(w1, w2, w3, w4): GPIO.output(A1Pin, w1) GPIO.output(A2Pin, w2) GPIO.output(B1Pin, w3) GPIO.output(B2Pin, w4) def wheel(pos): if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos * 3) b = 0 elif pos < 170: pos -= 85 r = int(255 - pos * 3) g = 0 b = int(pos * 3) else: pos -= 170 r = 0 g = int(pos * 3) b = int(255 - pos * 3) return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): pixel_index = i * 256 // num_pixels + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(wait) stepList = [(1, 0, 0, 0), (1, 1, 0, 0), (0, 1, 0, 0), (0, 1, 1, 0), (0, 0, 1, 0), (0, 0, 1, 1), (0, 0, 0, 1), (1, 0, 0, 1)] count = 0 def backwards(list, count): w1 = list[count][0] w2 = list[count][1] w3 = list[count][2] w4 = list[count][3] setStep(w1, w2, w3, w4) count += 1 if count >= 8: count = 0 return count for i in range(60): pixel[i] = 200, 100, 0 time.sleep(0.02) while True: for j in range(255): for i in range(num_pixels): pixel_index = i * 256 // num_pixels + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(0.005) if GPIO.input(20) == GPIO.HIGH: count = backwards(stepList, count) print('Pin 20') if GPIO.input(13) == GPIO.HIGH: print('Here comes the sun') os.system('python3 song2.py') if GPIO.input(19) == GPIO.HIGH: print('Button - September') os.system('python3 song4.py') if GPIO.input(26) == GPIO.HIGH: print('Button (26) 4 - Wonderwall') os.system('python3 song1.py') if GPIO.input(16) == GPIO.HIGH: print('Button (16) 6 - Shape of You') os.system('python3 song5.py') <|reserved_special_token_1|> import os import RPi.GPIO as GPIO import time import neopixel import board GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) enable_pin = 24 A1Pin = 23 A2Pin = 22 B1Pin = 27 B2Pin = 17 GPIO.setup(enable_pin, GPIO.OUT) GPIO.setup(A1Pin, GPIO.OUT) GPIO.setup(A2Pin, GPIO.OUT) GPIO.setup(B1Pin, GPIO.OUT) GPIO.setup(B2Pin, GPIO.OUT) GPIO.output(enable_pin, 1) pixel_pin = board.D21 num_pixels = 60 ORDER = neopixel.GRB CLEAR = 0, 0, 0 pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.03, auto_write=False, pixel_order=ORDER) pixel = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.1, pixel_order=ORDER) def setStep(w1, w2, w3, w4): GPIO.output(A1Pin, w1) GPIO.output(A2Pin, w2) GPIO.output(B1Pin, w3) GPIO.output(B2Pin, w4) def wheel(pos): if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos * 3) b = 0 elif pos < 170: pos -= 85 r = int(255 - pos * 3) g = 0 b = int(pos * 3) else: pos -= 170 r = 0 g = int(pos * 3) b = int(255 - pos * 3) return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): pixel_index = i * 256 // num_pixels + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(wait) stepList = [(1, 0, 0, 0), (1, 1, 0, 0), (0, 1, 0, 0), (0, 1, 1, 0), (0, 0, 1, 0), (0, 0, 1, 1), (0, 0, 0, 1), (1, 0, 0, 1)] count = 0 def backwards(list, count): w1 = list[count][0] w2 = list[count][1] w3 = list[count][2] w4 = list[count][3] setStep(w1, w2, w3, w4) count += 1 if count >= 8: count = 0 return count for i in range(60): pixel[i] = 200, 100, 0 time.sleep(0.02) while True: for j in range(255): for i in range(num_pixels): pixel_index = i * 256 // num_pixels + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(0.005) if GPIO.input(20) == GPIO.HIGH: count = backwards(stepList, count) print('Pin 20') if GPIO.input(13) == GPIO.HIGH: print('Here comes the sun') os.system('python3 song2.py') if GPIO.input(19) == GPIO.HIGH: print('Button - September') os.system('python3 song4.py') if GPIO.input(26) == GPIO.HIGH: print('Button (26) 4 - Wonderwall') os.system('python3 song1.py') if GPIO.input(16) == GPIO.HIGH: print('Button (16) 6 - Shape of You') os.system('python3 song5.py') <|reserved_special_token_1|> import os import RPi.GPIO as GPIO import time import neopixel import board GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Setup button pins GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) enable_pin = 24 #Setup stepper motor pins A1Pin = 23 A2Pin = 22 B1Pin = 27 B2Pin = 17 GPIO.setup(enable_pin, GPIO.OUT) GPIO.setup(A1Pin, GPIO.OUT) GPIO.setup(A2Pin, GPIO.OUT) GPIO.setup(B1Pin, GPIO.OUT) GPIO.setup(B2Pin, GPIO.OUT) GPIO.output(enable_pin, 1) pixel_pin = board.D21 #Setup Neopixels num_pixels = 60 ORDER = neopixel.GRB CLEAR = (0,0,0) pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.03, auto_write=False, pixel_order=ORDER) pixel = neopixel.NeoPixel(pixel_pin, num_pixels, brightness = 0.1, pixel_order = ORDER) def setStep(w1,w2,w3,w4): #Send instructions to the stepper motor GPIO.output(A1Pin, w1) GPIO.output(A2Pin, w2) GPIO.output(B1Pin, w3) GPIO.output(B2Pin, w4) def wheel(pos): #Function to generate a wheel on NeoPixels, taken from Adafruit # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos*3) b = 0 elif pos < 170: pos -= 85 r = int(255 - pos*3) g = 0 b = int(pos*3) else: pos -= 170 r = 0 g = int(pos*3) b = int(255 - pos*3) return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0) def rainbow_cycle(wait): #Function to make the wheel transition through the entire colour spectrum, taken from Adafruit for j in range(255): for i in range(num_pixels): pixel_index = (i * 256 // num_pixels) + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(wait) stepList = [(1,0,0,0),(1,1,0,0),(0,1,0,0),(0,1,1,0),(0,0,1,0),(0,0,1,1),(0,0,0,1),(1,0,0,1)] #List of positions for stepper motor count = 0 def backwards(list, count): #Function to turn the motor backwards by sending the stepList in a certian way w1 = list[count][0] w2 = list[count][1] w3 = list[count][2] w4 = list[count][3] setStep(w1,w2,w3,w4) count+=1 if count >= 8: count = 0 return count for i in range(60): #Loading circle, shows Gizmo is ready to use pixel[i] = (200,100,0) time.sleep(0.02) while True: for j in range(255): #NeoPixels transistion through rainbow colours for i in range(num_pixels): pixel_index = (i * 256 // num_pixels) + j pixels[i] = wheel(pixel_index & 255) pixels.show() time.sleep(0.005) if GPIO.input(20) == GPIO.HIGH: # Button 1 turns the pointer back to the start position count = backwards(stepList, count) print ("Pin 20") if GPIO.input(13) == GPIO.HIGH: # The other buttons select the songs print ("Here comes the sun") os.system("python3 song2.py") if GPIO.input(19) == GPIO.HIGH: print ("Button - September") os.system("python3 song4.py") if GPIO.input(26) == GPIO.HIGH: print ("Button (26) 4 - Wonderwall") os.system("python3 song1.py") if GPIO.input(16) == GPIO.HIGH: print ("Button (16) 6 - Shape of You") os.system("python3 song5.py")
flexible
{ "blob_id": "4a711642af753ba2c82ce3351b052a4973e17e7d", "index": 9672, "step-1": "<mask token>\n\n\ndef setStep(w1, w2, w3, w4):\n GPIO.output(A1Pin, w1)\n GPIO.output(A2Pin, w2)\n GPIO.output(B1Pin, w3)\n GPIO.output(B2Pin, w4)\n\n\ndef wheel(pos):\n if pos < 0 or pos > 255:\n r = g = b = 0\n elif pos < 85:\n r = int(pos * 3)\n g = int(255 - pos * 3)\n b = 0\n elif pos < 170:\n pos -= 85\n r = int(255 - pos * 3)\n g = 0\n b = int(pos * 3)\n else:\n pos -= 170\n r = 0\n g = int(pos * 3)\n b = int(255 - pos * 3)\n return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r,\n g, b, 0)\n\n\ndef rainbow_cycle(wait):\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = i * 256 // num_pixels + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(wait)\n\n\n<mask token>\n\n\ndef backwards(list, count):\n w1 = list[count][0]\n w2 = list[count][1]\n w3 = list[count][2]\n w4 = list[count][3]\n setStep(w1, w2, w3, w4)\n count += 1\n if count >= 8:\n count = 0\n return count\n\n\n<mask token>\n", "step-2": "<mask token>\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n<mask token>\nGPIO.setup(enable_pin, GPIO.OUT)\nGPIO.setup(A1Pin, GPIO.OUT)\nGPIO.setup(A2Pin, GPIO.OUT)\nGPIO.setup(B1Pin, GPIO.OUT)\nGPIO.setup(B2Pin, GPIO.OUT)\nGPIO.output(enable_pin, 1)\n<mask token>\n\n\ndef setStep(w1, w2, w3, w4):\n GPIO.output(A1Pin, w1)\n GPIO.output(A2Pin, w2)\n GPIO.output(B1Pin, w3)\n GPIO.output(B2Pin, w4)\n\n\ndef wheel(pos):\n if pos < 0 or pos > 255:\n r = g = b = 0\n elif pos < 85:\n r = int(pos * 3)\n g = int(255 - pos * 3)\n b = 0\n elif pos < 170:\n pos -= 85\n r = int(255 - pos * 3)\n g = 0\n b = int(pos * 3)\n else:\n pos -= 170\n r = 0\n g = int(pos * 3)\n b = int(255 - pos * 3)\n return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r,\n g, b, 0)\n\n\ndef rainbow_cycle(wait):\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = i * 256 // num_pixels + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(wait)\n\n\n<mask token>\n\n\ndef backwards(list, count):\n w1 = list[count][0]\n w2 = list[count][1]\n w3 = list[count][2]\n w4 = list[count][3]\n setStep(w1, w2, w3, w4)\n count += 1\n if count >= 8:\n count = 0\n return count\n\n\nfor i in range(60):\n pixel[i] = 200, 100, 0\n time.sleep(0.02)\nwhile True:\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = i * 256 // num_pixels + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(0.005)\n if GPIO.input(20) == GPIO.HIGH:\n count = backwards(stepList, count)\n print('Pin 20')\n if GPIO.input(13) == GPIO.HIGH:\n print('Here comes the sun')\n os.system('python3 song2.py')\n if GPIO.input(19) == GPIO.HIGH:\n print('Button - September')\n os.system('python3 song4.py')\n if GPIO.input(26) == GPIO.HIGH:\n print('Button (26) 4 - Wonderwall')\n os.system('python3 song1.py')\n if GPIO.input(16) == GPIO.HIGH:\n print('Button (16) 6 - Shape of You')\n os.system('python3 song5.py')\n", "step-3": "<mask token>\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nenable_pin = 24\nA1Pin = 23\nA2Pin = 22\nB1Pin = 27\nB2Pin = 17\nGPIO.setup(enable_pin, GPIO.OUT)\nGPIO.setup(A1Pin, GPIO.OUT)\nGPIO.setup(A2Pin, GPIO.OUT)\nGPIO.setup(B1Pin, GPIO.OUT)\nGPIO.setup(B2Pin, GPIO.OUT)\nGPIO.output(enable_pin, 1)\npixel_pin = board.D21\nnum_pixels = 60\nORDER = neopixel.GRB\nCLEAR = 0, 0, 0\npixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.03,\n auto_write=False, pixel_order=ORDER)\npixel = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.1,\n pixel_order=ORDER)\n\n\ndef setStep(w1, w2, w3, w4):\n GPIO.output(A1Pin, w1)\n GPIO.output(A2Pin, w2)\n GPIO.output(B1Pin, w3)\n GPIO.output(B2Pin, w4)\n\n\ndef wheel(pos):\n if pos < 0 or pos > 255:\n r = g = b = 0\n elif pos < 85:\n r = int(pos * 3)\n g = int(255 - pos * 3)\n b = 0\n elif pos < 170:\n pos -= 85\n r = int(255 - pos * 3)\n g = 0\n b = int(pos * 3)\n else:\n pos -= 170\n r = 0\n g = int(pos * 3)\n b = int(255 - pos * 3)\n return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r,\n g, b, 0)\n\n\ndef rainbow_cycle(wait):\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = i * 256 // num_pixels + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(wait)\n\n\nstepList = [(1, 0, 0, 0), (1, 1, 0, 0), (0, 1, 0, 0), (0, 1, 1, 0), (0, 0, \n 1, 0), (0, 0, 1, 1), (0, 0, 0, 1), (1, 0, 0, 1)]\ncount = 0\n\n\ndef backwards(list, count):\n w1 = list[count][0]\n w2 = list[count][1]\n w3 = list[count][2]\n w4 = list[count][3]\n setStep(w1, w2, w3, w4)\n count += 1\n if count >= 8:\n count = 0\n return count\n\n\nfor i in range(60):\n pixel[i] = 200, 100, 0\n time.sleep(0.02)\nwhile True:\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = i * 256 // num_pixels + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(0.005)\n if GPIO.input(20) == GPIO.HIGH:\n count = backwards(stepList, count)\n print('Pin 20')\n if GPIO.input(13) == GPIO.HIGH:\n print('Here comes the sun')\n os.system('python3 song2.py')\n if GPIO.input(19) == GPIO.HIGH:\n print('Button - September')\n os.system('python3 song4.py')\n if GPIO.input(26) == GPIO.HIGH:\n print('Button (26) 4 - Wonderwall')\n os.system('python3 song1.py')\n if GPIO.input(16) == GPIO.HIGH:\n print('Button (16) 6 - Shape of You')\n os.system('python3 song5.py')\n", "step-4": "import os\nimport RPi.GPIO as GPIO\nimport time\nimport neopixel\nimport board\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nenable_pin = 24\nA1Pin = 23\nA2Pin = 22\nB1Pin = 27\nB2Pin = 17\nGPIO.setup(enable_pin, GPIO.OUT)\nGPIO.setup(A1Pin, GPIO.OUT)\nGPIO.setup(A2Pin, GPIO.OUT)\nGPIO.setup(B1Pin, GPIO.OUT)\nGPIO.setup(B2Pin, GPIO.OUT)\nGPIO.output(enable_pin, 1)\npixel_pin = board.D21\nnum_pixels = 60\nORDER = neopixel.GRB\nCLEAR = 0, 0, 0\npixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.03,\n auto_write=False, pixel_order=ORDER)\npixel = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.1,\n pixel_order=ORDER)\n\n\ndef setStep(w1, w2, w3, w4):\n GPIO.output(A1Pin, w1)\n GPIO.output(A2Pin, w2)\n GPIO.output(B1Pin, w3)\n GPIO.output(B2Pin, w4)\n\n\ndef wheel(pos):\n if pos < 0 or pos > 255:\n r = g = b = 0\n elif pos < 85:\n r = int(pos * 3)\n g = int(255 - pos * 3)\n b = 0\n elif pos < 170:\n pos -= 85\n r = int(255 - pos * 3)\n g = 0\n b = int(pos * 3)\n else:\n pos -= 170\n r = 0\n g = int(pos * 3)\n b = int(255 - pos * 3)\n return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r,\n g, b, 0)\n\n\ndef rainbow_cycle(wait):\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = i * 256 // num_pixels + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(wait)\n\n\nstepList = [(1, 0, 0, 0), (1, 1, 0, 0), (0, 1, 0, 0), (0, 1, 1, 0), (0, 0, \n 1, 0), (0, 0, 1, 1), (0, 0, 0, 1), (1, 0, 0, 1)]\ncount = 0\n\n\ndef backwards(list, count):\n w1 = list[count][0]\n w2 = list[count][1]\n w3 = list[count][2]\n w4 = list[count][3]\n setStep(w1, w2, w3, w4)\n count += 1\n if count >= 8:\n count = 0\n return count\n\n\nfor i in range(60):\n pixel[i] = 200, 100, 0\n time.sleep(0.02)\nwhile True:\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = i * 256 // num_pixels + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(0.005)\n if GPIO.input(20) == GPIO.HIGH:\n count = backwards(stepList, count)\n print('Pin 20')\n if GPIO.input(13) == GPIO.HIGH:\n print('Here comes the sun')\n os.system('python3 song2.py')\n if GPIO.input(19) == GPIO.HIGH:\n print('Button - September')\n os.system('python3 song4.py')\n if GPIO.input(26) == GPIO.HIGH:\n print('Button (26) 4 - Wonderwall')\n os.system('python3 song1.py')\n if GPIO.input(16) == GPIO.HIGH:\n print('Button (16) 6 - Shape of You')\n os.system('python3 song5.py')\n", "step-5": "import os\nimport RPi.GPIO as GPIO\nimport time\nimport neopixel\nimport board\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Setup button pins\nGPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\nenable_pin = 24 #Setup stepper motor pins\nA1Pin = 23\nA2Pin = 22\nB1Pin = 27\nB2Pin = 17\n\nGPIO.setup(enable_pin, GPIO.OUT)\nGPIO.setup(A1Pin, GPIO.OUT)\nGPIO.setup(A2Pin, GPIO.OUT)\nGPIO.setup(B1Pin, GPIO.OUT)\nGPIO.setup(B2Pin, GPIO.OUT)\n\nGPIO.output(enable_pin, 1)\n\npixel_pin = board.D21 #Setup Neopixels\nnum_pixels = 60\nORDER = neopixel.GRB\nCLEAR = (0,0,0)\npixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.03, auto_write=False,\n pixel_order=ORDER)\npixel = neopixel.NeoPixel(pixel_pin, num_pixels, brightness = 0.1, pixel_order = ORDER)\n\ndef setStep(w1,w2,w3,w4): #Send instructions to the stepper motor\n GPIO.output(A1Pin, w1)\n GPIO.output(A2Pin, w2)\n GPIO.output(B1Pin, w3)\n GPIO.output(B2Pin, w4)\n\ndef wheel(pos): #Function to generate a wheel on NeoPixels, taken from Adafruit\n # Input a value 0 to 255 to get a color value.\n # The colours are a transition r - g - b - back to r.\n if pos < 0 or pos > 255:\n r = g = b = 0\n elif pos < 85:\n r = int(pos * 3)\n g = int(255 - pos*3)\n b = 0\n elif pos < 170:\n pos -= 85\n r = int(255 - pos*3)\n g = 0\n b = int(pos*3)\n else:\n pos -= 170\n r = 0\n g = int(pos*3)\n b = int(255 - pos*3)\n return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0)\n\ndef rainbow_cycle(wait): #Function to make the wheel transition through the entire colour spectrum, taken from Adafruit\n for j in range(255):\n for i in range(num_pixels):\n pixel_index = (i * 256 // num_pixels) + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(wait)\n\nstepList = [(1,0,0,0),(1,1,0,0),(0,1,0,0),(0,1,1,0),(0,0,1,0),(0,0,1,1),(0,0,0,1),(1,0,0,1)] #List of positions for stepper motor\ncount = 0\ndef backwards(list, count): #Function to turn the motor backwards by sending the stepList in a certian way\n w1 = list[count][0]\n w2 = list[count][1]\n w3 = list[count][2]\n w4 = list[count][3]\n setStep(w1,w2,w3,w4)\n count+=1\n if count >= 8:\n count = 0\n return count\n\nfor i in range(60): #Loading circle, shows Gizmo is ready to use\n pixel[i] = (200,100,0)\n time.sleep(0.02)\nwhile True:\n for j in range(255): #NeoPixels transistion through rainbow colours\n for i in range(num_pixels):\n pixel_index = (i * 256 // num_pixels) + j\n pixels[i] = wheel(pixel_index & 255)\n pixels.show()\n time.sleep(0.005)\n if GPIO.input(20) == GPIO.HIGH: # Button 1 turns the pointer back to the start position\n count = backwards(stepList, count)\n print (\"Pin 20\")\n if GPIO.input(13) == GPIO.HIGH: # The other buttons select the songs\n print (\"Here comes the sun\")\n os.system(\"python3 song2.py\")\n if GPIO.input(19) == GPIO.HIGH:\n print (\"Button - September\")\n os.system(\"python3 song4.py\")\n if GPIO.input(26) == GPIO.HIGH:\n print (\"Button (26) 4 - Wonderwall\")\n os.system(\"python3 song1.py\")\n if GPIO.input(16) == GPIO.HIGH:\n print (\"Button (16) 6 - Shape of You\")\n os.system(\"python3 song5.py\")\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> class TestViews(TestCase): <|reserved_special_token_0|> def test_add_order_get(self): response = self.client.get(url_for('add_order')) self.assertEqual(response.status_code, 200) def test_view_order_get(self): response = self.client.get(url_for('view_order', id=1)) self.assertEqual(response.status_code, 200) def test_register_get(self): response = self.client.get(url_for('register')) self.assertEqual(response.status_code, 200) <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class TestCreateUser(TestCase): def test_create_user(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test2', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) user = Users.query.filter_by(id=2).first() self.assertEqual('[email protected]', user.email) self.assertEqual('Test2', user.name) self.assertEqual('82', user.house_number) self.assertEqual('G2 8PX', user.postcode) self.assertEqual('0788888888', user.phone) class TestDuplicateEmail(TestCase): def test_duplicate_email(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) class TestAddOrder(TestCase): def test_add_order(self): response = self.client.post(url_for('add_order', id=1), data=dict( email='[email protected]'), follow_redirects=True) order = Orders.query.filter_by(id=1).first() user = Users.query.filter_by(id=1).first() self.assertEqual(1, order.customer_id) self.assertEqual('order placed', order.order_status) self.assertEqual(None, order.tracking_num) self.assertIn(order, user.orders) class TestAddOrderNoUser(TestCase): def test_add_order_no_user(self): response = self.client.post(url_for('add_order'), data=dict(email= '[email protected]')) class TestViewOrder(TestCase): def test_view_order(self): response = self.client.get(url_for('view_order', id=1), data=dict( id='0006', name='Test', house_number='8', postode='G3 8PX', phone='07999999999')) self.assertIn(b'0001', response.data) self.assertIn(b'Test', response.data) self.assertIn(b'8', response.data) self.assertIn(b'G3 8PX', response.data) self.assertIn(b'07999999999', response.data) class TestUpdateOrder(TestCase): def test_update_order(self): response = self.client.post(url_for('update_order', id=1), data= dict(status='out for delivery', tracking_num_len=8)) order = Orders.query.filter_by(id=1).first() self.assertEqual('out for delivery', order.order_status) self.assertEqual(len(order.tracking_num), 8) class TestDelivered(TestCase): def test_delivered(self): response = self.client.post(url_for('delivered', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual('delivered', order.order_status) class TestDelete(TestCase): def test_delete(self): response = self.client.post(url_for('delete', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual(order, None) <|reserved_special_token_1|> <|reserved_special_token_0|> class TestPadNum(TestCase): <|reserved_special_token_0|> class TestTrackingGen(TestCase): def test_tracking_gen(self): self.assertEqual(len(tracking_gen()), 8) class TestViews(TestCase): def test_home_get(self): response = self.client.get(url_for('home')) self.assertEqual(response.status_code, 200) def test_add_order_get(self): response = self.client.get(url_for('add_order')) self.assertEqual(response.status_code, 200) def test_view_order_get(self): response = self.client.get(url_for('view_order', id=1)) self.assertEqual(response.status_code, 200) def test_register_get(self): response = self.client.get(url_for('register')) self.assertEqual(response.status_code, 200) def test_update_order_get(self): response = self.client.get(url_for('update_order', id=1)) self.assertEqual(response.status_code, 200) def test_delete_get(self): response = self.client.get(url_for('delete', id=1)) self.assertEqual(response.status_code, 405) def test_delivered_get(self): response = self.client.get(url_for('delivered', id=1)) self.assertEqual(response.status_code, 405) class TestCreateUser(TestCase): def test_create_user(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test2', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) user = Users.query.filter_by(id=2).first() self.assertEqual('[email protected]', user.email) self.assertEqual('Test2', user.name) self.assertEqual('82', user.house_number) self.assertEqual('G2 8PX', user.postcode) self.assertEqual('0788888888', user.phone) class TestDuplicateEmail(TestCase): def test_duplicate_email(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) class TestAddOrder(TestCase): def test_add_order(self): response = self.client.post(url_for('add_order', id=1), data=dict( email='[email protected]'), follow_redirects=True) order = Orders.query.filter_by(id=1).first() user = Users.query.filter_by(id=1).first() self.assertEqual(1, order.customer_id) self.assertEqual('order placed', order.order_status) self.assertEqual(None, order.tracking_num) self.assertIn(order, user.orders) class TestAddOrderNoUser(TestCase): def test_add_order_no_user(self): response = self.client.post(url_for('add_order'), data=dict(email= '[email protected]')) class TestViewOrder(TestCase): def test_view_order(self): response = self.client.get(url_for('view_order', id=1), data=dict( id='0006', name='Test', house_number='8', postode='G3 8PX', phone='07999999999')) self.assertIn(b'0001', response.data) self.assertIn(b'Test', response.data) self.assertIn(b'8', response.data) self.assertIn(b'G3 8PX', response.data) self.assertIn(b'07999999999', response.data) class TestUpdateOrder(TestCase): def test_update_order(self): response = self.client.post(url_for('update_order', id=1), data= dict(status='out for delivery', tracking_num_len=8)) order = Orders.query.filter_by(id=1).first() self.assertEqual('out for delivery', order.order_status) self.assertEqual(len(order.tracking_num), 8) class TestDelivered(TestCase): def test_delivered(self): response = self.client.post(url_for('delivered', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual('delivered', order.order_status) class TestDelete(TestCase): def test_delete(self): response = self.client.post(url_for('delete', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual(order, None) <|reserved_special_token_1|> <|reserved_special_token_0|> class TestCase(TestCase): def create_app(self): app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db', SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False) return app def setUp(self): db.create_all() new_user = Users(email='[email protected]', name='Test', house_number= '8', postcode='G3 8PX', phone='07999999999') db.session.add(new_user) new_order = Orders(customer_id=1) db.session.add(new_order) new_order = Orders(customer_id=1, order_status='out for delivery') db.session.add(new_order) new_order = Orders(customer_id=1, order_status='delivered') db.session.add(new_order) db.session.commit() def tearDown(self): db.session.remove() db.drop_all() class TestPadNum(TestCase): def test_pad_num(self): self.assertEqual(len(pad_num(3)), 4) class TestTrackingGen(TestCase): def test_tracking_gen(self): self.assertEqual(len(tracking_gen()), 8) class TestViews(TestCase): def test_home_get(self): response = self.client.get(url_for('home')) self.assertEqual(response.status_code, 200) def test_add_order_get(self): response = self.client.get(url_for('add_order')) self.assertEqual(response.status_code, 200) def test_view_order_get(self): response = self.client.get(url_for('view_order', id=1)) self.assertEqual(response.status_code, 200) def test_register_get(self): response = self.client.get(url_for('register')) self.assertEqual(response.status_code, 200) def test_update_order_get(self): response = self.client.get(url_for('update_order', id=1)) self.assertEqual(response.status_code, 200) def test_delete_get(self): response = self.client.get(url_for('delete', id=1)) self.assertEqual(response.status_code, 405) def test_delivered_get(self): response = self.client.get(url_for('delivered', id=1)) self.assertEqual(response.status_code, 405) class TestCreateUser(TestCase): def test_create_user(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test2', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) user = Users.query.filter_by(id=2).first() self.assertEqual('[email protected]', user.email) self.assertEqual('Test2', user.name) self.assertEqual('82', user.house_number) self.assertEqual('G2 8PX', user.postcode) self.assertEqual('0788888888', user.phone) class TestDuplicateEmail(TestCase): def test_duplicate_email(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) class TestAddOrder(TestCase): def test_add_order(self): response = self.client.post(url_for('add_order', id=1), data=dict( email='[email protected]'), follow_redirects=True) order = Orders.query.filter_by(id=1).first() user = Users.query.filter_by(id=1).first() self.assertEqual(1, order.customer_id) self.assertEqual('order placed', order.order_status) self.assertEqual(None, order.tracking_num) self.assertIn(order, user.orders) class TestAddOrderNoUser(TestCase): def test_add_order_no_user(self): response = self.client.post(url_for('add_order'), data=dict(email= '[email protected]')) class TestViewOrder(TestCase): def test_view_order(self): response = self.client.get(url_for('view_order', id=1), data=dict( id='0006', name='Test', house_number='8', postode='G3 8PX', phone='07999999999')) self.assertIn(b'0001', response.data) self.assertIn(b'Test', response.data) self.assertIn(b'8', response.data) self.assertIn(b'G3 8PX', response.data) self.assertIn(b'07999999999', response.data) class TestUpdateOrder(TestCase): def test_update_order(self): response = self.client.post(url_for('update_order', id=1), data= dict(status='out for delivery', tracking_num_len=8)) order = Orders.query.filter_by(id=1).first() self.assertEqual('out for delivery', order.order_status) self.assertEqual(len(order.tracking_num), 8) class TestDelivered(TestCase): def test_delivered(self): response = self.client.post(url_for('delivered', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual('delivered', order.order_status) class TestDelete(TestCase): def test_delete(self): response = self.client.post(url_for('delete', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual(order, None) <|reserved_special_token_1|> from application.routes import pad_num, tracking_gen from flask import url_for from flask_testing import TestCase from application import app, db from application.models import Users, Orders from os import getenv class TestCase(TestCase): def create_app(self): app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db', SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False) return app def setUp(self): db.create_all() new_user = Users(email='[email protected]', name='Test', house_number= '8', postcode='G3 8PX', phone='07999999999') db.session.add(new_user) new_order = Orders(customer_id=1) db.session.add(new_order) new_order = Orders(customer_id=1, order_status='out for delivery') db.session.add(new_order) new_order = Orders(customer_id=1, order_status='delivered') db.session.add(new_order) db.session.commit() def tearDown(self): db.session.remove() db.drop_all() class TestPadNum(TestCase): def test_pad_num(self): self.assertEqual(len(pad_num(3)), 4) class TestTrackingGen(TestCase): def test_tracking_gen(self): self.assertEqual(len(tracking_gen()), 8) class TestViews(TestCase): def test_home_get(self): response = self.client.get(url_for('home')) self.assertEqual(response.status_code, 200) def test_add_order_get(self): response = self.client.get(url_for('add_order')) self.assertEqual(response.status_code, 200) def test_view_order_get(self): response = self.client.get(url_for('view_order', id=1)) self.assertEqual(response.status_code, 200) def test_register_get(self): response = self.client.get(url_for('register')) self.assertEqual(response.status_code, 200) def test_update_order_get(self): response = self.client.get(url_for('update_order', id=1)) self.assertEqual(response.status_code, 200) def test_delete_get(self): response = self.client.get(url_for('delete', id=1)) self.assertEqual(response.status_code, 405) def test_delivered_get(self): response = self.client.get(url_for('delivered', id=1)) self.assertEqual(response.status_code, 405) class TestCreateUser(TestCase): def test_create_user(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test2', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) user = Users.query.filter_by(id=2).first() self.assertEqual('[email protected]', user.email) self.assertEqual('Test2', user.name) self.assertEqual('82', user.house_number) self.assertEqual('G2 8PX', user.postcode) self.assertEqual('0788888888', user.phone) class TestDuplicateEmail(TestCase): def test_duplicate_email(self): response = self.client.post(url_for('register'), data=dict(email= '[email protected]', name='Test', house_number='82', postcode= 'G2 8PX', phone='0788888888'), follow_redirects=True) class TestAddOrder(TestCase): def test_add_order(self): response = self.client.post(url_for('add_order', id=1), data=dict( email='[email protected]'), follow_redirects=True) order = Orders.query.filter_by(id=1).first() user = Users.query.filter_by(id=1).first() self.assertEqual(1, order.customer_id) self.assertEqual('order placed', order.order_status) self.assertEqual(None, order.tracking_num) self.assertIn(order, user.orders) class TestAddOrderNoUser(TestCase): def test_add_order_no_user(self): response = self.client.post(url_for('add_order'), data=dict(email= '[email protected]')) class TestViewOrder(TestCase): def test_view_order(self): response = self.client.get(url_for('view_order', id=1), data=dict( id='0006', name='Test', house_number='8', postode='G3 8PX', phone='07999999999')) self.assertIn(b'0001', response.data) self.assertIn(b'Test', response.data) self.assertIn(b'8', response.data) self.assertIn(b'G3 8PX', response.data) self.assertIn(b'07999999999', response.data) class TestUpdateOrder(TestCase): def test_update_order(self): response = self.client.post(url_for('update_order', id=1), data= dict(status='out for delivery', tracking_num_len=8)) order = Orders.query.filter_by(id=1).first() self.assertEqual('out for delivery', order.order_status) self.assertEqual(len(order.tracking_num), 8) class TestDelivered(TestCase): def test_delivered(self): response = self.client.post(url_for('delivered', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual('delivered', order.order_status) class TestDelete(TestCase): def test_delete(self): response = self.client.post(url_for('delete', id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual(order, None) <|reserved_special_token_1|> from application.routes import pad_num, tracking_gen from flask import url_for from flask_testing import TestCase from application import app, db from application.models import Users, Orders from os import getenv class TestCase(TestCase): def create_app(self): app.config.update( SQLALCHEMY_DATABASE_URI="sqlite:///test.db", SECRET_KEY="TEST_SECRET_KEY", DEBUG=True, WTF_CSRF_ENABLED=False, ) return app def setUp(self): db.create_all() new_user = Users( email="[email protected]", name="Test", house_number="8", postcode="G3 8PX", phone="07999999999", ) db.session.add(new_user) new_order = Orders(customer_id=1) db.session.add(new_order) new_order = Orders(customer_id=1, order_status="out for delivery") db.session.add(new_order) new_order = Orders(customer_id=1, order_status="delivered") db.session.add(new_order) db.session.commit() def tearDown(self): db.session.remove() db.drop_all() class TestPadNum(TestCase): def test_pad_num(self): self.assertEqual(len(pad_num(3)), 4) class TestTrackingGen(TestCase): def test_tracking_gen(self): self.assertEqual(len(tracking_gen()), 8) class TestViews(TestCase): def test_home_get(self): response = self.client.get(url_for("home")) self.assertEqual(response.status_code, 200) def test_add_order_get(self): response = self.client.get(url_for("add_order")) self.assertEqual(response.status_code, 200) def test_view_order_get(self): response = self.client.get(url_for("view_order", id=1)) self.assertEqual(response.status_code, 200) def test_register_get(self): response = self.client.get(url_for("register")) self.assertEqual(response.status_code, 200) def test_update_order_get(self): response = self.client.get(url_for("update_order", id=1)) self.assertEqual(response.status_code, 200) def test_delete_get(self): response = self.client.get(url_for("delete", id=1)) self.assertEqual(response.status_code, 405) def test_delivered_get(self): response = self.client.get(url_for("delivered", id=1)) self.assertEqual(response.status_code, 405) class TestCreateUser(TestCase): def test_create_user(self): response = self.client.post( url_for("register"), data=dict( email="[email protected]", name="Test2", house_number="82", postcode="G2 8PX", phone="0788888888", ), follow_redirects=True, ) user = Users.query.filter_by(id=2).first() self.assertEqual("[email protected]", user.email) self.assertEqual("Test2", user.name) self.assertEqual("82", user.house_number) self.assertEqual("G2 8PX", user.postcode) self.assertEqual("0788888888", user.phone) class TestDuplicateEmail(TestCase): def test_duplicate_email(self): response = self.client.post( url_for("register"), data=dict( email="[email protected]", name="Test", house_number="82", postcode="G2 8PX", phone="0788888888", ), follow_redirects=True, ) class TestAddOrder(TestCase): def test_add_order(self): response = self.client.post( url_for("add_order", id=1), data=dict(email="[email protected]"), follow_redirects=True, ) order = Orders.query.filter_by(id=1).first() user = Users.query.filter_by(id=1).first() self.assertEqual(1, order.customer_id) self.assertEqual("order placed", order.order_status) self.assertEqual(None, order.tracking_num) self.assertIn(order, user.orders) class TestAddOrderNoUser(TestCase): def test_add_order_no_user(self): response = self.client.post( url_for("add_order"), data=dict(email="[email protected]") ) class TestViewOrder(TestCase): def test_view_order(self): response = self.client.get( url_for("view_order", id=1), data=dict( id="0006", name="Test", house_number="8", postode="G3 8PX", phone="07999999999", ), ) self.assertIn(b"0001", response.data) self.assertIn(b"Test", response.data) self.assertIn(b"8", response.data) self.assertIn(b"G3 8PX", response.data) self.assertIn(b"07999999999", response.data) class TestUpdateOrder(TestCase): def test_update_order(self): response = self.client.post( url_for("update_order", id=1), data=dict( status="out for delivery", tracking_num_len=8, ), ) order = Orders.query.filter_by(id=1).first() self.assertEqual("out for delivery", order.order_status) self.assertEqual(len(order.tracking_num), 8) class TestDelivered(TestCase): def test_delivered(self): response = self.client.post(url_for("delivered", id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual("delivered", order.order_status) class TestDelete(TestCase): def test_delete(self): response = self.client.post(url_for("delete", id=1)) order = Orders.query.filter_by(id=1).first() self.assertEqual(order, None)
flexible
{ "blob_id": "eeece3bf423f85f05ef11db47909215578e64aec", "index": 4912, "step-1": "<mask token>\n\n\nclass TestViews(TestCase):\n <mask token>\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-2": "<mask token>\n\n\nclass TestPadNum(TestCase):\n <mask token>\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-3": "<mask token>\n\n\nclass TestCase(TestCase):\n\n def create_app(self):\n app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db',\n SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False)\n return app\n\n def setUp(self):\n db.create_all()\n new_user = Users(email='[email protected]', name='Test', house_number=\n '8', postcode='G3 8PX', phone='07999999999')\n db.session.add(new_user)\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='out for delivery')\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='delivered')\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-4": "from application.routes import pad_num, tracking_gen\nfrom flask import url_for\nfrom flask_testing import TestCase\nfrom application import app, db\nfrom application.models import Users, Orders\nfrom os import getenv\n\n\nclass TestCase(TestCase):\n\n def create_app(self):\n app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db',\n SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False)\n return app\n\n def setUp(self):\n db.create_all()\n new_user = Users(email='[email protected]', name='Test', house_number=\n '8', postcode='G3 8PX', phone='07999999999')\n db.session.add(new_user)\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='out for delivery')\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='delivered')\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-5": "from application.routes import pad_num, tracking_gen\nfrom flask import url_for\nfrom flask_testing import TestCase\n\nfrom application import app, db\nfrom application.models import Users, Orders\nfrom os import getenv\n\n\nclass TestCase(TestCase):\n def create_app(self):\n app.config.update(\n SQLALCHEMY_DATABASE_URI=\"sqlite:///test.db\",\n SECRET_KEY=\"TEST_SECRET_KEY\",\n DEBUG=True,\n WTF_CSRF_ENABLED=False,\n )\n return app\n\n def setUp(self):\n db.create_all()\n\n new_user = Users(\n email=\"[email protected]\",\n name=\"Test\",\n house_number=\"8\",\n postcode=\"G3 8PX\",\n phone=\"07999999999\",\n )\n db.session.add(new_user)\n\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n\n new_order = Orders(customer_id=1, order_status=\"out for delivery\")\n db.session.add(new_order)\n\n new_order = Orders(customer_id=1, order_status=\"delivered\")\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n def test_home_get(self):\n response = self.client.get(url_for(\"home\"))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for(\"add_order\"))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for(\"view_order\", id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for(\"register\"))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for(\"update_order\", id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for(\"delete\", id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for(\"delivered\", id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n def test_create_user(self):\n response = self.client.post(\n url_for(\"register\"),\n data=dict(\n email=\"[email protected]\",\n name=\"Test2\",\n house_number=\"82\",\n postcode=\"G2 8PX\",\n phone=\"0788888888\",\n ),\n follow_redirects=True,\n )\n user = Users.query.filter_by(id=2).first()\n self.assertEqual(\"[email protected]\", user.email)\n self.assertEqual(\"Test2\", user.name)\n self.assertEqual(\"82\", user.house_number)\n self.assertEqual(\"G2 8PX\", user.postcode)\n self.assertEqual(\"0788888888\", user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n def test_duplicate_email(self):\n response = self.client.post(\n url_for(\"register\"),\n data=dict(\n email=\"[email protected]\",\n name=\"Test\",\n house_number=\"82\",\n postcode=\"G2 8PX\",\n phone=\"0788888888\",\n ),\n follow_redirects=True,\n )\n\n\nclass TestAddOrder(TestCase):\n def test_add_order(self):\n response = self.client.post(\n url_for(\"add_order\", id=1),\n data=dict(email=\"[email protected]\"),\n follow_redirects=True,\n )\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual(\"order placed\", order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n def test_add_order_no_user(self):\n response = self.client.post(\n url_for(\"add_order\"), data=dict(email=\"[email protected]\")\n )\n\n\nclass TestViewOrder(TestCase):\n def test_view_order(self):\n response = self.client.get(\n url_for(\"view_order\", id=1),\n data=dict(\n id=\"0006\",\n name=\"Test\",\n house_number=\"8\",\n postode=\"G3 8PX\",\n phone=\"07999999999\",\n ),\n )\n self.assertIn(b\"0001\", response.data)\n self.assertIn(b\"Test\", response.data)\n self.assertIn(b\"8\", response.data)\n self.assertIn(b\"G3 8PX\", response.data)\n self.assertIn(b\"07999999999\", response.data)\n\n\nclass TestUpdateOrder(TestCase):\n def test_update_order(self):\n response = self.client.post(\n url_for(\"update_order\", id=1),\n data=dict(\n status=\"out for delivery\",\n tracking_num_len=8,\n ),\n )\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(\"out for delivery\", order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n def test_delivered(self):\n response = self.client.post(url_for(\"delivered\", id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(\"delivered\", order.order_status)\n\n\nclass TestDelete(TestCase):\n def test_delete(self):\n response = self.client.post(url_for(\"delete\", id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n", "step-ids": [ 20, 27, 32, 33, 34 ] }
[ 20, 27, 32, 33, 34 ]
<|reserved_special_token_0|> class Weapon(Equipment): def __init__(self, name, power): super(Weapon, self).__init__(name) self.power = power <|reserved_special_token_0|> def __str__(self): return '{}: Power({})'.format(self.name, self.power) <|reserved_special_token_1|> <|reserved_special_token_0|> class Weapon(Equipment): def __init__(self, name, power): super(Weapon, self).__init__(name) self.power = power @staticmethod def fromJSON(jsonstr): obj = Equipment.fromJSON(jsonstr) return Weapon(obj['name'], obj['power']) def __str__(self): return '{}: Power({})'.format(self.name, self.power) <|reserved_special_token_1|> __author__ = 'Jager' <|reserved_special_token_0|> class Weapon(Equipment): def __init__(self, name, power): super(Weapon, self).__init__(name) self.power = power @staticmethod def fromJSON(jsonstr): obj = Equipment.fromJSON(jsonstr) return Weapon(obj['name'], obj['power']) def __str__(self): return '{}: Power({})'.format(self.name, self.power) <|reserved_special_token_1|> __author__ = 'Jager' from equipment import Equipment class Weapon(Equipment): def __init__(self, name, power): super(Weapon, self).__init__(name) self.power = power @staticmethod def fromJSON(jsonstr): obj = Equipment.fromJSON(jsonstr) return Weapon(obj['name'], obj['power']) def __str__(self): return '{}: Power({})'.format(self.name, self.power) <|reserved_special_token_1|> __author__ = 'Jager' from equipment import Equipment class Weapon (Equipment): def __init__(self, name, power): super(Weapon, self).__init__(name) self.power = power @staticmethod def fromJSON(jsonstr): obj = Equipment.fromJSON(jsonstr) return Weapon(obj["name"], obj["power"]) def __str__(self): return "{}: Power({})".format(self.name, self.power)
flexible
{ "blob_id": "276d7ac493ddcb327dbce279d9f4bc8a74c98245", "index": 5749, "step-1": "<mask token>\n\n\nclass Weapon(Equipment):\n\n def __init__(self, name, power):\n super(Weapon, self).__init__(name)\n self.power = power\n <mask token>\n\n def __str__(self):\n return '{}: Power({})'.format(self.name, self.power)\n", "step-2": "<mask token>\n\n\nclass Weapon(Equipment):\n\n def __init__(self, name, power):\n super(Weapon, self).__init__(name)\n self.power = power\n\n @staticmethod\n def fromJSON(jsonstr):\n obj = Equipment.fromJSON(jsonstr)\n return Weapon(obj['name'], obj['power'])\n\n def __str__(self):\n return '{}: Power({})'.format(self.name, self.power)\n", "step-3": "__author__ = 'Jager'\n<mask token>\n\n\nclass Weapon(Equipment):\n\n def __init__(self, name, power):\n super(Weapon, self).__init__(name)\n self.power = power\n\n @staticmethod\n def fromJSON(jsonstr):\n obj = Equipment.fromJSON(jsonstr)\n return Weapon(obj['name'], obj['power'])\n\n def __str__(self):\n return '{}: Power({})'.format(self.name, self.power)\n", "step-4": "__author__ = 'Jager'\nfrom equipment import Equipment\n\n\nclass Weapon(Equipment):\n\n def __init__(self, name, power):\n super(Weapon, self).__init__(name)\n self.power = power\n\n @staticmethod\n def fromJSON(jsonstr):\n obj = Equipment.fromJSON(jsonstr)\n return Weapon(obj['name'], obj['power'])\n\n def __str__(self):\n return '{}: Power({})'.format(self.name, self.power)\n", "step-5": "__author__ = 'Jager'\nfrom equipment import Equipment\n\n\nclass Weapon (Equipment):\n def __init__(self, name, power):\n super(Weapon, self).__init__(name)\n self.power = power\n\n @staticmethod\n def fromJSON(jsonstr):\n obj = Equipment.fromJSON(jsonstr)\n return Weapon(obj[\"name\"], obj[\"power\"])\n\n def __str__(self):\n return \"{}: Power({})\".format(self.name, self.power)", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
def solution(citations): # 사이테이션을 정렬 citations.sort() # for i in range(len(citations)): if citations[i] >= len(citations) - i: return len(citations)-i print(solution([3,0,6,1,5]))
normal
{ "blob_id": "0b3d6339faf9d66d4e1338599e4784fac0f63d3f", "index": 5310, "step-1": "<mask token>\n", "step-2": "def solution(citations):\n citations.sort()\n for i in range(len(citations)):\n if citations[i] >= len(citations) - i:\n return len(citations) - i\n\n\n<mask token>\n", "step-3": "def solution(citations):\n citations.sort()\n for i in range(len(citations)):\n if citations[i] >= len(citations) - i:\n return len(citations) - i\n\n\nprint(solution([3, 0, 6, 1, 5]))\n", "step-4": "def solution(citations):\n # 사이테이션을 정렬\n citations.sort()\n # \n for i in range(len(citations)):\n if citations[i] >= len(citations) - i: \n return len(citations)-i \n\n\nprint(solution([3,0,6,1,5]))", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('application', '0003_auto_20190818_1623')] operations = [migrations.AlterField(model_name='user', name='visited', field=models.ManyToManyField(related_name='visitors', to= 'application.EscapeRoom'))] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('application', '0003_auto_20190818_1623')] operations = [migrations.AlterField(model_name='user', name='visited', field=models.ManyToManyField(related_name='visitors', to= 'application.EscapeRoom'))] <|reserved_special_token_1|> # Generated by Django 2.2.4 on 2019-08-19 19:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('application', '0003_auto_20190818_1623'), ] operations = [ migrations.AlterField( model_name='user', name='visited', field=models.ManyToManyField(related_name='visitors', to='application.EscapeRoom'), ), ]
flexible
{ "blob_id": "913e1f5a0af436ef081ab567c44b4149299d0ec6", "index": 3154, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('application', '0003_auto_20190818_1623')]\n operations = [migrations.AlterField(model_name='user', name='visited',\n field=models.ManyToManyField(related_name='visitors', to=\n 'application.EscapeRoom'))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('application', '0003_auto_20190818_1623')]\n operations = [migrations.AlterField(model_name='user', name='visited',\n field=models.ManyToManyField(related_name='visitors', to=\n 'application.EscapeRoom'))]\n", "step-5": "# Generated by Django 2.2.4 on 2019-08-19 19:14\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('application', '0003_auto_20190818_1623'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='visited',\n field=models.ManyToManyField(related_name='visitors', to='application.EscapeRoom'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
def usage_list(self): print('Available modules') print('=================') for module in sorted(self.list()): if ('module' not in self.mods[module]): self.import_module(module) if (not self.mods[module]['module'].__doc__): continue text = self.mods[module]['module'].__doc__.strip('\n ') text = text.split('\n') if (len(text) > 2): if text[1].startswith('='): text[1] = ('=' * (14 + len(text[1]))) text = '\n'.join(text) print(('\n%-12s: %s' % (module, text)))
normal
{ "blob_id": "d0eb6ea2e816ac59ae93684edb38ff3a49909633", "index": 762, "step-1": "<mask token>\n", "step-2": "def usage_list(self):\n print('Available modules')\n print('=================')\n for module in sorted(self.list()):\n if 'module' not in self.mods[module]:\n self.import_module(module)\n if not self.mods[module]['module'].__doc__:\n continue\n text = self.mods[module]['module'].__doc__.strip('\\n ')\n text = text.split('\\n')\n if len(text) > 2:\n if text[1].startswith('='):\n text[1] = '=' * (14 + len(text[1]))\n text = '\\n'.join(text)\n print('\\n%-12s: %s' % (module, text))\n", "step-3": "def usage_list(self):\n print('Available modules')\n print('=================')\n for module in sorted(self.list()):\n if ('module' not in self.mods[module]):\n self.import_module(module)\n if (not self.mods[module]['module'].__doc__):\n continue\n text = self.mods[module]['module'].__doc__.strip('\\n ')\n text = text.split('\\n')\n if (len(text) > 2):\n if text[1].startswith('='):\n text[1] = ('=' * (14 + len(text[1])))\n text = '\\n'.join(text)\n print(('\\n%-12s: %s' % (module, text)))", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from abc import ABCMeta, abstractmethod, ABC from domain.models.network_information import NetworkInformation class AbstractTensorboardExportService(ABC): __metaclass__ = ABCMeta @abstractmethod def save_tensorboard(self, network_info: NetworkInformation) ->None: raise NotImplementedError
normal
{ "blob_id": "08c3155a5fbf6c94f5885c12cfc7c917313ae9c7", "index": 5929, "step-1": "<mask token>\n\n\nclass AbstractTensorboardExportService(ABC):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass AbstractTensorboardExportService(ABC):\n <mask token>\n\n @abstractmethod\n def save_tensorboard(self, network_info: NetworkInformation) ->None:\n raise NotImplementedError\n", "step-3": "<mask token>\n\n\nclass AbstractTensorboardExportService(ABC):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def save_tensorboard(self, network_info: NetworkInformation) ->None:\n raise NotImplementedError\n", "step-4": "from abc import ABCMeta, abstractmethod, ABC\nfrom domain.models.network_information import NetworkInformation\n\n\nclass AbstractTensorboardExportService(ABC):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def save_tensorboard(self, network_info: NetworkInformation) ->None:\n raise NotImplementedError\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
from Common.TreasureIsland import TIenv from .Agent import TIagent import torch feature_size = (8, 8) env = TIenv(frame_rate=0, num_marks=1, feature_size=feature_size) agent = TIagent(feature_size=feature_size, learning_rate=0.0001) EPISODE_COUNT = 50000 STEP_COUNT = 40 for episode in range(EPISODE_COUNT): obs = env.reset() agent.reset() steps = 0 if (episode + 1) % 100 == 0: state = { 'model_state': agent.model.state_dict(), 'optim_state': agent.optim.state_dict() } torch.save(state, "models/" + str(episode+1) + '.pt') env.save_value_and_policy_map_for_A2C(agent.model, 'images/' + str(episode+1) + '.png') while True: env.render() action = agent.action(obs) obs = env.step(action) agent.reward(obs.reward) if obs.done: agent.train(obs) break steps += 1 if steps % STEP_COUNT == 0: agent.train(obs) continue print(str(episode + 1) + ": " + str(agent.episode_reward))
normal
{ "blob_id": "bf133e73f0c842603dbd7cc3a103a2aa95e2236e", "index": 4359, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor episode in range(EPISODE_COUNT):\n obs = env.reset()\n agent.reset()\n steps = 0\n if (episode + 1) % 100 == 0:\n state = {'model_state': agent.model.state_dict(), 'optim_state':\n agent.optim.state_dict()}\n torch.save(state, 'models/' + str(episode + 1) + '.pt')\n env.save_value_and_policy_map_for_A2C(agent.model, 'images/' + str(\n episode + 1) + '.png')\n while True:\n env.render()\n action = agent.action(obs)\n obs = env.step(action)\n agent.reward(obs.reward)\n if obs.done:\n agent.train(obs)\n break\n steps += 1\n if steps % STEP_COUNT == 0:\n agent.train(obs)\n continue\n print(str(episode + 1) + ': ' + str(agent.episode_reward))\n", "step-3": "<mask token>\nfeature_size = 8, 8\nenv = TIenv(frame_rate=0, num_marks=1, feature_size=feature_size)\nagent = TIagent(feature_size=feature_size, learning_rate=0.0001)\nEPISODE_COUNT = 50000\nSTEP_COUNT = 40\nfor episode in range(EPISODE_COUNT):\n obs = env.reset()\n agent.reset()\n steps = 0\n if (episode + 1) % 100 == 0:\n state = {'model_state': agent.model.state_dict(), 'optim_state':\n agent.optim.state_dict()}\n torch.save(state, 'models/' + str(episode + 1) + '.pt')\n env.save_value_and_policy_map_for_A2C(agent.model, 'images/' + str(\n episode + 1) + '.png')\n while True:\n env.render()\n action = agent.action(obs)\n obs = env.step(action)\n agent.reward(obs.reward)\n if obs.done:\n agent.train(obs)\n break\n steps += 1\n if steps % STEP_COUNT == 0:\n agent.train(obs)\n continue\n print(str(episode + 1) + ': ' + str(agent.episode_reward))\n", "step-4": "from Common.TreasureIsland import TIenv\nfrom .Agent import TIagent\nimport torch\nfeature_size = 8, 8\nenv = TIenv(frame_rate=0, num_marks=1, feature_size=feature_size)\nagent = TIagent(feature_size=feature_size, learning_rate=0.0001)\nEPISODE_COUNT = 50000\nSTEP_COUNT = 40\nfor episode in range(EPISODE_COUNT):\n obs = env.reset()\n agent.reset()\n steps = 0\n if (episode + 1) % 100 == 0:\n state = {'model_state': agent.model.state_dict(), 'optim_state':\n agent.optim.state_dict()}\n torch.save(state, 'models/' + str(episode + 1) + '.pt')\n env.save_value_and_policy_map_for_A2C(agent.model, 'images/' + str(\n episode + 1) + '.png')\n while True:\n env.render()\n action = agent.action(obs)\n obs = env.step(action)\n agent.reward(obs.reward)\n if obs.done:\n agent.train(obs)\n break\n steps += 1\n if steps % STEP_COUNT == 0:\n agent.train(obs)\n continue\n print(str(episode + 1) + ': ' + str(agent.episode_reward))\n", "step-5": "from Common.TreasureIsland import TIenv\nfrom .Agent import TIagent\n\nimport torch\n\nfeature_size = (8, 8)\n\nenv = TIenv(frame_rate=0, num_marks=1, feature_size=feature_size)\nagent = TIagent(feature_size=feature_size, learning_rate=0.0001)\n\nEPISODE_COUNT = 50000\nSTEP_COUNT = 40\n\n\nfor episode in range(EPISODE_COUNT):\n\n obs = env.reset()\n agent.reset()\n\n steps = 0\n\n if (episode + 1) % 100 == 0:\n state = {\n 'model_state': agent.model.state_dict(),\n 'optim_state': agent.optim.state_dict()\n }\n\n torch.save(state, \"models/\" + str(episode+1) + '.pt')\n env.save_value_and_policy_map_for_A2C(agent.model, 'images/' + str(episode+1) + '.png')\n\n while True:\n env.render()\n\n action = agent.action(obs)\n obs = env.step(action)\n agent.reward(obs.reward)\n\n if obs.done:\n agent.train(obs)\n break\n\n steps += 1\n if steps % STEP_COUNT == 0:\n agent.train(obs)\n continue\n\n print(str(episode + 1) + \": \" + str(agent.episode_reward))\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('c4c_app', '0006_c4cjob_complete'), ] operations = [ migrations.AlterModelOptions( name='c4cbranch', options={'verbose_name': 'Branch', 'verbose_name_plural': 'Branches'}, ), migrations.AlterModelOptions( name='c4cdonation', options={'verbose_name': 'Donation', 'verbose_name_plural': 'Donations'}, ), migrations.AlterModelOptions( name='c4cevent', options={'verbose_name': 'Event', 'verbose_name_plural': 'Events'}, ), migrations.AlterModelOptions( name='c4cjob', options={'verbose_name': 'Job', 'verbose_name_plural': 'Jobs'}, ), migrations.AlterModelOptions( name='c4cuser', options={'verbose_name': 'C4C User', 'verbose_name_plural': 'C4C Users'}, ), migrations.RemoveField( model_name='c4cbranch', name='officers', ), migrations.AddField( model_name='c4cbranch', name='group', field=models.OneToOneField(related_name='in_branches', default=None, to='auth.Group'), preserve_default=False, ), migrations.AddField( model_name='c4cbranch', name='officers_group', field=models.OneToOneField(related_name='is_branch_officer_of', default=None, to='auth.Group'), preserve_default=False, ), migrations.AddField( model_name='c4cjob', name='offer', field=models.BooleanField(default=False), preserve_default=True, ), migrations.AlterField( model_name='c4cjob', name='duration', field=models.IntegerField(null=True), preserve_default=True, ), ]
normal
{ "blob_id": "30986eb0a6cd82f837dd14fb383529a6a41def9a", "index": 8338, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('auth', '0001_initial'), ('c4c_app',\n '0006_c4cjob_complete')]\n operations = [migrations.AlterModelOptions(name='c4cbranch', options={\n 'verbose_name': 'Branch', 'verbose_name_plural': 'Branches'}),\n migrations.AlterModelOptions(name='c4cdonation', options={\n 'verbose_name': 'Donation', 'verbose_name_plural': 'Donations'}),\n migrations.AlterModelOptions(name='c4cevent', options={\n 'verbose_name': 'Event', 'verbose_name_plural': 'Events'}),\n migrations.AlterModelOptions(name='c4cjob', options={'verbose_name':\n 'Job', 'verbose_name_plural': 'Jobs'}), migrations.\n AlterModelOptions(name='c4cuser', options={'verbose_name':\n 'C4C User', 'verbose_name_plural': 'C4C Users'}), migrations.\n RemoveField(model_name='c4cbranch', name='officers'), migrations.\n AddField(model_name='c4cbranch', name='group', field=models.\n OneToOneField(related_name='in_branches', default=None, to=\n 'auth.Group'), preserve_default=False), migrations.AddField(\n model_name='c4cbranch', name='officers_group', field=models.\n OneToOneField(related_name='is_branch_officer_of', default=None, to\n ='auth.Group'), preserve_default=False), migrations.AddField(\n model_name='c4cjob', name='offer', field=models.BooleanField(\n default=False), preserve_default=True), migrations.AlterField(\n model_name='c4cjob', name='duration', field=models.IntegerField(\n null=True), preserve_default=True)]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [('auth', '0001_initial'), ('c4c_app',\n '0006_c4cjob_complete')]\n operations = [migrations.AlterModelOptions(name='c4cbranch', options={\n 'verbose_name': 'Branch', 'verbose_name_plural': 'Branches'}),\n migrations.AlterModelOptions(name='c4cdonation', options={\n 'verbose_name': 'Donation', 'verbose_name_plural': 'Donations'}),\n migrations.AlterModelOptions(name='c4cevent', options={\n 'verbose_name': 'Event', 'verbose_name_plural': 'Events'}),\n migrations.AlterModelOptions(name='c4cjob', options={'verbose_name':\n 'Job', 'verbose_name_plural': 'Jobs'}), migrations.\n AlterModelOptions(name='c4cuser', options={'verbose_name':\n 'C4C User', 'verbose_name_plural': 'C4C Users'}), migrations.\n RemoveField(model_name='c4cbranch', name='officers'), migrations.\n AddField(model_name='c4cbranch', name='group', field=models.\n OneToOneField(related_name='in_branches', default=None, to=\n 'auth.Group'), preserve_default=False), migrations.AddField(\n model_name='c4cbranch', name='officers_group', field=models.\n OneToOneField(related_name='is_branch_officer_of', default=None, to\n ='auth.Group'), preserve_default=False), migrations.AddField(\n model_name='c4cjob', name='offer', field=models.BooleanField(\n default=False), preserve_default=True), migrations.AlterField(\n model_name='c4cjob', name='duration', field=models.IntegerField(\n null=True), preserve_default=True)]\n", "step-5": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0001_initial'),\n ('c4c_app', '0006_c4cjob_complete'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='c4cbranch',\n options={'verbose_name': 'Branch', 'verbose_name_plural': 'Branches'},\n ),\n migrations.AlterModelOptions(\n name='c4cdonation',\n options={'verbose_name': 'Donation', 'verbose_name_plural': 'Donations'},\n ),\n migrations.AlterModelOptions(\n name='c4cevent',\n options={'verbose_name': 'Event', 'verbose_name_plural': 'Events'},\n ),\n migrations.AlterModelOptions(\n name='c4cjob',\n options={'verbose_name': 'Job', 'verbose_name_plural': 'Jobs'},\n ),\n migrations.AlterModelOptions(\n name='c4cuser',\n options={'verbose_name': 'C4C User', 'verbose_name_plural': 'C4C Users'},\n ),\n migrations.RemoveField(\n model_name='c4cbranch',\n name='officers',\n ),\n migrations.AddField(\n model_name='c4cbranch',\n name='group',\n field=models.OneToOneField(related_name='in_branches', default=None, to='auth.Group'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='c4cbranch',\n name='officers_group',\n field=models.OneToOneField(related_name='is_branch_officer_of', default=None, to='auth.Group'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='c4cjob',\n name='offer',\n field=models.BooleanField(default=False),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='c4cjob',\n name='duration',\n field=models.IntegerField(null=True),\n preserve_default=True,\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import TemplateView, ListView, DetailView, CreateView, DeleteView, UpdateView from .models import PayFor, PayItem from .forms import SignupForm # Create your views here. def signup_func(request): if request.method == 'POST': input_username = request.POST['username'] input_password = request.POST['password'] try: User.objects.get(username=input_username) return render(request, 'registration/signup.html', {'error': 'このユーザーは登録されています'}) except: user = User.objects.create_user(input_username, '', input_password) return redirect('money_easy:login') return render(request, 'registration/signup.html', {}) def login_func(request): if request.method == 'POST': input_username = request.POST['username'] input_password = request.POST['password'] user = authenticate(request, username=input_username, password=input_password) if user is not None: login(request, user) return redirect('money_easy:pay_item_list') else: return render(request, 'registration/login.html', {'error': 'ユーザー名かパスワードが間違っています。もう一度入力してください。'}) else: return render(request, 'registration/login.html') @login_required() def logout_func(request): logout(request) return redirect('money_easy:login') # class SignupView(CreateView): # form_class = SignupForm # success_url = reverse_lazy('home') # template_name = 'registration/signup.html' # # def form_valid(self, form): # # self.objectにsave()されたユーザーオブジェクトを格納 # valid = super().form_valid(form) # login(self.request, self.object) # return valid class IndexView(LoginRequiredMixin, TemplateView): template_name = 'money_easy/index.html' index = IndexView.as_view() class PayForList(LoginRequiredMixin,ListView): template_name = 'money_easy/payfor_list.html' model = PayFor pay_for_list = PayForList.as_view() class PayForDetailView(LoginRequiredMixin, DetailView): template_name = 'money_easy/payfor_detail.html' model = PayFor pay_for_detail = PayForDetailView.as_view() class PayForCreate(LoginRequiredMixin,CreateView): template_name = 'money_easy/payfor_create.html' model = PayFor fields = ('name', 'description') success_url = reverse_lazy('money_easy:pay_item_list') pay_for_create = PayForCreate.as_view() class PayForDelete(LoginRequiredMixin, DeleteView): template_name = 'money_easy/payfor_delete.html' model = PayFor success_url = reverse_lazy('money_easy:pay_for_list') pay_for_delete = PayForDelete.as_view() class PayForUpdate(LoginRequiredMixin, UpdateView): template_name = 'money_easy/payfor_update.html' model = PayFor fields = ('name', 'description') success_url = reverse_lazy('money_easy:pay_for_list') pay_for_update = PayForUpdate.as_view() class PayItemList(LoginRequiredMixin, ListView): template_name = 'money_easy/payitem_list.html' model = PayItem pay_item_list = PayItemList.as_view() class PayForDetailView(LoginRequiredMixin, DetailView): template_name = 'money_easy/payfor_detail.html' model = PayFor payfor_detail = PayForDetailView.as_view() class PayItemDetailView(LoginRequiredMixin, DetailView): template_name = 'money_easy/payitem_detail.html' model = PayItem def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['priority'] = PayItem.get_priority_display() return context pay_item_detail = PayItemDetailView.as_view() class PayItemCreate(LoginRequiredMixin,CreateView): template_name = 'money_easy/payitem_create.html' model = PayItem fields = ('title', 'payfor', 'money', 'rate', 'priority', 'duedate') success_url = reverse_lazy('money_easy:pay_item_list') pay_item_create = PayItemCreate.as_view() class PayItemDelete(LoginRequiredMixin, DeleteView): template_name = 'money_easy/payitem_delete.html' model = PayItem success_url = reverse_lazy('money_easy:pay_item_list') pay_item_delete = PayItemDelete.as_view() class PayItemUpdate(LoginRequiredMixin, UpdateView): template_name = 'money_easy/payitem_update.html' model = PayItem fields = ('title', 'payfor', 'money', 'rate', 'priority', 'duedate') success_url = reverse_lazy('money_easy:pay_item_list') pay_item_update = PayItemUpdate.as_view() # class LoginView(AuthLoginView): # template_name = 'money_easy/login.html' # # # login = LoginView.as_view() # def hello(request): # if request.method == 'GET': # context = { # 'message': 'Hello World', # } # return render(request, 'hello.html',context) # # # class HelloView(View): # def get(self, request, *args, **kwargs): # context = { # 'message': 'Hello World', # } # return render(request,'hello.html',context) # # # hello = HelloView.as_view()
normal
{ "blob_id": "dc9b5fbe082f7cf6cd0a9cb0d1b5a662cf3496f0", "index": 4768, "step-1": "<mask token>\n\n\nclass PayForList(LoginRequiredMixin, ListView):\n <mask token>\n <mask token>\n\n\n<mask token>\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayForCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payfor_create.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayForDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payfor_delete.html'\n model = PayFor\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\n<mask token>\n\n\nclass PayForUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payfor_update.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\n<mask token>\n\n\nclass PayItemList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payitem_list.html'\n model = PayItem\n\n\n<mask token>\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayItemDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payitem_detail.html'\n model = PayItem\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\n<mask token>\n\n\nclass PayItemCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payitem_create.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayItemDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payitem_delete.html'\n model = PayItem\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayItemUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payitem_update.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass PayForList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payfor_list.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayForCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payfor_create.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayForDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payfor_delete.html'\n model = PayFor\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\n<mask token>\n\n\nclass PayForUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payfor_update.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\n<mask token>\n\n\nclass PayItemList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payitem_list.html'\n model = PayItem\n\n\n<mask token>\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayItemDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payitem_detail.html'\n model = PayItem\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\n<mask token>\n\n\nclass PayItemCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payitem_create.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayItemDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payitem_delete.html'\n model = PayItem\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayItemUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payitem_update.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef signup_func(request):\n if request.method == 'POST':\n input_username = request.POST['username']\n input_password = request.POST['password']\n try:\n User.objects.get(username=input_username)\n return render(request, 'registration/signup.html', {'error':\n 'このユーザーは登録されています'})\n except:\n user = User.objects.create_user(input_username, '', input_password)\n return redirect('money_easy:login')\n return render(request, 'registration/signup.html', {})\n\n\ndef login_func(request):\n if request.method == 'POST':\n input_username = request.POST['username']\n input_password = request.POST['password']\n user = authenticate(request, username=input_username, password=\n input_password)\n if user is not None:\n login(request, user)\n return redirect('money_easy:pay_item_list')\n else:\n return render(request, 'registration/login.html', {'error':\n 'ユーザー名かパスワードが間違っています。もう一度入力してください。'})\n else:\n return render(request, 'registration/login.html')\n\n\n@login_required()\ndef logout_func(request):\n logout(request)\n return redirect('money_easy:login')\n\n\nclass IndexView(LoginRequiredMixin, TemplateView):\n template_name = 'money_easy/index.html'\n\n\n<mask token>\n\n\nclass PayForList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payfor_list.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayForCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payfor_create.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayForDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payfor_delete.html'\n model = PayFor\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\n<mask token>\n\n\nclass PayForUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payfor_update.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\n<mask token>\n\n\nclass PayItemList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payitem_list.html'\n model = PayItem\n\n\n<mask token>\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\n<mask token>\n\n\nclass PayItemDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payitem_detail.html'\n model = PayItem\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\n<mask token>\n\n\nclass PayItemCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payitem_create.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayItemDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payitem_delete.html'\n model = PayItem\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n\n\nclass PayItemUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payitem_update.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef signup_func(request):\n if request.method == 'POST':\n input_username = request.POST['username']\n input_password = request.POST['password']\n try:\n User.objects.get(username=input_username)\n return render(request, 'registration/signup.html', {'error':\n 'このユーザーは登録されています'})\n except:\n user = User.objects.create_user(input_username, '', input_password)\n return redirect('money_easy:login')\n return render(request, 'registration/signup.html', {})\n\n\ndef login_func(request):\n if request.method == 'POST':\n input_username = request.POST['username']\n input_password = request.POST['password']\n user = authenticate(request, username=input_username, password=\n input_password)\n if user is not None:\n login(request, user)\n return redirect('money_easy:pay_item_list')\n else:\n return render(request, 'registration/login.html', {'error':\n 'ユーザー名かパスワードが間違っています。もう一度入力してください。'})\n else:\n return render(request, 'registration/login.html')\n\n\n@login_required()\ndef logout_func(request):\n logout(request)\n return redirect('money_easy:login')\n\n\nclass IndexView(LoginRequiredMixin, TemplateView):\n template_name = 'money_easy/index.html'\n\n\nindex = IndexView.as_view()\n\n\nclass PayForList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payfor_list.html'\n model = PayFor\n\n\npay_for_list = PayForList.as_view()\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\npay_for_detail = PayForDetailView.as_view()\n\n\nclass PayForCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payfor_create.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_for_create = PayForCreate.as_view()\n\n\nclass PayForDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payfor_delete.html'\n model = PayFor\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\npay_for_delete = PayForDelete.as_view()\n\n\nclass PayForUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payfor_update.html'\n model = PayFor\n fields = 'name', 'description'\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\npay_for_update = PayForUpdate.as_view()\n\n\nclass PayItemList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payitem_list.html'\n model = PayItem\n\n\npay_item_list = PayItemList.as_view()\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n model = PayFor\n\n\npayfor_detail = PayForDetailView.as_view()\n\n\nclass PayItemDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payitem_detail.html'\n model = PayItem\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\npay_item_detail = PayItemDetailView.as_view()\n\n\nclass PayItemCreate(LoginRequiredMixin, CreateView):\n template_name = 'money_easy/payitem_create.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_item_create = PayItemCreate.as_view()\n\n\nclass PayItemDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payitem_delete.html'\n model = PayItem\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_item_delete = PayItemDelete.as_view()\n\n\nclass PayItemUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payitem_update.html'\n model = PayItem\n fields = 'title', 'payfor', 'money', 'rate', 'priority', 'duedate'\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_item_update = PayItemUpdate.as_view()\n", "step-5": "from django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic import TemplateView, ListView, DetailView, CreateView, DeleteView, UpdateView\n\nfrom .models import PayFor, PayItem\nfrom .forms import SignupForm\n\n\n# Create your views here.\n\n\ndef signup_func(request):\n if request.method == 'POST':\n input_username = request.POST['username']\n input_password = request.POST['password']\n try:\n User.objects.get(username=input_username)\n return render(request, 'registration/signup.html', {'error': 'このユーザーは登録されています'})\n except:\n user = User.objects.create_user(input_username, '', input_password)\n return redirect('money_easy:login')\n return render(request, 'registration/signup.html', {})\n\n\ndef login_func(request):\n if request.method == 'POST':\n input_username = request.POST['username']\n input_password = request.POST['password']\n user = authenticate(request, username=input_username, password=input_password)\n if user is not None:\n login(request, user)\n return redirect('money_easy:pay_item_list')\n else:\n return render(request, 'registration/login.html', {'error': 'ユーザー名かパスワードが間違っています。もう一度入力してください。'})\n else:\n return render(request, 'registration/login.html')\n\n\n@login_required()\ndef logout_func(request):\n logout(request)\n return redirect('money_easy:login')\n\n\n\n# class SignupView(CreateView):\n# form_class = SignupForm\n# success_url = reverse_lazy('home')\n# template_name = 'registration/signup.html'\n#\n# def form_valid(self, form):\n# # self.objectにsave()されたユーザーオブジェクトを格納\n# valid = super().form_valid(form)\n# login(self.request, self.object)\n# return valid\n\n\nclass IndexView(LoginRequiredMixin, TemplateView):\n template_name = 'money_easy/index.html'\n\n\nindex = IndexView.as_view()\n\n\nclass PayForList(LoginRequiredMixin,ListView):\n template_name = 'money_easy/payfor_list.html'\n\n model = PayFor\n\n\npay_for_list = PayForList.as_view()\n\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n\n model = PayFor\n\n\npay_for_detail = PayForDetailView.as_view()\n\n\nclass PayForCreate(LoginRequiredMixin,CreateView):\n template_name = 'money_easy/payfor_create.html'\n\n model = PayFor\n\n fields = ('name', 'description')\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_for_create = PayForCreate.as_view()\n\n\nclass PayForDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payfor_delete.html'\n\n model = PayFor\n\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\npay_for_delete = PayForDelete.as_view()\n\n\nclass PayForUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payfor_update.html'\n\n model = PayFor\n\n fields = ('name', 'description')\n\n success_url = reverse_lazy('money_easy:pay_for_list')\n\n\npay_for_update = PayForUpdate.as_view()\n\n\n\nclass PayItemList(LoginRequiredMixin, ListView):\n template_name = 'money_easy/payitem_list.html'\n\n model = PayItem\n\n\npay_item_list = PayItemList.as_view()\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.html'\n\n model = PayFor\n\n\npayfor_detail = PayForDetailView.as_view()\n\n\nclass PayItemDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payitem_detail.html'\n\n model = PayItem\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n # context['priority'] = PayItem.get_priority_display()\n return context\n\n\npay_item_detail = PayItemDetailView.as_view()\n\n\nclass PayItemCreate(LoginRequiredMixin,CreateView):\n template_name = 'money_easy/payitem_create.html'\n\n model = PayItem\n\n fields = ('title', 'payfor', 'money', 'rate', 'priority', 'duedate')\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_item_create = PayItemCreate.as_view()\n\n\nclass PayItemDelete(LoginRequiredMixin, DeleteView):\n template_name = 'money_easy/payitem_delete.html'\n\n model = PayItem\n\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_item_delete = PayItemDelete.as_view()\n\n\nclass PayItemUpdate(LoginRequiredMixin, UpdateView):\n template_name = 'money_easy/payitem_update.html'\n\n model = PayItem\n\n fields = ('title', 'payfor', 'money', 'rate', 'priority', 'duedate')\n\n success_url = reverse_lazy('money_easy:pay_item_list')\n\n\npay_item_update = PayItemUpdate.as_view()\n\n# class LoginView(AuthLoginView):\n# template_name = 'money_easy/login.html'\n#\n#\n# login = LoginView.as_view()\n\n# def hello(request):\n# if request.method == 'GET':\n# context = {\n# 'message': 'Hello World',\n# }\n# return render(request, 'hello.html',context)\n#\n#\n# class HelloView(View):\n# def get(self, request, *args, **kwargs):\n# context = {\n# 'message': 'Hello World',\n# }\n# return render(request,'hello.html',context)\n#\n#\n# hello = HelloView.as_view()\n", "step-ids": [ 22, 23, 28, 29, 31 ] }
[ 22, 23, 28, 29, 31 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for i in word: if 'a' <= i and i <= 'z' or 'A' <= i and i <= 'Z': letter += 1 if '0' <= i and i <= '9': digit += 1 print("""LETTERS {0} DIGITS {1}""".format(letter, digit)) <|reserved_special_token_1|> word = input() letter, digit = 0, 0 for i in word: if 'a' <= i and i <= 'z' or 'A' <= i and i <= 'Z': letter += 1 if '0' <= i and i <= '9': digit += 1 print("""LETTERS {0} DIGITS {1}""".format(letter, digit)) <|reserved_special_token_1|> word=input() letter,digit=0,0 for i in word: if('a'<=i and i<='z') or ('A'<=i and i<='Z'): letter+=1 if '0'<=i and i<='9': digit+=1 print("LETTERS {0} \n DIGITS {1}".format(letter,digit))
flexible
{ "blob_id": "f2a508ae99697d6ba320b158a1000379b975d568", "index": 2227, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in word:\n if 'a' <= i and i <= 'z' or 'A' <= i and i <= 'Z':\n letter += 1\n if '0' <= i and i <= '9':\n digit += 1\nprint(\"\"\"LETTERS {0} \n DIGITS {1}\"\"\".format(letter, digit))\n", "step-3": "word = input()\nletter, digit = 0, 0\nfor i in word:\n if 'a' <= i and i <= 'z' or 'A' <= i and i <= 'Z':\n letter += 1\n if '0' <= i and i <= '9':\n digit += 1\nprint(\"\"\"LETTERS {0} \n DIGITS {1}\"\"\".format(letter, digit))\n", "step-4": "word=input()\nletter,digit=0,0\n\nfor i in word:\n if('a'<=i and i<='z') or ('A'<=i and i<='Z'):\n letter+=1\n if '0'<=i and i<='9':\n digit+=1\n\nprint(\"LETTERS {0} \\n DIGITS {1}\".format(letter,digit))\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
l={1,2,3,4} try: print(l) s=len(l) if s>5: raise TypeError print(d[2]) except TypeError: print("Error!!!length should be less than or equals to 5") except NameError: print("index out of range") else: for i in l: print(i) finally: print("execution done!!!!!!")
normal
{ "blob_id": "e59e60b0a4b7deca9c510bd6b9c58636c6d34c80", "index": 1027, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n print(l)\n s = len(l)\n if s > 5:\n raise TypeError\n print(d[2])\nexcept TypeError:\n print('Error!!!length should be less than or equals to 5')\nexcept NameError:\n print('index out of range')\nelse:\n for i in l:\n print(i)\nfinally:\n print('execution done!!!!!!')\n", "step-3": "l = {1, 2, 3, 4}\ntry:\n print(l)\n s = len(l)\n if s > 5:\n raise TypeError\n print(d[2])\nexcept TypeError:\n print('Error!!!length should be less than or equals to 5')\nexcept NameError:\n print('index out of range')\nelse:\n for i in l:\n print(i)\nfinally:\n print('execution done!!!!!!')\n", "step-4": "\nl={1,2,3,4}\ntry:\n\tprint(l)\n\ts=len(l)\n\tif s>5:\n\t\traise TypeError\n\tprint(d[2])\n\nexcept TypeError:\n\tprint(\"Error!!!length should be less than or equals to 5\")\nexcept NameError:\n\tprint(\"index out of range\")\nelse:\n\tfor i in l:\n\t\tprint(i)\nfinally:\n\tprint(\"execution done!!!!!!\")", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import tkinter as tk from functools import partial from numpy import random from base import NinePalaceGame class SingleMode(NinePalaceGame): player1 = player = 'O' player2 = computer = 'X' def __init__(self): self.create_choose_one_window() super().__init__() self.main_game_window.mainloop() def player_play(self, i, j): if not self.game_is_over and not self.box[i][j]: self.box[i][j] = 1 self.value_group[i][j].set(self.dominance) self.dominance = self.computer return 1 return 0 def computer_play(self): if not self.game_is_over: while 1: i, j = random.choice(range(3)), random.choice(range(3)) if not self.box[i][j]: self.box[i][j] = 1 self.value_group[i][j].set(self.computer) self.dominance = self.player break def judge(self): if self.check_win(self.player): self.game_is_over = 1 self.billboard_value.set('Player is win!') elif self.check_win(self.computer): self.game_is_over = 1 self.billboard_value.set('Computer is win!') elif self.check_game_over(): self.game_is_over = 1 self.billboard_value.set('Game over!') def reset(self): super().reset() self.dominance = self.player self.box = [ [0, 0, 0], [0, 0, 0], [0, 0, 0]] self.main_game_window.withdraw() self.choose_one_window.update() self.choose_one_window.deiconify() def button_function(self, i, j): if self.player_play(i, j): self.judge() self.computer_play() self.judge() def set_O_or_X(self, use): self.player = use if use == 'X': self.computer = 'O' self.computer_play() else: self.computer = 'X' self.dominance = self.player self.choose_one_window.withdraw() self.main_game_window.update() self.main_game_window.deiconify() def create_choose_one_window(self): self.choose_one_window = tk.Toplevel(self.main_game_window) self.choose_one_window.title('choose one window') self.choose_one_window.geometry('500x500') choose_one_window_billboard = tk.StringVar( master=self.choose_one_window, value='Choose you want') use_O_or_X = tk.Label(self.choose_one_window, bg='yellow', width=50, height=5, textvariable=choose_one_window_billboard) use_O_or_X.pack() use_O = tk.Button(self.choose_one_window, text='I want use O', width=40, height=5, command=partial(self.set_O_or_X, 'O')) use_O.pack() use_X = tk.Button(self.choose_one_window, text='I want use X', width=40, height=5, command=partial(self.set_O_or_X, 'X')) use_X.pack() if __name__ == '__main__': game = SingleMode()
normal
{ "blob_id": "841743d4e9d683827962d83a77a87c6432842add", "index": 8013, "step-1": "<mask token>\n\n\nclass SingleMode(NinePalaceGame):\n <mask token>\n <mask token>\n <mask token>\n\n def player_play(self, i, j):\n if not self.game_is_over and not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.dominance)\n self.dominance = self.computer\n return 1\n return 0\n\n def computer_play(self):\n if not self.game_is_over:\n while 1:\n i, j = random.choice(range(3)), random.choice(range(3))\n if not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.computer)\n self.dominance = self.player\n break\n <mask token>\n\n def reset(self):\n super().reset()\n self.dominance = self.player\n self.box = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n self.main_game_window.withdraw()\n self.choose_one_window.update()\n self.choose_one_window.deiconify()\n\n def button_function(self, i, j):\n if self.player_play(i, j):\n self.judge()\n self.computer_play()\n self.judge()\n <mask token>\n\n def create_choose_one_window(self):\n self.choose_one_window = tk.Toplevel(self.main_game_window)\n self.choose_one_window.title('choose one window')\n self.choose_one_window.geometry('500x500')\n choose_one_window_billboard = tk.StringVar(master=self.\n choose_one_window, value='Choose you want')\n use_O_or_X = tk.Label(self.choose_one_window, bg='yellow', width=50,\n height=5, textvariable=choose_one_window_billboard)\n use_O_or_X.pack()\n use_O = tk.Button(self.choose_one_window, text='I want use O',\n width=40, height=5, command=partial(self.set_O_or_X, 'O'))\n use_O.pack()\n use_X = tk.Button(self.choose_one_window, text='I want use X',\n width=40, height=5, command=partial(self.set_O_or_X, 'X'))\n use_X.pack()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass SingleMode(NinePalaceGame):\n <mask token>\n <mask token>\n <mask token>\n\n def player_play(self, i, j):\n if not self.game_is_over and not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.dominance)\n self.dominance = self.computer\n return 1\n return 0\n\n def computer_play(self):\n if not self.game_is_over:\n while 1:\n i, j = random.choice(range(3)), random.choice(range(3))\n if not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.computer)\n self.dominance = self.player\n break\n <mask token>\n\n def reset(self):\n super().reset()\n self.dominance = self.player\n self.box = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n self.main_game_window.withdraw()\n self.choose_one_window.update()\n self.choose_one_window.deiconify()\n\n def button_function(self, i, j):\n if self.player_play(i, j):\n self.judge()\n self.computer_play()\n self.judge()\n\n def set_O_or_X(self, use):\n self.player = use\n if use == 'X':\n self.computer = 'O'\n self.computer_play()\n else:\n self.computer = 'X'\n self.dominance = self.player\n self.choose_one_window.withdraw()\n self.main_game_window.update()\n self.main_game_window.deiconify()\n\n def create_choose_one_window(self):\n self.choose_one_window = tk.Toplevel(self.main_game_window)\n self.choose_one_window.title('choose one window')\n self.choose_one_window.geometry('500x500')\n choose_one_window_billboard = tk.StringVar(master=self.\n choose_one_window, value='Choose you want')\n use_O_or_X = tk.Label(self.choose_one_window, bg='yellow', width=50,\n height=5, textvariable=choose_one_window_billboard)\n use_O_or_X.pack()\n use_O = tk.Button(self.choose_one_window, text='I want use O',\n width=40, height=5, command=partial(self.set_O_or_X, 'O'))\n use_O.pack()\n use_X = tk.Button(self.choose_one_window, text='I want use X',\n width=40, height=5, command=partial(self.set_O_or_X, 'X'))\n use_X.pack()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass SingleMode(NinePalaceGame):\n <mask token>\n <mask token>\n\n def __init__(self):\n self.create_choose_one_window()\n super().__init__()\n self.main_game_window.mainloop()\n\n def player_play(self, i, j):\n if not self.game_is_over and not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.dominance)\n self.dominance = self.computer\n return 1\n return 0\n\n def computer_play(self):\n if not self.game_is_over:\n while 1:\n i, j = random.choice(range(3)), random.choice(range(3))\n if not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.computer)\n self.dominance = self.player\n break\n\n def judge(self):\n if self.check_win(self.player):\n self.game_is_over = 1\n self.billboard_value.set('Player is win!')\n elif self.check_win(self.computer):\n self.game_is_over = 1\n self.billboard_value.set('Computer is win!')\n elif self.check_game_over():\n self.game_is_over = 1\n self.billboard_value.set('Game over!')\n\n def reset(self):\n super().reset()\n self.dominance = self.player\n self.box = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n self.main_game_window.withdraw()\n self.choose_one_window.update()\n self.choose_one_window.deiconify()\n\n def button_function(self, i, j):\n if self.player_play(i, j):\n self.judge()\n self.computer_play()\n self.judge()\n\n def set_O_or_X(self, use):\n self.player = use\n if use == 'X':\n self.computer = 'O'\n self.computer_play()\n else:\n self.computer = 'X'\n self.dominance = self.player\n self.choose_one_window.withdraw()\n self.main_game_window.update()\n self.main_game_window.deiconify()\n\n def create_choose_one_window(self):\n self.choose_one_window = tk.Toplevel(self.main_game_window)\n self.choose_one_window.title('choose one window')\n self.choose_one_window.geometry('500x500')\n choose_one_window_billboard = tk.StringVar(master=self.\n choose_one_window, value='Choose you want')\n use_O_or_X = tk.Label(self.choose_one_window, bg='yellow', width=50,\n height=5, textvariable=choose_one_window_billboard)\n use_O_or_X.pack()\n use_O = tk.Button(self.choose_one_window, text='I want use O',\n width=40, height=5, command=partial(self.set_O_or_X, 'O'))\n use_O.pack()\n use_X = tk.Button(self.choose_one_window, text='I want use X',\n width=40, height=5, command=partial(self.set_O_or_X, 'X'))\n use_X.pack()\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass SingleMode(NinePalaceGame):\n player1 = player = 'O'\n player2 = computer = 'X'\n\n def __init__(self):\n self.create_choose_one_window()\n super().__init__()\n self.main_game_window.mainloop()\n\n def player_play(self, i, j):\n if not self.game_is_over and not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.dominance)\n self.dominance = self.computer\n return 1\n return 0\n\n def computer_play(self):\n if not self.game_is_over:\n while 1:\n i, j = random.choice(range(3)), random.choice(range(3))\n if not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.computer)\n self.dominance = self.player\n break\n\n def judge(self):\n if self.check_win(self.player):\n self.game_is_over = 1\n self.billboard_value.set('Player is win!')\n elif self.check_win(self.computer):\n self.game_is_over = 1\n self.billboard_value.set('Computer is win!')\n elif self.check_game_over():\n self.game_is_over = 1\n self.billboard_value.set('Game over!')\n\n def reset(self):\n super().reset()\n self.dominance = self.player\n self.box = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n self.main_game_window.withdraw()\n self.choose_one_window.update()\n self.choose_one_window.deiconify()\n\n def button_function(self, i, j):\n if self.player_play(i, j):\n self.judge()\n self.computer_play()\n self.judge()\n\n def set_O_or_X(self, use):\n self.player = use\n if use == 'X':\n self.computer = 'O'\n self.computer_play()\n else:\n self.computer = 'X'\n self.dominance = self.player\n self.choose_one_window.withdraw()\n self.main_game_window.update()\n self.main_game_window.deiconify()\n\n def create_choose_one_window(self):\n self.choose_one_window = tk.Toplevel(self.main_game_window)\n self.choose_one_window.title('choose one window')\n self.choose_one_window.geometry('500x500')\n choose_one_window_billboard = tk.StringVar(master=self.\n choose_one_window, value='Choose you want')\n use_O_or_X = tk.Label(self.choose_one_window, bg='yellow', width=50,\n height=5, textvariable=choose_one_window_billboard)\n use_O_or_X.pack()\n use_O = tk.Button(self.choose_one_window, text='I want use O',\n width=40, height=5, command=partial(self.set_O_or_X, 'O'))\n use_O.pack()\n use_X = tk.Button(self.choose_one_window, text='I want use X',\n width=40, height=5, command=partial(self.set_O_or_X, 'X'))\n use_X.pack()\n\n\nif __name__ == '__main__':\n game = SingleMode()\n", "step-5": "import tkinter as tk\nfrom functools import partial\nfrom numpy import random\nfrom base import NinePalaceGame\n\n\nclass SingleMode(NinePalaceGame):\n player1 = player = 'O'\n player2 = computer = 'X'\n\n def __init__(self):\n self.create_choose_one_window()\n super().__init__()\n\n self.main_game_window.mainloop()\n\n def player_play(self, i, j):\n if not self.game_is_over and not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.dominance)\n self.dominance = self.computer\n return 1\n return 0\n\n def computer_play(self):\n if not self.game_is_over:\n while 1:\n i, j = random.choice(range(3)), random.choice(range(3))\n if not self.box[i][j]:\n self.box[i][j] = 1\n self.value_group[i][j].set(self.computer)\n self.dominance = self.player\n break\n\n def judge(self):\n if self.check_win(self.player):\n self.game_is_over = 1\n self.billboard_value.set('Player is win!')\n elif self.check_win(self.computer):\n self.game_is_over = 1\n self.billboard_value.set('Computer is win!')\n elif self.check_game_over():\n self.game_is_over = 1\n self.billboard_value.set('Game over!')\n\n def reset(self):\n super().reset()\n self.dominance = self.player\n self.box = [\n [0, 0, 0], [0, 0, 0], [0, 0, 0]]\n\n self.main_game_window.withdraw()\n self.choose_one_window.update()\n self.choose_one_window.deiconify()\n\n def button_function(self, i, j):\n if self.player_play(i, j):\n self.judge()\n self.computer_play()\n self.judge()\n\n def set_O_or_X(self, use):\n self.player = use\n if use == 'X':\n self.computer = 'O'\n self.computer_play()\n else:\n self.computer = 'X'\n self.dominance = self.player\n self.choose_one_window.withdraw()\n self.main_game_window.update()\n self.main_game_window.deiconify()\n\n def create_choose_one_window(self):\n self.choose_one_window = tk.Toplevel(self.main_game_window)\n self.choose_one_window.title('choose one window')\n self.choose_one_window.geometry('500x500')\n\n choose_one_window_billboard = tk.StringVar(\n master=self.choose_one_window, value='Choose you want')\n use_O_or_X = tk.Label(self.choose_one_window, bg='yellow', width=50,\n height=5, textvariable=choose_one_window_billboard)\n use_O_or_X.pack()\n\n use_O = tk.Button(self.choose_one_window, text='I want use O', width=40,\n height=5, command=partial(self.set_O_or_X, 'O'))\n use_O.pack()\n use_X = tk.Button(self.choose_one_window, text='I want use X', width=40,\n height=5, command=partial(self.set_O_or_X, 'X'))\n use_X.pack()\n\n\nif __name__ == '__main__':\n game = SingleMode()\n", "step-ids": [ 6, 7, 9, 11, 13 ] }
[ 6, 7, 9, 11, 13 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> app_name = 'genius' urlpatterns = [path('', home, name='home'), path('class/', Classes, name= 'class'), path('class/add-name', Add_name, name='add-name'), path( 'class/create', Class_create, name='create-class'), path( 'class/<int:id>', Class_Detail, name='detail'), path( 'class/<int:id>/edit/', Class_Update, name='update'), path( 'class/<int:id>/delete/', Class_Delete, name='delete'), path('stds/', Student_Main, name='stds'), path('stds/create', Student_Create, name= 'stds-new'), path('stds/<int:id>', Student_Detail, name='std-detail'), path('stds/search/', Search, name='std-search'), path( 'stds/<int:id>/edit/', Student_Update, name='std-update'), path( 'stds/<int:id>/delete/', Student_Delete, name='std-delete')] <|reserved_special_token_1|> from django import urls from django.urls import path from genius.views import home, Class_create, Class_Update, Class_Delete, Class_Detail, Classes, Add_name, Student_Main, Student_Create, Student_Update, Student_Delete, Student_Detail, Search app_name = 'genius' urlpatterns = [path('', home, name='home'), path('class/', Classes, name= 'class'), path('class/add-name', Add_name, name='add-name'), path( 'class/create', Class_create, name='create-class'), path( 'class/<int:id>', Class_Detail, name='detail'), path( 'class/<int:id>/edit/', Class_Update, name='update'), path( 'class/<int:id>/delete/', Class_Delete, name='delete'), path('stds/', Student_Main, name='stds'), path('stds/create', Student_Create, name= 'stds-new'), path('stds/<int:id>', Student_Detail, name='std-detail'), path('stds/search/', Search, name='std-search'), path( 'stds/<int:id>/edit/', Student_Update, name='std-update'), path( 'stds/<int:id>/delete/', Student_Delete, name='std-delete')] <|reserved_special_token_1|> from django import urls from django.urls import path from genius.views import (home, Class_create, Class_Update, Class_Delete, Class_Detail, Classes, Add_name, Student_Main, Student_Create, Student_Update, Student_Delete, Student_Detail, Search) app_name = 'genius' urlpatterns = [ path('', home, name='home'), path('class/', Classes, name='class'), path('class/add-name', Add_name, name='add-name'), path('class/create', Class_create, name='create-class'), path('class/<int:id>', Class_Detail, name='detail'), path('class/<int:id>/edit/', Class_Update, name='update'), path('class/<int:id>/delete/', Class_Delete, name='delete'), path('stds/', Student_Main, name='stds'), path('stds/create', Student_Create, name='stds-new'), path('stds/<int:id>',Student_Detail , name='std-detail'), path('stds/search/',Search , name='std-search'), path('stds/<int:id>/edit/', Student_Update, name='std-update'), path('stds/<int:id>/delete/', Student_Delete, name='std-delete'), ]
flexible
{ "blob_id": "fd6a32652b845b2a6d6d8934c0dde91afdddd9f3", "index": 9046, "step-1": "<mask token>\n", "step-2": "<mask token>\napp_name = 'genius'\nurlpatterns = [path('', home, name='home'), path('class/', Classes, name=\n 'class'), path('class/add-name', Add_name, name='add-name'), path(\n 'class/create', Class_create, name='create-class'), path(\n 'class/<int:id>', Class_Detail, name='detail'), path(\n 'class/<int:id>/edit/', Class_Update, name='update'), path(\n 'class/<int:id>/delete/', Class_Delete, name='delete'), path('stds/',\n Student_Main, name='stds'), path('stds/create', Student_Create, name=\n 'stds-new'), path('stds/<int:id>', Student_Detail, name='std-detail'),\n path('stds/search/', Search, name='std-search'), path(\n 'stds/<int:id>/edit/', Student_Update, name='std-update'), path(\n 'stds/<int:id>/delete/', Student_Delete, name='std-delete')]\n", "step-3": "from django import urls\nfrom django.urls import path\nfrom genius.views import home, Class_create, Class_Update, Class_Delete, Class_Detail, Classes, Add_name, Student_Main, Student_Create, Student_Update, Student_Delete, Student_Detail, Search\napp_name = 'genius'\nurlpatterns = [path('', home, name='home'), path('class/', Classes, name=\n 'class'), path('class/add-name', Add_name, name='add-name'), path(\n 'class/create', Class_create, name='create-class'), path(\n 'class/<int:id>', Class_Detail, name='detail'), path(\n 'class/<int:id>/edit/', Class_Update, name='update'), path(\n 'class/<int:id>/delete/', Class_Delete, name='delete'), path('stds/',\n Student_Main, name='stds'), path('stds/create', Student_Create, name=\n 'stds-new'), path('stds/<int:id>', Student_Detail, name='std-detail'),\n path('stds/search/', Search, name='std-search'), path(\n 'stds/<int:id>/edit/', Student_Update, name='std-update'), path(\n 'stds/<int:id>/delete/', Student_Delete, name='std-delete')]\n", "step-4": "from django import urls\nfrom django.urls import path\nfrom genius.views import (home, Class_create, Class_Update, Class_Delete, Class_Detail, Classes, Add_name,\n Student_Main, Student_Create, Student_Update, Student_Delete, Student_Detail, Search)\n\napp_name = 'genius'\n\nurlpatterns = [\n path('', home, name='home'),\n path('class/', Classes, name='class'),\n path('class/add-name', Add_name, name='add-name'),\n path('class/create', Class_create, name='create-class'),\n path('class/<int:id>', Class_Detail, name='detail'),\n path('class/<int:id>/edit/', Class_Update, name='update'),\n path('class/<int:id>/delete/', Class_Delete, name='delete'),\n path('stds/', Student_Main, name='stds'),\n path('stds/create', Student_Create, name='stds-new'),\n path('stds/<int:id>',Student_Detail , name='std-detail'),\n path('stds/search/',Search , name='std-search'),\n path('stds/<int:id>/edit/', Student_Update, name='std-update'),\n path('stds/<int:id>/delete/', Student_Delete, name='std-delete'),\n]\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from django.db import models from django.utils import timezone from django.contrib.auth.models import User """ Using the django shell: $ python manage.py shell from django.contrib.auth.models import User from accounts.models import Profile from papers.models import Paper, Comment, Rating, UserSavedPaper users = User.objects.all() profiles = Profile.objects.all() papers = Paper.objects.all() comments = Comment.objects.all() ratings = Rating.objects.all() usps = UserSavedPaper.objects.all() comments.create(text='this is an awesome paper!', profile=profiles[0], paper=papers[0]) """ # Reversing migrations # https://docs.djangoproject.com/en/3.0/topics/migrations/#reversing-migrations # - Ex) $ python manage.py migrate papers zero <- reverses all migrations for app "papers", see all migrations with "$ python manage.py showmigrations" # -> python manage.py makemigrations -> python manage.py migrate # https://docs.djangoproject.com/en/3.0/ref/models/fields/ class Paper(models.Model): title = models.CharField(max_length=200) # About data storage space when specifying a max_length: https://stackoverflow.com/questions/30663791/do-setting-the-max-length-to-a-very-large-value-consume-extra-space authors = models.CharField(max_length=200) abstract = models.CharField(max_length=2000, blank=True) journal = models.CharField(max_length=80, blank=True) date_published = models.DateField(blank=True) # https://www.django-rest-framework.org/api-guide/fields/#datefield doi = models.CharField(max_length=32, blank=True) pdflink = models.CharField(max_length=80, blank=True) avg_rating = models.FloatField(default=0) num_ratings = models.PositiveIntegerField(default=0) # Useful example for many-to-many in django: https://www.revsys.com/tidbits/tips-using-djangos-manytomanyfield/ # - TO DO: Get rid of these fields below in the Paper model? The Comment/Rating/UserSavedPaper tables can exist without them being here!? commented_by_users = models.ManyToManyField( 'accounts.Profile', related_name='comments_made', through='Comment', blank=True ) rated_by_users = models.ManyToManyField( 'accounts.Profile', related_name='ratings_given', through='Rating', blank=True ) saved_by_users = models.ManyToManyField( 'accounts.Profile', related_name="papers_saved", through='UserSavedPaper', blank=True ) def __str__(self): return self.title # Custom "through" models: https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ManyToManyField.through_fields class Comment(models.Model): text = models.CharField(max_length=500) #rating = models.PositiveIntegerField(blank=True) # should rating be given simultaneously with posting a comment? time = models.DateTimeField(default=timezone.now) # - TO DO: Look into and decide format for the timestamping profile = models.ForeignKey('accounts.Profile', related_name='comments', on_delete=models.CASCADE) paper = models.ForeignKey('Paper', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.text # No support for composite primary key, e.g. (profile_id, paper_id) in django? https://stackoverflow.com/questions/15440593/tell-djangos-model-to-use-as-primary-key-a-set-of-foreign-keys # - https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys # - possible to enforce it using SQL commands, using something other than the Django ORM, e.g. SQLAlchemy) # - there are validators that can be used with a Serializer to enforce "unique together" - https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator class Rating(models.Model): rating = models.PositiveIntegerField() profile = models.ForeignKey('accounts.Profile', related_name='ratings', on_delete=models.CASCADE) paper = models.ForeignKey('Paper', related_name='ratings', on_delete=models.CASCADE) def __str__(self): return f"{self.profile.user.username} gave {self.paper.title} a rating of {self.rating}" # class UserSavedPaper(models.Model): profile = models.ForeignKey('accounts.Profile', related_name='saved_papers', on_delete=models.CASCADE) paper = models.ForeignKey('Paper', related_name='saved_papers', on_delete=models.CASCADE) comment = models.CharField(max_length=500, blank=True) def __str__(self): return f"user {self.profile.user.username} saved paper {self.paper.title} - comment: {self.comment}"
normal
{ "blob_id": "052574be3f4a46bceefc0a54b1fe268a7cef18a9", "index": 3061, "step-1": "<mask token>\n\n\nclass Comment(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.text\n\n\nclass Rating(models.Model):\n rating = models.PositiveIntegerField()\n profile = models.ForeignKey('accounts.Profile', related_name='ratings',\n on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='ratings', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return (\n f'{self.profile.user.username} gave {self.paper.title} a rating of {self.rating}'\n )\n\n\nclass UserSavedPaper(models.Model):\n profile = models.ForeignKey('accounts.Profile', related_name=\n 'saved_papers', on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='saved_papers',\n on_delete=models.CASCADE)\n comment = models.CharField(max_length=500, blank=True)\n\n def __str__(self):\n return (\n f'user {self.profile.user.username} saved paper {self.paper.title} - comment: {self.comment}'\n )\n", "step-2": "<mask token>\n\n\nclass Comment(models.Model):\n text = models.CharField(max_length=500)\n time = models.DateTimeField(default=timezone.now)\n profile = models.ForeignKey('accounts.Profile', related_name='comments',\n on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='comments', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return self.text\n\n\nclass Rating(models.Model):\n rating = models.PositiveIntegerField()\n profile = models.ForeignKey('accounts.Profile', related_name='ratings',\n on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='ratings', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return (\n f'{self.profile.user.username} gave {self.paper.title} a rating of {self.rating}'\n )\n\n\nclass UserSavedPaper(models.Model):\n profile = models.ForeignKey('accounts.Profile', related_name=\n 'saved_papers', on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='saved_papers',\n on_delete=models.CASCADE)\n comment = models.CharField(max_length=500, blank=True)\n\n def __str__(self):\n return (\n f'user {self.profile.user.username} saved paper {self.paper.title} - comment: {self.comment}'\n )\n", "step-3": "<mask token>\n\n\nclass Paper(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Comment(models.Model):\n text = models.CharField(max_length=500)\n time = models.DateTimeField(default=timezone.now)\n profile = models.ForeignKey('accounts.Profile', related_name='comments',\n on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='comments', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return self.text\n\n\nclass Rating(models.Model):\n rating = models.PositiveIntegerField()\n profile = models.ForeignKey('accounts.Profile', related_name='ratings',\n on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='ratings', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return (\n f'{self.profile.user.username} gave {self.paper.title} a rating of {self.rating}'\n )\n\n\nclass UserSavedPaper(models.Model):\n profile = models.ForeignKey('accounts.Profile', related_name=\n 'saved_papers', on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='saved_papers',\n on_delete=models.CASCADE)\n comment = models.CharField(max_length=500, blank=True)\n\n def __str__(self):\n return (\n f'user {self.profile.user.username} saved paper {self.paper.title} - comment: {self.comment}'\n )\n", "step-4": "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n<mask token>\n\n\nclass Paper(models.Model):\n title = models.CharField(max_length=200)\n authors = models.CharField(max_length=200)\n abstract = models.CharField(max_length=2000, blank=True)\n journal = models.CharField(max_length=80, blank=True)\n date_published = models.DateField(blank=True)\n doi = models.CharField(max_length=32, blank=True)\n pdflink = models.CharField(max_length=80, blank=True)\n avg_rating = models.FloatField(default=0)\n num_ratings = models.PositiveIntegerField(default=0)\n commented_by_users = models.ManyToManyField('accounts.Profile',\n related_name='comments_made', through='Comment', blank=True)\n rated_by_users = models.ManyToManyField('accounts.Profile',\n related_name='ratings_given', through='Rating', blank=True)\n saved_by_users = models.ManyToManyField('accounts.Profile',\n related_name='papers_saved', through='UserSavedPaper', blank=True)\n\n def __str__(self):\n return self.title\n\n\nclass Comment(models.Model):\n text = models.CharField(max_length=500)\n time = models.DateTimeField(default=timezone.now)\n profile = models.ForeignKey('accounts.Profile', related_name='comments',\n on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='comments', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return self.text\n\n\nclass Rating(models.Model):\n rating = models.PositiveIntegerField()\n profile = models.ForeignKey('accounts.Profile', related_name='ratings',\n on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='ratings', on_delete=\n models.CASCADE)\n\n def __str__(self):\n return (\n f'{self.profile.user.username} gave {self.paper.title} a rating of {self.rating}'\n )\n\n\nclass UserSavedPaper(models.Model):\n profile = models.ForeignKey('accounts.Profile', related_name=\n 'saved_papers', on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='saved_papers',\n on_delete=models.CASCADE)\n comment = models.CharField(max_length=500, blank=True)\n\n def __str__(self):\n return (\n f'user {self.profile.user.username} saved paper {self.paper.title} - comment: {self.comment}'\n )\n", "step-5": "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\n\"\"\"\nUsing the django shell:\n$ python manage.py shell\n\nfrom django.contrib.auth.models import User\nfrom accounts.models import Profile\nfrom papers.models import Paper, Comment, Rating, UserSavedPaper\n\nusers = User.objects.all()\nprofiles = Profile.objects.all()\npapers = Paper.objects.all()\ncomments = Comment.objects.all()\nratings = Rating.objects.all()\nusps = UserSavedPaper.objects.all()\n\ncomments.create(text='this is an awesome paper!', profile=profiles[0], paper=papers[0])\n\"\"\"\n\n# Reversing migrations\n# https://docs.djangoproject.com/en/3.0/topics/migrations/#reversing-migrations\n# - Ex) $ python manage.py migrate papers zero <- reverses all migrations for app \"papers\", see all migrations with \"$ python manage.py showmigrations\"\n# -> python manage.py makemigrations -> python manage.py migrate\n\n\n# https://docs.djangoproject.com/en/3.0/ref/models/fields/\nclass Paper(models.Model):\n title = models.CharField(max_length=200) # About data storage space when specifying a max_length: https://stackoverflow.com/questions/30663791/do-setting-the-max-length-to-a-very-large-value-consume-extra-space\n authors = models.CharField(max_length=200)\n abstract = models.CharField(max_length=2000, blank=True)\n journal = models.CharField(max_length=80, blank=True) \n date_published = models.DateField(blank=True) # https://www.django-rest-framework.org/api-guide/fields/#datefield\n doi = models.CharField(max_length=32, blank=True)\n pdflink = models.CharField(max_length=80, blank=True)\n avg_rating = models.FloatField(default=0)\n num_ratings = models.PositiveIntegerField(default=0)\n\n # Useful example for many-to-many in django: https://www.revsys.com/tidbits/tips-using-djangos-manytomanyfield/\n # - TO DO: Get rid of these fields below in the Paper model? The Comment/Rating/UserSavedPaper tables can exist without them being here!?\n commented_by_users = models.ManyToManyField(\n 'accounts.Profile',\n related_name='comments_made',\n through='Comment',\n blank=True\n )\n\n rated_by_users = models.ManyToManyField(\n 'accounts.Profile',\n related_name='ratings_given',\n through='Rating',\n blank=True\n )\n \n saved_by_users = models.ManyToManyField(\n 'accounts.Profile',\n related_name=\"papers_saved\",\n through='UserSavedPaper',\n blank=True\n )\n\n def __str__(self):\n return self.title\n\n\n# Custom \"through\" models: https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ManyToManyField.through_fields\nclass Comment(models.Model):\n text = models.CharField(max_length=500)\n #rating = models.PositiveIntegerField(blank=True) # should rating be given simultaneously with posting a comment?\n time = models.DateTimeField(default=timezone.now) # - TO DO: Look into and decide format for the timestamping\n profile = models.ForeignKey('accounts.Profile', related_name='comments', on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='comments', on_delete=models.CASCADE)\n\n def __str__(self):\n return self.text\n\n\n# No support for composite primary key, e.g. (profile_id, paper_id) in django? https://stackoverflow.com/questions/15440593/tell-djangos-model-to-use-as-primary-key-a-set-of-foreign-keys\n# - https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys\n# - possible to enforce it using SQL commands, using something other than the Django ORM, e.g. SQLAlchemy)\n# - there are validators that can be used with a Serializer to enforce \"unique together\" - https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator\nclass Rating(models.Model):\n rating = models.PositiveIntegerField()\n profile = models.ForeignKey('accounts.Profile', related_name='ratings', on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='ratings', on_delete=models.CASCADE)\n\n def __str__(self):\n return f\"{self.profile.user.username} gave {self.paper.title} a rating of {self.rating}\"\n\n\n# \nclass UserSavedPaper(models.Model): \n profile = models.ForeignKey('accounts.Profile', related_name='saved_papers', on_delete=models.CASCADE)\n paper = models.ForeignKey('Paper', related_name='saved_papers', on_delete=models.CASCADE)\n comment = models.CharField(max_length=500, blank=True)\n\n def __str__(self):\n return f\"user {self.profile.user.username} saved paper {self.paper.title} - comment: {self.comment}\"\n", "step-ids": [ 8, 9, 10, 13, 14 ] }
[ 8, 9, 10, 13, 14 ]
<|reserved_special_token_0|> class Codec: <|reserved_special_token_0|> def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i, str = 0, [] while i < len(s): sharp = s.find('#', i) l = int(s[i:sharp]) str.append(s[sharp + 1:sharp + l + 1]) i = sharp + l + 1 return str class Codec(object): def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ encoded_str = '' for s in strs: encoded_str += '%0*x' % (8, len(s)) + s return encoded_str def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i = 0 strs = [] while i < len(s): l = int(s[i:i + 8], 16) strs.append(s[i + 8:i + 8 + l]) i += 8 + l return strs <|reserved_special_token_1|> <|reserved_special_token_0|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ s = '' for i in strs: s += str(len(i)) + '#' + i return s def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i, str = 0, [] while i < len(s): sharp = s.find('#', i) l = int(s[i:sharp]) str.append(s[sharp + 1:sharp + l + 1]) i = sharp + l + 1 return str class Codec(object): def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ encoded_str = '' for s in strs: encoded_str += '%0*x' % (8, len(s)) + s return encoded_str def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i = 0 strs = [] while i < len(s): l = int(s[i:i + 8], 16) strs.append(s[i + 8:i + 8 + l]) i += 8 + l return strs <|reserved_special_token_1|> class Codec: <|reserved_special_token_0|> <|reserved_special_token_0|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ s = '' for i in strs: s += str(len(i)) + '#' + i return s def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i, str = 0, [] while i < len(s): sharp = s.find('#', i) l = int(s[i:sharp]) str.append(s[sharp + 1:sharp + l + 1]) i = sharp + l + 1 return str class Codec(object): def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ encoded_str = '' for s in strs: encoded_str += '%0*x' % (8, len(s)) + s return encoded_str def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i = 0 strs = [] while i < len(s): l = int(s[i:i + 8], 16) strs.append(s[i + 8:i + 8 + l]) i += 8 + l return strs <|reserved_special_token_1|> class Codec: def encode(self, strs): s = '' for i in strs: s += str(len(i)) + '#' + i return s <|reserved_special_token_0|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ s = '' for i in strs: s += str(len(i)) + '#' + i return s def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i, str = 0, [] while i < len(s): sharp = s.find('#', i) l = int(s[i:sharp]) str.append(s[sharp + 1:sharp + l + 1]) i = sharp + l + 1 return str class Codec(object): def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ encoded_str = '' for s in strs: encoded_str += '%0*x' % (8, len(s)) + s return encoded_str def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i = 0 strs = [] while i < len(s): l = int(s[i:i + 8], 16) strs.append(s[i + 8:i + 8 + l]) i += 8 + l return strs <|reserved_special_token_1|> # V0 class Codec: def encode(self, strs): s = "" for i in strs: s += str(len(i)) + "#" + i return s def decode(self, s): i, str = 0, [] while i < len(s): sharp = s.find("#", i) l = int(s[i:sharp]) str.append(s[sharp + 1:sharp + l + 1]) i = sharp + l + 1 return str # V1 # http://www.voidcn.com/article/p-hpbzcdjd-zo.html class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ s = "" for i in strs: s += str(len(i)) + "#" + i return s def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i, str = 0, [] while i < len(s): sharp = s.find("#", i) l = int(s[i:sharp]) str.append(s[sharp + 1:sharp + l + 1]) i = sharp + l + 1 return str # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(strs)) ### Test case : dev # V1' # https://medium.com/leetcode-%E6%BC%94%E7%AE%97%E6%B3%95%E6%95%99%E5%AD%B8/024-leetcode-271-%E6%BC%94%E7%AE%97%E6%B3%95-encode-and-decode-strings-%E5%AD%97%E4%B8%B2%E5%8A%A0%E8%A7%A3%E5%AF%86-722cafd6238 # IDEA : # ABC -> 3/ABC # ABCD -> 4/ABCD # A B C D ->1/A1/B1/C1/D # # JAVA # // Encodes a list of strings to a single string. # public String encode(List<String> strs) { # StringBuilder sb = new StringBuilder(); # for(String s : strs) { # sb.append(s.length()).append('/').append(s); # } # return sb.toString(); # } # # // Decodes a single string to a list of strings. # public List<String> decode(String s) { # List<String> ret = new ArrayList<String>(); # int i = 0; # while(i < s.length()) { # int slash = s.indexOf('/', i);// return the 1st '/' index from i # int size = Integer.valueOf(s.substring(i, slash)); // the length of encode # ret.add(s.substring(slash + 1, slash + size + 1)); // cut it off # i = slash + size + 1;// redefine the i index # } # return ret; # } # V2 # Time: O(n) # Space: O(1) class Codec(object): def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ encoded_str = "" for s in strs: encoded_str += "%0*x" % (8, len(s)) + s return encoded_str def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ i = 0 strs = [] while i < len(s): l = int(s[i:i+8], 16) strs.append(s[i+8:i+8+l]) i += 8+l return strs
flexible
{ "blob_id": "b94392c9c6547415326d80ff0923cb8ba9251783", "index": 5724, "step-1": "<mask token>\n\n\nclass Codec:\n <mask token>\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n \n :type s: str\n :rtype: List[str]\n \"\"\"\n i, str = 0, []\n while i < len(s):\n sharp = s.find('#', i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\n return str\n\n\nclass Codec(object):\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n encoded_str = ''\n for s in strs:\n encoded_str += '%0*x' % (8, len(s)) + s\n return encoded_str\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n :type s: str\n :rtype: List[str]\n \"\"\"\n i = 0\n strs = []\n while i < len(s):\n l = int(s[i:i + 8], 16)\n strs.append(s[i + 8:i + 8 + l])\n i += 8 + l\n return strs\n", "step-2": "<mask token>\n\n\nclass Codec:\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n \n :type strs: List[str]\n :rtype: str\n \"\"\"\n s = ''\n for i in strs:\n s += str(len(i)) + '#' + i\n return s\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n \n :type s: str\n :rtype: List[str]\n \"\"\"\n i, str = 0, []\n while i < len(s):\n sharp = s.find('#', i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\n return str\n\n\nclass Codec(object):\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n encoded_str = ''\n for s in strs:\n encoded_str += '%0*x' % (8, len(s)) + s\n return encoded_str\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n :type s: str\n :rtype: List[str]\n \"\"\"\n i = 0\n strs = []\n while i < len(s):\n l = int(s[i:i + 8], 16)\n strs.append(s[i + 8:i + 8 + l])\n i += 8 + l\n return strs\n", "step-3": "class Codec:\n <mask token>\n <mask token>\n\n\nclass Codec:\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n \n :type strs: List[str]\n :rtype: str\n \"\"\"\n s = ''\n for i in strs:\n s += str(len(i)) + '#' + i\n return s\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n \n :type s: str\n :rtype: List[str]\n \"\"\"\n i, str = 0, []\n while i < len(s):\n sharp = s.find('#', i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\n return str\n\n\nclass Codec(object):\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n encoded_str = ''\n for s in strs:\n encoded_str += '%0*x' % (8, len(s)) + s\n return encoded_str\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n :type s: str\n :rtype: List[str]\n \"\"\"\n i = 0\n strs = []\n while i < len(s):\n l = int(s[i:i + 8], 16)\n strs.append(s[i + 8:i + 8 + l])\n i += 8 + l\n return strs\n", "step-4": "class Codec:\n\n def encode(self, strs):\n s = ''\n for i in strs:\n s += str(len(i)) + '#' + i\n return s\n <mask token>\n\n\nclass Codec:\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n \n :type strs: List[str]\n :rtype: str\n \"\"\"\n s = ''\n for i in strs:\n s += str(len(i)) + '#' + i\n return s\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n \n :type s: str\n :rtype: List[str]\n \"\"\"\n i, str = 0, []\n while i < len(s):\n sharp = s.find('#', i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\n return str\n\n\nclass Codec(object):\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n encoded_str = ''\n for s in strs:\n encoded_str += '%0*x' % (8, len(s)) + s\n return encoded_str\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n :type s: str\n :rtype: List[str]\n \"\"\"\n i = 0\n strs = []\n while i < len(s):\n l = int(s[i:i + 8], 16)\n strs.append(s[i + 8:i + 8 + l])\n i += 8 + l\n return strs\n", "step-5": "# V0 \nclass Codec:\n def encode(self, strs):\n s = \"\"\n for i in strs:\n s += str(len(i)) + \"#\" + i\n return s\n\n def decode(self, s):\n i, str = 0, []\n while i < len(s):\n sharp = s.find(\"#\", i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\n return str\n\n# V1 \n# http://www.voidcn.com/article/p-hpbzcdjd-zo.html\nclass Codec:\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n \n :type strs: List[str]\n :rtype: str\n \"\"\"\n s = \"\"\n for i in strs:\n s += str(len(i)) + \"#\" + i\n return s\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n \n :type s: str\n :rtype: List[str]\n \"\"\"\n i, str = 0, []\n while i < len(s):\n sharp = s.find(\"#\", i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\n return str\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.decode(codec.encode(strs))\n\n### Test case : dev \n\n# V1'\n# https://medium.com/leetcode-%E6%BC%94%E7%AE%97%E6%B3%95%E6%95%99%E5%AD%B8/024-leetcode-271-%E6%BC%94%E7%AE%97%E6%B3%95-encode-and-decode-strings-%E5%AD%97%E4%B8%B2%E5%8A%A0%E8%A7%A3%E5%AF%86-722cafd6238\n# IDEA :\n# ABC -> 3/ABC \n# ABCD -> 4/ABCD\n# A B C D ->1/A1/B1/C1/D\n#\n# JAVA\n# // Encodes a list of strings to a single string.\n# public String encode(List<String> strs) {\n# StringBuilder sb = new StringBuilder();\n# for(String s : strs) {\n# sb.append(s.length()).append('/').append(s);\n# }\n# return sb.toString();\n# }\n#\n# // Decodes a single string to a list of strings.\n# public List<String> decode(String s) {\n# List<String> ret = new ArrayList<String>();\n# int i = 0;\n# while(i < s.length()) {\n# int slash = s.indexOf('/', i);// return the 1st '/' index from i\n# int size = Integer.valueOf(s.substring(i, slash)); // the length of encode\n# ret.add(s.substring(slash + 1, slash + size + 1)); // cut it off\n# i = slash + size + 1;// redefine the i index \n# }\n# return ret;\n# }\n\n# V2 \n# Time: O(n)\n# Space: O(1)\nclass Codec(object):\n\n def encode(self, strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n encoded_str = \"\"\n for s in strs:\n encoded_str += \"%0*x\" % (8, len(s)) + s\n return encoded_str\n\n\n def decode(self, s):\n \"\"\"Decodes a single string to a list of strings.\n :type s: str\n :rtype: List[str]\n \"\"\"\n i = 0\n strs = []\n while i < len(s):\n l = int(s[i:i+8], 16)\n strs.append(s[i+8:i+8+l])\n i += 8+l\n return strs", "step-ids": [ 5, 6, 7, 8, 10 ] }
[ 5, 6, 7, 8, 10 ]
#!/usr/bin/env python ############################################################################### # Copyright 2017 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### """Global config access.""" import os import google.protobuf.text_format as text_format import gflags import glog import modules.hmi.proto.config_pb2 as config_pb2 class Config(object): """Global config.""" pb_singleton = None hardware_dict = None module_dict = None tool_dict = None apollo_root = os.path.join(os.path.dirname(__file__), '../../..') @classmethod def get_pb(cls): """Get a pb instance from the config.""" if cls.pb_singleton is None: # Init the config by reading conf file. with open(gflags.FLAGS.conf, 'r') as conf_file: cls.pb_singleton = text_format.Merge(conf_file.read(), config_pb2.Config()) glog.info('Get config: {}'.format(cls.pb_singleton)) return cls.pb_singleton @classmethod def get_hardware(cls, hardware_name): """Get Hardware config by name.""" if cls.hardware_dict is None: # Init the hardware_dict once. cls.hardware_dict = {hw.name: hw for hw in cls.get_pb().hardware} return cls.hardware_dict.get(hardware_name) @classmethod def get_module(cls, module_name): """Get module config by name.""" if cls.module_dict is None: # Init the module_dict once. cls.module_dict = {mod.name: mod for mod in cls.get_pb().modules} return cls.module_dict.get(module_name) @classmethod def get_tool(cls, tool_name): """Get module config by name.""" if cls.tool_dict is None: # Init the module_dict once. cls.tool_dict = {tool.name: tool for tool in cls.get_pb().tools} return cls.tool_dict.get(tool_name) @classmethod def get_realpath(cls, path_str): """ Get realpath from a path string in config. Starting with '/' indicates an absolute path, otherwise it will be taken as a relative path of the Apollo root. """ if path_str.startswith('/'): return path_str return os.path.abspath(os.path.join(cls.apollo_root, path_str))
normal
{ "blob_id": "4b552731fcfc661c7ad2d63c7c47f79c43a8ae5e", "index": 4839, "step-1": "<mask token>\n\n\nclass Config(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def get_pb(cls):\n \"\"\"Get a pb instance from the config.\"\"\"\n if cls.pb_singleton is None:\n with open(gflags.FLAGS.conf, 'r') as conf_file:\n cls.pb_singleton = text_format.Merge(conf_file.read(),\n config_pb2.Config())\n glog.info('Get config: {}'.format(cls.pb_singleton))\n return cls.pb_singleton\n <mask token>\n\n @classmethod\n def get_module(cls, module_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.module_dict is None:\n cls.module_dict = {mod.name: mod for mod in cls.get_pb().modules}\n return cls.module_dict.get(module_name)\n <mask token>\n\n @classmethod\n def get_realpath(cls, path_str):\n \"\"\"\n Get realpath from a path string in config.\n\n Starting with '/' indicates an absolute path, otherwise it will be taken\n as a relative path of the Apollo root.\n \"\"\"\n if path_str.startswith('/'):\n return path_str\n return os.path.abspath(os.path.join(cls.apollo_root, path_str))\n", "step-2": "<mask token>\n\n\nclass Config(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def get_pb(cls):\n \"\"\"Get a pb instance from the config.\"\"\"\n if cls.pb_singleton is None:\n with open(gflags.FLAGS.conf, 'r') as conf_file:\n cls.pb_singleton = text_format.Merge(conf_file.read(),\n config_pb2.Config())\n glog.info('Get config: {}'.format(cls.pb_singleton))\n return cls.pb_singleton\n\n @classmethod\n def get_hardware(cls, hardware_name):\n \"\"\"Get Hardware config by name.\"\"\"\n if cls.hardware_dict is None:\n cls.hardware_dict = {hw.name: hw for hw in cls.get_pb().hardware}\n return cls.hardware_dict.get(hardware_name)\n\n @classmethod\n def get_module(cls, module_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.module_dict is None:\n cls.module_dict = {mod.name: mod for mod in cls.get_pb().modules}\n return cls.module_dict.get(module_name)\n\n @classmethod\n def get_tool(cls, tool_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.tool_dict is None:\n cls.tool_dict = {tool.name: tool for tool in cls.get_pb().tools}\n return cls.tool_dict.get(tool_name)\n\n @classmethod\n def get_realpath(cls, path_str):\n \"\"\"\n Get realpath from a path string in config.\n\n Starting with '/' indicates an absolute path, otherwise it will be taken\n as a relative path of the Apollo root.\n \"\"\"\n if path_str.startswith('/'):\n return path_str\n return os.path.abspath(os.path.join(cls.apollo_root, path_str))\n", "step-3": "<mask token>\n\n\nclass Config(object):\n <mask token>\n pb_singleton = None\n hardware_dict = None\n module_dict = None\n tool_dict = None\n apollo_root = os.path.join(os.path.dirname(__file__), '../../..')\n\n @classmethod\n def get_pb(cls):\n \"\"\"Get a pb instance from the config.\"\"\"\n if cls.pb_singleton is None:\n with open(gflags.FLAGS.conf, 'r') as conf_file:\n cls.pb_singleton = text_format.Merge(conf_file.read(),\n config_pb2.Config())\n glog.info('Get config: {}'.format(cls.pb_singleton))\n return cls.pb_singleton\n\n @classmethod\n def get_hardware(cls, hardware_name):\n \"\"\"Get Hardware config by name.\"\"\"\n if cls.hardware_dict is None:\n cls.hardware_dict = {hw.name: hw for hw in cls.get_pb().hardware}\n return cls.hardware_dict.get(hardware_name)\n\n @classmethod\n def get_module(cls, module_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.module_dict is None:\n cls.module_dict = {mod.name: mod for mod in cls.get_pb().modules}\n return cls.module_dict.get(module_name)\n\n @classmethod\n def get_tool(cls, tool_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.tool_dict is None:\n cls.tool_dict = {tool.name: tool for tool in cls.get_pb().tools}\n return cls.tool_dict.get(tool_name)\n\n @classmethod\n def get_realpath(cls, path_str):\n \"\"\"\n Get realpath from a path string in config.\n\n Starting with '/' indicates an absolute path, otherwise it will be taken\n as a relative path of the Apollo root.\n \"\"\"\n if path_str.startswith('/'):\n return path_str\n return os.path.abspath(os.path.join(cls.apollo_root, path_str))\n", "step-4": "<mask token>\nimport os\nimport google.protobuf.text_format as text_format\nimport gflags\nimport glog\nimport modules.hmi.proto.config_pb2 as config_pb2\n\n\nclass Config(object):\n \"\"\"Global config.\"\"\"\n pb_singleton = None\n hardware_dict = None\n module_dict = None\n tool_dict = None\n apollo_root = os.path.join(os.path.dirname(__file__), '../../..')\n\n @classmethod\n def get_pb(cls):\n \"\"\"Get a pb instance from the config.\"\"\"\n if cls.pb_singleton is None:\n with open(gflags.FLAGS.conf, 'r') as conf_file:\n cls.pb_singleton = text_format.Merge(conf_file.read(),\n config_pb2.Config())\n glog.info('Get config: {}'.format(cls.pb_singleton))\n return cls.pb_singleton\n\n @classmethod\n def get_hardware(cls, hardware_name):\n \"\"\"Get Hardware config by name.\"\"\"\n if cls.hardware_dict is None:\n cls.hardware_dict = {hw.name: hw for hw in cls.get_pb().hardware}\n return cls.hardware_dict.get(hardware_name)\n\n @classmethod\n def get_module(cls, module_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.module_dict is None:\n cls.module_dict = {mod.name: mod for mod in cls.get_pb().modules}\n return cls.module_dict.get(module_name)\n\n @classmethod\n def get_tool(cls, tool_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.tool_dict is None:\n cls.tool_dict = {tool.name: tool for tool in cls.get_pb().tools}\n return cls.tool_dict.get(tool_name)\n\n @classmethod\n def get_realpath(cls, path_str):\n \"\"\"\n Get realpath from a path string in config.\n\n Starting with '/' indicates an absolute path, otherwise it will be taken\n as a relative path of the Apollo root.\n \"\"\"\n if path_str.startswith('/'):\n return path_str\n return os.path.abspath(os.path.join(cls.apollo_root, path_str))\n", "step-5": "#!/usr/bin/env python\n\n###############################################################################\n# Copyright 2017 The Apollo Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n\"\"\"Global config access.\"\"\"\n\nimport os\n\nimport google.protobuf.text_format as text_format\nimport gflags\nimport glog\n\nimport modules.hmi.proto.config_pb2 as config_pb2\n\n\nclass Config(object):\n \"\"\"Global config.\"\"\"\n\n pb_singleton = None\n hardware_dict = None\n module_dict = None\n tool_dict = None\n apollo_root = os.path.join(os.path.dirname(__file__), '../../..')\n\n @classmethod\n def get_pb(cls):\n \"\"\"Get a pb instance from the config.\"\"\"\n if cls.pb_singleton is None:\n # Init the config by reading conf file.\n with open(gflags.FLAGS.conf, 'r') as conf_file:\n cls.pb_singleton = text_format.Merge(conf_file.read(),\n config_pb2.Config())\n glog.info('Get config: {}'.format(cls.pb_singleton))\n return cls.pb_singleton\n\n @classmethod\n def get_hardware(cls, hardware_name):\n \"\"\"Get Hardware config by name.\"\"\"\n if cls.hardware_dict is None:\n # Init the hardware_dict once.\n cls.hardware_dict = {hw.name: hw for hw in cls.get_pb().hardware}\n return cls.hardware_dict.get(hardware_name)\n\n @classmethod\n def get_module(cls, module_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.module_dict is None:\n # Init the module_dict once.\n cls.module_dict = {mod.name: mod for mod in cls.get_pb().modules}\n return cls.module_dict.get(module_name)\n\n @classmethod\n def get_tool(cls, tool_name):\n \"\"\"Get module config by name.\"\"\"\n if cls.tool_dict is None:\n # Init the module_dict once.\n cls.tool_dict = {tool.name: tool for tool in cls.get_pb().tools}\n return cls.tool_dict.get(tool_name)\n\n @classmethod\n def get_realpath(cls, path_str):\n \"\"\"\n Get realpath from a path string in config.\n\n Starting with '/' indicates an absolute path, otherwise it will be taken\n as a relative path of the Apollo root.\n \"\"\"\n if path_str.startswith('/'):\n return path_str\n return os.path.abspath(os.path.join(cls.apollo_root, path_str))\n", "step-ids": [ 4, 6, 7, 9, 10 ] }
[ 4, 6, 7, 9, 10 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(radius - 10, radius + 10)) return xpoint, ypoint, color, radius, delta_list, radius_list <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(radius - 10, radius + 10)) return xpoint, ypoint, color, radius, delta_list, radius_list def sun(prepare_list): xpoint = prepare_list[0] ypoint = prepare_list[1] color = prepare_list[2] radius = prepare_list[3] delta_list = prepare_list[4] radius_list = prepare_list[5] sd.start_drawing() point = sd.get_point(xpoint, ypoint) sd.circle(center_position=point, radius=radius * 3.9, color=sd. background_color, width=0) sd.circle(center_position=point, radius=radius, color=color, width=0) for j, (delta, radius) in enumerate(zip(delta_list, radius_list)): v = sd.get_vector(start_point=point, angle=delta, width=6, length= random.randint(radius * 2, radius * 3)) v.draw(color) sd.finish_drawing() <|reserved_special_token_1|> import simple_draw as sd import random def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(radius - 10, radius + 10)) return xpoint, ypoint, color, radius, delta_list, radius_list def sun(prepare_list): xpoint = prepare_list[0] ypoint = prepare_list[1] color = prepare_list[2] radius = prepare_list[3] delta_list = prepare_list[4] radius_list = prepare_list[5] sd.start_drawing() point = sd.get_point(xpoint, ypoint) sd.circle(center_position=point, radius=radius * 3.9, color=sd. background_color, width=0) sd.circle(center_position=point, radius=radius, color=color, width=0) for j, (delta, radius) in enumerate(zip(delta_list, radius_list)): v = sd.get_vector(start_point=point, angle=delta, width=6, length= random.randint(radius * 2, radius * 3)) v.draw(color) sd.finish_drawing() <|reserved_special_token_1|> import simple_draw as sd import random # sd.resolution = (1400, 900) # Prepare data for the sun function def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(radius - 10, radius + 10)) return xpoint, ypoint, color, radius, delta_list, radius_list # Drawing the sun def sun(prepare_list): xpoint = prepare_list[0] ypoint = prepare_list[1] color = prepare_list[2] radius = prepare_list[3] delta_list = prepare_list[4] radius_list = prepare_list[5] sd.start_drawing() point = sd.get_point(xpoint, ypoint) sd.circle(center_position=point, radius=radius * 3.9, color=sd.background_color, width=0) sd.circle(center_position=point, radius=radius, color=color, width=0) for j, (delta, radius) in enumerate(zip(delta_list, radius_list)): v = sd.get_vector(start_point=point, angle=delta, width=6, length=random.randint(radius * 2, radius * 3)) v.draw(color) sd.finish_drawing() # sd.pause()
flexible
{ "blob_id": "46babde9c26a944c9d29121b6bbf89a32f242a81", "index": 251, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef sun_prepare(xpoint, ypoint, radius, color, angle):\n delta_list = []\n radius_list = []\n for delta in range(0, 360, angle):\n delta_list.append(delta)\n radius_list.append(random.randint(radius - 10, radius + 10))\n return xpoint, ypoint, color, radius, delta_list, radius_list\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef sun_prepare(xpoint, ypoint, radius, color, angle):\n delta_list = []\n radius_list = []\n for delta in range(0, 360, angle):\n delta_list.append(delta)\n radius_list.append(random.randint(radius - 10, radius + 10))\n return xpoint, ypoint, color, radius, delta_list, radius_list\n\n\ndef sun(prepare_list):\n xpoint = prepare_list[0]\n ypoint = prepare_list[1]\n color = prepare_list[2]\n radius = prepare_list[3]\n delta_list = prepare_list[4]\n radius_list = prepare_list[5]\n sd.start_drawing()\n point = sd.get_point(xpoint, ypoint)\n sd.circle(center_position=point, radius=radius * 3.9, color=sd.\n background_color, width=0)\n sd.circle(center_position=point, radius=radius, color=color, width=0)\n for j, (delta, radius) in enumerate(zip(delta_list, radius_list)):\n v = sd.get_vector(start_point=point, angle=delta, width=6, length=\n random.randint(radius * 2, radius * 3))\n v.draw(color)\n sd.finish_drawing()\n", "step-4": "import simple_draw as sd\nimport random\n\n\ndef sun_prepare(xpoint, ypoint, radius, color, angle):\n delta_list = []\n radius_list = []\n for delta in range(0, 360, angle):\n delta_list.append(delta)\n radius_list.append(random.randint(radius - 10, radius + 10))\n return xpoint, ypoint, color, radius, delta_list, radius_list\n\n\ndef sun(prepare_list):\n xpoint = prepare_list[0]\n ypoint = prepare_list[1]\n color = prepare_list[2]\n radius = prepare_list[3]\n delta_list = prepare_list[4]\n radius_list = prepare_list[5]\n sd.start_drawing()\n point = sd.get_point(xpoint, ypoint)\n sd.circle(center_position=point, radius=radius * 3.9, color=sd.\n background_color, width=0)\n sd.circle(center_position=point, radius=radius, color=color, width=0)\n for j, (delta, radius) in enumerate(zip(delta_list, radius_list)):\n v = sd.get_vector(start_point=point, angle=delta, width=6, length=\n random.randint(radius * 2, radius * 3))\n v.draw(color)\n sd.finish_drawing()\n", "step-5": "import simple_draw as sd\nimport random\n\n\n# sd.resolution = (1400, 900)\n\n# Prepare data for the sun function\ndef sun_prepare(xpoint, ypoint, radius, color, angle):\n delta_list = []\n radius_list = []\n for delta in range(0, 360, angle):\n delta_list.append(delta)\n radius_list.append(random.randint(radius - 10, radius + 10))\n\n return xpoint, ypoint, color, radius, delta_list, radius_list\n\n\n# Drawing the sun\ndef sun(prepare_list):\n xpoint = prepare_list[0]\n ypoint = prepare_list[1]\n color = prepare_list[2]\n radius = prepare_list[3]\n delta_list = prepare_list[4]\n radius_list = prepare_list[5]\n sd.start_drawing()\n point = sd.get_point(xpoint, ypoint)\n sd.circle(center_position=point, radius=radius * 3.9, color=sd.background_color, width=0)\n sd.circle(center_position=point, radius=radius, color=color, width=0)\n for j, (delta, radius) in enumerate(zip(delta_list, radius_list)):\n v = sd.get_vector(start_point=point, angle=delta, width=6,\n length=random.randint(radius * 2, radius * 3))\n v.draw(color)\n sd.finish_drawing()\n\n# sd.pause()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from django.apps import AppConfig class QuadraticEquationsSolverConfig(AppConfig): name = 'quadratic_equations_solver'
normal
{ "blob_id": "730fc527f3d2805559e8917e846b0b13f4a9f6ee", "index": 2316, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass QuadraticEquationsSolverConfig(AppConfig):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass QuadraticEquationsSolverConfig(AppConfig):\n name = 'quadratic_equations_solver'\n", "step-4": "from django.apps import AppConfig\n\n\nclass QuadraticEquationsSolverConfig(AppConfig):\n name = 'quadratic_equations_solver'\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def top(request): return render(request, 'new_questions.html', {'title': 'Топ вопросов', 'questions': paginate(request, models.Question.objects.get_hot()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects. get_hot())}) <|reserved_special_token_0|> def hot(request, id=1): """docstring for Main_menu""" return render(request, 'hot.html', {'users': paginate(request, models. CustomUser.objects.by_rating())[:10], 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'questions': paginate(request, objects_list=models.Question.objects.get_hot()), 'page_objects': paginate(request, objects_list=models.Question.objects.get_hot())}) <|reserved_special_token_0|> def question_page(request, id): return render(request, 'questions.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'question': get_object_or_404(models.Question, pk=id), 'answers': paginate( request, objects_list=models.Answer.objects.get_hot_for_answer(id)), 'page_objects': paginate(request, objects_list=models.Answer. objects.get_hot_for_answer(id))}) def tag(request, id): return render(request, 'tag_find.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[0:10], 'tags': paginate( request, models.Tag.objects.hottest())[0:10], 'tag': get_object_or_404(models.Tag, pk=id), 'questions': paginate(request, models.Question.objects.get_by_tag(tag_id=id)), 'page_objects': paginate(request, objects_list=models.Question.objects.get_by_tag( tag_id=id))}) <|reserved_special_token_0|> @login_required(login_url='/log_in/') def ask(request): error = True if request.method == 'POST': firstly = False form = AskForm(request.POST) if form.is_valid(): ques = models.Question.objects.create(author=request.user, create_date=timezone.now(), is_active=True, title=form. cleaned_data['title'], text=form.cleaned_data['text']) ques.save() for tagTitle in form.cleaned_data['tags'].split(): tag = models.Tag.objects.get_or_create(title=tagTitle)[0] ques.tags.add(tag) ques.save() return redirect('/question/{}/'.format(ques.id)) else: error = False else: form = AskForm() firstly = True return render(request, 'new_ask.html', {'firstly': firstly, 'error': error, 'form': form, 'tags': paginate(request, models.Tag.objects. hottest())[:10], 'users': paginate(request, models.CustomUser. objects.by_rating())[:10]}) def signin(request): last_page = request.GET['next'] if last_page == '/logout' or last_page == '/login': last_page = '/' error = False if request.method == 'POST': user = authenticate(username=request.POST['nickname'], password= request.POST['password']) if user is not None: login(request, user) return redirect(last_page) else: error = True return render(request, 'login.html', {'error': error, 'last_page': last_page, 'tags': paginate(request, models.Tag.objects.hottest()), 'users': paginate(request, models.CustomUser.objects.by_rating())}) <|reserved_special_token_0|> def signout(request): if not request.user.is_authenticated: raise Http404 logout(request) return redirect('/') <|reserved_special_token_0|> @require_POST def like_question(request): question_id = request.POST.get('question_id', '') like_type = request.POST.get('like_type', '') question = get_object_or_404(Question, pk=question_id) if not question: return JsonResponse({'status': 'error'}) if like_type == 'like': question.rating += 1 elif like_type == 'dislike': question.rating -= 1 question.save() return JsonResponse({'status': 'ok'}) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def top(request): return render(request, 'new_questions.html', {'title': 'Топ вопросов', 'questions': paginate(request, models.Question.objects.get_hot()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects. get_hot())}) def new(request): return render(request, 'new_questions.html', {'title': 'Новые', 'questions': paginate(request, models.Question.objects.get_new()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects. get_new())}) def hot(request, id=1): """docstring for Main_menu""" return render(request, 'hot.html', {'users': paginate(request, models. CustomUser.objects.by_rating())[:10], 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'questions': paginate(request, objects_list=models.Question.objects.get_hot()), 'page_objects': paginate(request, objects_list=models.Question.objects.get_hot())}) def profile(request, id): return render(request, 'user_settings.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'profile': get_object_or_404(models.CustomUser, pk=id)}) <|reserved_special_token_0|> def question_page(request, id): return render(request, 'questions.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'question': get_object_or_404(models.Question, pk=id), 'answers': paginate( request, objects_list=models.Answer.objects.get_hot_for_answer(id)), 'page_objects': paginate(request, objects_list=models.Answer. objects.get_hot_for_answer(id))}) def tag(request, id): return render(request, 'tag_find.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[0:10], 'tags': paginate( request, models.Tag.objects.hottest())[0:10], 'tag': get_object_or_404(models.Tag, pk=id), 'questions': paginate(request, models.Question.objects.get_by_tag(tag_id=id)), 'page_objects': paginate(request, objects_list=models.Question.objects.get_by_tag( tag_id=id))}) <|reserved_special_token_0|> @login_required(login_url='/log_in/') def new_answer(request, id): if models.Question.objects.filter(id=id).exists(): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answeredQuestion = get_object_or_404(models.Question, pk=id) answer = models.Answer.objects.create(author=request.user, create_date=timezone.now(), text=form.cleaned_data[ 'text'], question_id=answeredQuestion.id) answer.save() return redirect('/question/{}/add_answer/'.format(id)) else: form = AnswerForm() return render(request, 'questions.html', {'form': form, 'question': get_object_or_404(models.Question, pk=id), 'answers': paginate( request, models.Answer.objects.get_hot_for_answer(id)), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects': paginate(request, models.Answer.objects. get_hot_for_answer(id))}) else: raise Http404 @login_required(login_url='/log_in/') def ask(request): error = True if request.method == 'POST': firstly = False form = AskForm(request.POST) if form.is_valid(): ques = models.Question.objects.create(author=request.user, create_date=timezone.now(), is_active=True, title=form. cleaned_data['title'], text=form.cleaned_data['text']) ques.save() for tagTitle in form.cleaned_data['tags'].split(): tag = models.Tag.objects.get_or_create(title=tagTitle)[0] ques.tags.add(tag) ques.save() return redirect('/question/{}/'.format(ques.id)) else: error = False else: form = AskForm() firstly = True return render(request, 'new_ask.html', {'firstly': firstly, 'error': error, 'form': form, 'tags': paginate(request, models.Tag.objects. hottest())[:10], 'users': paginate(request, models.CustomUser. objects.by_rating())[:10]}) def signin(request): last_page = request.GET['next'] if last_page == '/logout' or last_page == '/login': last_page = '/' error = False if request.method == 'POST': user = authenticate(username=request.POST['nickname'], password= request.POST['password']) if user is not None: login(request, user) return redirect(last_page) else: error = True return render(request, 'login.html', {'error': error, 'last_page': last_page, 'tags': paginate(request, models.Tag.objects.hottest()), 'users': paginate(request, models.CustomUser.objects.by_rating())}) def registration(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST, request.FILES) print(user_form) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() login(request, user) return redirect(request.GET.get('next') if request.GET.get( 'next') != '' else '/') else: print(user_form.errors) else: user_form = UserRegistrationForm() return render(request, 'registration.html', {'form': user_form}) def signout(request): if not request.user.is_authenticated: raise Http404 logout(request) return redirect('/') <|reserved_special_token_0|> @require_POST def like_question(request): question_id = request.POST.get('question_id', '') like_type = request.POST.get('like_type', '') question = get_object_or_404(Question, pk=question_id) if not question: return JsonResponse({'status': 'error'}) if like_type == 'like': question.rating += 1 elif like_type == 'dislike': question.rating -= 1 question.save() return JsonResponse({'status': 'ok'}) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def top(request): return render(request, 'new_questions.html', {'title': 'Топ вопросов', 'questions': paginate(request, models.Question.objects.get_hot()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects. get_hot())}) def new(request): return render(request, 'new_questions.html', {'title': 'Новые', 'questions': paginate(request, models.Question.objects.get_new()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects. get_new())}) def hot(request, id=1): """docstring for Main_menu""" return render(request, 'hot.html', {'users': paginate(request, models. CustomUser.objects.by_rating())[:10], 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'questions': paginate(request, objects_list=models.Question.objects.get_hot()), 'page_objects': paginate(request, objects_list=models.Question.objects.get_hot())}) def profile(request, id): return render(request, 'user_settings.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'profile': get_object_or_404(models.CustomUser, pk=id)}) def user_questions(request, id): """docstring for Main_menu""" return render(request, 'user_question.html', {'questions': paginate( request, models.Question.objects.get_by_user(user_id=id)), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects': paginate(request, models.Question.objects. get_by_user(user_id=id))}) def question_page(request, id): return render(request, 'questions.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'question': get_object_or_404(models.Question, pk=id), 'answers': paginate( request, objects_list=models.Answer.objects.get_hot_for_answer(id)), 'page_objects': paginate(request, objects_list=models.Answer. objects.get_hot_for_answer(id))}) def tag(request, id): return render(request, 'tag_find.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[0:10], 'tags': paginate( request, models.Tag.objects.hottest())[0:10], 'tag': get_object_or_404(models.Tag, pk=id), 'questions': paginate(request, models.Question.objects.get_by_tag(tag_id=id)), 'page_objects': paginate(request, objects_list=models.Question.objects.get_by_tag( tag_id=id))}) <|reserved_special_token_0|> @login_required(login_url='/log_in/') def new_answer(request, id): if models.Question.objects.filter(id=id).exists(): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answeredQuestion = get_object_or_404(models.Question, pk=id) answer = models.Answer.objects.create(author=request.user, create_date=timezone.now(), text=form.cleaned_data[ 'text'], question_id=answeredQuestion.id) answer.save() return redirect('/question/{}/add_answer/'.format(id)) else: form = AnswerForm() return render(request, 'questions.html', {'form': form, 'question': get_object_or_404(models.Question, pk=id), 'answers': paginate( request, models.Answer.objects.get_hot_for_answer(id)), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects': paginate(request, models.Answer.objects. get_hot_for_answer(id))}) else: raise Http404 @login_required(login_url='/log_in/') def ask(request): error = True if request.method == 'POST': firstly = False form = AskForm(request.POST) if form.is_valid(): ques = models.Question.objects.create(author=request.user, create_date=timezone.now(), is_active=True, title=form. cleaned_data['title'], text=form.cleaned_data['text']) ques.save() for tagTitle in form.cleaned_data['tags'].split(): tag = models.Tag.objects.get_or_create(title=tagTitle)[0] ques.tags.add(tag) ques.save() return redirect('/question/{}/'.format(ques.id)) else: error = False else: form = AskForm() firstly = True return render(request, 'new_ask.html', {'firstly': firstly, 'error': error, 'form': form, 'tags': paginate(request, models.Tag.objects. hottest())[:10], 'users': paginate(request, models.CustomUser. objects.by_rating())[:10]}) def signin(request): last_page = request.GET['next'] if last_page == '/logout' or last_page == '/login': last_page = '/' error = False if request.method == 'POST': user = authenticate(username=request.POST['nickname'], password= request.POST['password']) if user is not None: login(request, user) return redirect(last_page) else: error = True return render(request, 'login.html', {'error': error, 'last_page': last_page, 'tags': paginate(request, models.Tag.objects.hottest()), 'users': paginate(request, models.CustomUser.objects.by_rating())}) def registration(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST, request.FILES) print(user_form) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() login(request, user) return redirect(request.GET.get('next') if request.GET.get( 'next') != '' else '/') else: print(user_form.errors) else: user_form = UserRegistrationForm() return render(request, 'registration.html', {'form': user_form}) def signout(request): if not request.user.is_authenticated: raise Http404 logout(request) return redirect('/') <|reserved_special_token_0|> @require_POST def like_question(request): question_id = request.POST.get('question_id', '') like_type = request.POST.get('like_type', '') question = get_object_or_404(Question, pk=question_id) if not question: return JsonResponse({'status': 'error'}) if like_type == 'like': question.rating += 1 elif like_type == 'dislike': question.rating -= 1 question.save() return JsonResponse({'status': 'ok'}) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def index(request): return render(request, 'new_questions.html', {'title': 'Вопросы', 'questions': paginate(request, models.Question.objects.all()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects.all())}) def top(request): return render(request, 'new_questions.html', {'title': 'Топ вопросов', 'questions': paginate(request, models.Question.objects.get_hot()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects. get_hot())}) def new(request): return render(request, 'new_questions.html', {'title': 'Новые', 'questions': paginate(request, models.Question.objects.get_new()), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[: 10], 'page_objects': paginate(request, models.Question.objects. get_new())}) def hot(request, id=1): """docstring for Main_menu""" return render(request, 'hot.html', {'users': paginate(request, models. CustomUser.objects.by_rating())[:10], 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'questions': paginate(request, objects_list=models.Question.objects.get_hot()), 'page_objects': paginate(request, objects_list=models.Question.objects.get_hot())}) def profile(request, id): return render(request, 'user_settings.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'profile': get_object_or_404(models.CustomUser, pk=id)}) def user_questions(request, id): """docstring for Main_menu""" return render(request, 'user_question.html', {'questions': paginate( request, models.Question.objects.get_by_user(user_id=id)), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects': paginate(request, models.Question.objects. get_by_user(user_id=id))}) def question_page(request, id): return render(request, 'questions.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'question': get_object_or_404(models.Question, pk=id), 'answers': paginate( request, objects_list=models.Answer.objects.get_hot_for_answer(id)), 'page_objects': paginate(request, objects_list=models.Answer. objects.get_hot_for_answer(id))}) def tag(request, id): return render(request, 'tag_find.html', {'users': paginate(request, models.CustomUser.objects.by_rating())[0:10], 'tags': paginate( request, models.Tag.objects.hottest())[0:10], 'tag': get_object_or_404(models.Tag, pk=id), 'questions': paginate(request, models.Question.objects.get_by_tag(tag_id=id)), 'page_objects': paginate(request, objects_list=models.Question.objects.get_by_tag( tag_id=id))}) def edit(request): user = get_object_or_404(models.CustomUser, username=request.user) if request.method == 'POST': form = UserSettingsForm(instance=user, data=request.POST, files= request.FILES) if form.is_valid(): form.save() return profile(request, user.id) else: form = UserSettingsForm(instance=user) return render(request, 'edit.html', {'form': form, 'tags': paginate( request, models.Tag.objects.hottest())[:10], 'users': paginate( request, models.CustomUser.objects.by_rating())[:10]}) @login_required(login_url='/log_in/') def new_answer(request, id): if models.Question.objects.filter(id=id).exists(): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answeredQuestion = get_object_or_404(models.Question, pk=id) answer = models.Answer.objects.create(author=request.user, create_date=timezone.now(), text=form.cleaned_data[ 'text'], question_id=answeredQuestion.id) answer.save() return redirect('/question/{}/add_answer/'.format(id)) else: form = AnswerForm() return render(request, 'questions.html', {'form': form, 'question': get_object_or_404(models.Question, pk=id), 'answers': paginate( request, models.Answer.objects.get_hot_for_answer(id)), 'tags': paginate(request, models.Tag.objects.hottest())[:10], 'users': paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects': paginate(request, models.Answer.objects. get_hot_for_answer(id))}) else: raise Http404 @login_required(login_url='/log_in/') def ask(request): error = True if request.method == 'POST': firstly = False form = AskForm(request.POST) if form.is_valid(): ques = models.Question.objects.create(author=request.user, create_date=timezone.now(), is_active=True, title=form. cleaned_data['title'], text=form.cleaned_data['text']) ques.save() for tagTitle in form.cleaned_data['tags'].split(): tag = models.Tag.objects.get_or_create(title=tagTitle)[0] ques.tags.add(tag) ques.save() return redirect('/question/{}/'.format(ques.id)) else: error = False else: form = AskForm() firstly = True return render(request, 'new_ask.html', {'firstly': firstly, 'error': error, 'form': form, 'tags': paginate(request, models.Tag.objects. hottest())[:10], 'users': paginate(request, models.CustomUser. objects.by_rating())[:10]}) def signin(request): last_page = request.GET['next'] if last_page == '/logout' or last_page == '/login': last_page = '/' error = False if request.method == 'POST': user = authenticate(username=request.POST['nickname'], password= request.POST['password']) if user is not None: login(request, user) return redirect(last_page) else: error = True return render(request, 'login.html', {'error': error, 'last_page': last_page, 'tags': paginate(request, models.Tag.objects.hottest()), 'users': paginate(request, models.CustomUser.objects.by_rating())}) def registration(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST, request.FILES) print(user_form) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() login(request, user) return redirect(request.GET.get('next') if request.GET.get( 'next') != '' else '/') else: print(user_form.errors) else: user_form = UserRegistrationForm() return render(request, 'registration.html', {'form': user_form}) def signout(request): if not request.user.is_authenticated: raise Http404 logout(request) return redirect('/') def paginate(request, objects_list): paginator = Paginator(objects_list, 30) page = request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) return objects @require_POST def like_question(request): question_id = request.POST.get('question_id', '') like_type = request.POST.get('like_type', '') question = get_object_or_404(Question, pk=question_id) if not question: return JsonResponse({'status': 'error'}) if like_type == 'like': question.rating += 1 elif like_type == 'dislike': question.rating -= 1 question.save() return JsonResponse({'status': 'ok'}) @require_POST def like_answer(request): answer_id = request.POST.get('answer_id', '') like_type = request.POST.get('like_type', '') answer = get_object_or_404(Answer, pk=answer_id) if not answer: return JsonResponse({'status': 'error'}) if like_type == 'like': answer.rating += 1 elif like_type == 'dislike': answer.rating -= 1 answer.save() return JsonResponse({'status': 'ok'}) @require_POST def approve_answer(request): answer_id = request.POST.get('answer_id', '') answer = get_object_or_404(Answer, pk=answer_id) if not answer: return JsonResponse({'status': 'error'}) answer.approved = not answer.approved answer.save() return JsonResponse({'status': 'ok'}) <|reserved_special_token_1|> # from django.shortcuts import render # from django.http import HttpResponse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.views import generic from django.urls import reverse_lazy from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_exempt import json from . import models from django.utils import timezone from questions.forms import UserRegistrationForm, UserLoginForm, UserSettingsForm, AskForm, AnswerForm, UserForm # from .models import Post # Create your views here. def index(request): return render(request, 'new_questions.html', { 'title': 'Вопросы', 'questions': paginate(request, models.Question.objects.all()), 'tags' : paginate(request, models.Tag.objects.hottest())[:10], 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects' : paginate(request, models.Question.objects.all()), }) def top(request): return render(request, 'new_questions.html', { 'title': 'Топ вопросов', 'questions': paginate(request, models.Question.objects.get_hot()), 'tags' : paginate(request, models.Tag.objects.hottest())[:10], 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects' : paginate(request, models.Question.objects.get_hot()), }) def new(request): return render(request, 'new_questions.html', { 'title': 'Новые', 'questions': paginate(request, models.Question.objects.get_new()), 'tags' : paginate(request, models.Tag.objects.hottest())[:10], 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects' : paginate(request, models.Question.objects.get_new()), }) def hot(request, id=1): """docstring for Main_menu""" return render(request, "hot.html", { 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags' : paginate(request, models.Tag.objects.hottest())[:10], "questions" : paginate(request, objects_list = models.Question.objects.get_hot()), "page_objects" : paginate(request, objects_list = models.Question.objects.get_hot()), }) def profile(request, id): return render(request, "user_settings.html", { 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags' : paginate(request, models.Tag.objects.hottest())[:10], "profile": get_object_or_404(models.CustomUser, pk=id), }) def user_questions(request, id): #Переделай вид страницы! не красиво! """docstring for Main_menu""" return render(request, "user_question.html", { 'questions': paginate(request, models.Question.objects.get_by_user(user_id=id)), 'tags' : paginate(request, models.Tag.objects.hottest())[:10], 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects' : paginate(request, models.Question.objects.get_by_user(user_id=id)), }) def question_page(request, id): return render(request, "questions.html", { 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'tags' : paginate(request, models.Tag.objects.hottest())[:10], "question": get_object_or_404(models.Question, pk=id) , "answers": paginate(request, objects_list = models.Answer.objects.get_hot_for_answer(id)), "page_objects": paginate(request, objects_list = models.Answer.objects.get_hot_for_answer(id)), }) def tag(request, id): return render(request, 'tag_find.html', { 'users' : paginate(request, models.CustomUser.objects.by_rating())[0:10], 'tags' : paginate(request, models.Tag.objects.hottest())[0:10], 'tag' : get_object_or_404(models.Tag, pk=id) , 'questions': paginate(request, models.Question.objects.get_by_tag(tag_id=id)), "page_objects": paginate(request, objects_list = models.Question.objects.get_by_tag(tag_id=id)), }) def edit(request): user = get_object_or_404(models.CustomUser, username=request.user) if request.method == 'POST': form = UserSettingsForm(instance=user, data=request.POST, files=request.FILES ) if form.is_valid(): form.save() return profile(request, user.id) else: form = UserSettingsForm(instance=user) return render(request, 'edit.html', { 'form': form, 'tags' : paginate(request, models.Tag.objects.hottest())[:10], 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], }) @login_required(login_url='/log_in/') def new_answer(request, id): if models.Question.objects.filter(id=id).exists(): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): #answeredQuestion = Question.objects.get_by_id(id)[0] answeredQuestion = get_object_or_404(models.Question, pk=id) answer = models.Answer.objects.create(author=request.user, create_date=timezone.now(), text=form.cleaned_data['text'], question_id=answeredQuestion.id) answer.save() return redirect('/question/{}/add_answer/'.format(id)) else: form = AnswerForm() #return render(request, 'question/new_answer.html', {'form': form}) return render(request, 'questions.html', { 'form': form, 'question': get_object_or_404(models.Question, pk=id), 'answers' : paginate(request, models.Answer.objects.get_hot_for_answer(id)), 'tags' : paginate(request, models.Tag.objects.hottest())[:10], 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], 'page_objects' : paginate(request, models.Answer.objects.get_hot_for_answer(id)), }) else: raise Http404 @login_required(login_url='/log_in/') def ask(request): error = True if request.method == 'POST': firstly = False form = AskForm(request.POST) if form.is_valid(): ques = models.Question.objects.create(author=request.user, create_date=timezone.now(), is_active=True, title=form.cleaned_data['title'], text=form.cleaned_data['text']) ques.save() for tagTitle in form.cleaned_data['tags'].split(): tag = models.Tag.objects.get_or_create(title=tagTitle)[0] ques.tags.add(tag) ques.save() #return question(request, ques.id) return redirect('/question/{}/'.format(ques.id)) else: error = False else: form = AskForm() firstly = True return render(request, 'new_ask.html', { 'firstly': firstly, 'error': error, 'form': form, 'tags' : paginate(request, models.Tag.objects.hottest())[:10], 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10], }) def signin(request): last_page = request.GET['next'] if last_page == '/logout' or last_page == '/login': last_page = '/' error = False if request.method == 'POST': user = authenticate(username=request.POST['nickname'], password=request.POST['password']) if user is not None: login(request, user) # Авторизуем пользователя return redirect(last_page) else: error = True return render(request, 'login.html', {'error': error, 'last_page': last_page, 'tags' : paginate(request, models.Tag.objects.hottest()), 'users' : paginate(request, models.CustomUser.objects.by_rating()), }) def registration(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST, request.FILES) print(user_form) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() login(request, user) return redirect(request.GET.get('next') if request.GET.get('next') != '' else '/') else: print(user_form.errors) else: user_form = UserRegistrationForm() return render(request,'registration.html', {'form':user_form,}) def signout(request): if not request.user.is_authenticated: raise Http404 logout(request) #return redirect(request.GET['from']) return redirect('/') def paginate(request, objects_list): paginator = Paginator(objects_list, 30) page = request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) return objects @require_POST def like_question(request): question_id = request.POST.get('question_id', '') like_type = request.POST.get('like_type', '') question =get_object_or_404(Question, pk=question_id) if not question: return JsonResponse({"status": "error"}) if (like_type == 'like'): question.rating += 1 elif (like_type == 'dislike'): question.rating -= 1 question.save() return JsonResponse({"status": "ok"}) @require_POST def like_answer(request): answer_id = request.POST.get('answer_id', '') like_type = request.POST.get('like_type', '') answer =get_object_or_404(Answer, pk=answer_id) if not answer: return JsonResponse({"status": "error"}) if (like_type == 'like'): answer.rating += 1 elif (like_type == 'dislike'): answer.rating -= 1 answer.save() return JsonResponse({"status": "ok"}) @require_POST def approve_answer(request): answer_id = request.POST.get('answer_id', '') answer =get_object_or_404(Answer, pk=answer_id) if not answer: return JsonResponse({"status": "error"}) answer.approved = not answer.approved answer.save() return JsonResponse({"status": "ok"})
flexible
{ "blob_id": "c4b4585501319fd8a8106c91751bb1408912827a", "index": 3180, "step-1": "<mask token>\n\n\ndef top(request):\n return render(request, 'new_questions.html', {'title': 'Топ вопросов',\n 'questions': paginate(request, models.Question.objects.get_hot()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.\n get_hot())})\n\n\n<mask token>\n\n\ndef hot(request, id=1):\n \"\"\"docstring for Main_menu\"\"\"\n return render(request, 'hot.html', {'users': paginate(request, models.\n CustomUser.objects.by_rating())[:10], 'tags': paginate(request,\n models.Tag.objects.hottest())[:10], 'questions': paginate(request,\n objects_list=models.Question.objects.get_hot()), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_hot())})\n\n\n<mask token>\n\n\ndef question_page(request, id):\n return render(request, 'questions.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'question':\n get_object_or_404(models.Question, pk=id), 'answers': paginate(\n request, objects_list=models.Answer.objects.get_hot_for_answer(id)),\n 'page_objects': paginate(request, objects_list=models.Answer.\n objects.get_hot_for_answer(id))})\n\n\ndef tag(request, id):\n return render(request, 'tag_find.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[0:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[0:10], 'tag':\n get_object_or_404(models.Tag, pk=id), 'questions': paginate(request,\n models.Question.objects.get_by_tag(tag_id=id)), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_by_tag(\n tag_id=id))})\n\n\n<mask token>\n\n\n@login_required(login_url='/log_in/')\ndef ask(request):\n error = True\n if request.method == 'POST':\n firstly = False\n form = AskForm(request.POST)\n if form.is_valid():\n ques = models.Question.objects.create(author=request.user,\n create_date=timezone.now(), is_active=True, title=form.\n cleaned_data['title'], text=form.cleaned_data['text'])\n ques.save()\n for tagTitle in form.cleaned_data['tags'].split():\n tag = models.Tag.objects.get_or_create(title=tagTitle)[0]\n ques.tags.add(tag)\n ques.save()\n return redirect('/question/{}/'.format(ques.id))\n else:\n error = False\n else:\n form = AskForm()\n firstly = True\n return render(request, 'new_ask.html', {'firstly': firstly, 'error':\n error, 'form': form, 'tags': paginate(request, models.Tag.objects.\n hottest())[:10], 'users': paginate(request, models.CustomUser.\n objects.by_rating())[:10]})\n\n\ndef signin(request):\n last_page = request.GET['next']\n if last_page == '/logout' or last_page == '/login':\n last_page = '/'\n error = False\n if request.method == 'POST':\n user = authenticate(username=request.POST['nickname'], password=\n request.POST['password'])\n if user is not None:\n login(request, user)\n return redirect(last_page)\n else:\n error = True\n return render(request, 'login.html', {'error': error, 'last_page':\n last_page, 'tags': paginate(request, models.Tag.objects.hottest()),\n 'users': paginate(request, models.CustomUser.objects.by_rating())})\n\n\n<mask token>\n\n\ndef signout(request):\n if not request.user.is_authenticated:\n raise Http404\n logout(request)\n return redirect('/')\n\n\n<mask token>\n\n\n@require_POST\ndef like_question(request):\n question_id = request.POST.get('question_id', '')\n like_type = request.POST.get('like_type', '')\n question = get_object_or_404(Question, pk=question_id)\n if not question:\n return JsonResponse({'status': 'error'})\n if like_type == 'like':\n question.rating += 1\n elif like_type == 'dislike':\n question.rating -= 1\n question.save()\n return JsonResponse({'status': 'ok'})\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef top(request):\n return render(request, 'new_questions.html', {'title': 'Топ вопросов',\n 'questions': paginate(request, models.Question.objects.get_hot()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.\n get_hot())})\n\n\ndef new(request):\n return render(request, 'new_questions.html', {'title': 'Новые',\n 'questions': paginate(request, models.Question.objects.get_new()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.\n get_new())})\n\n\ndef hot(request, id=1):\n \"\"\"docstring for Main_menu\"\"\"\n return render(request, 'hot.html', {'users': paginate(request, models.\n CustomUser.objects.by_rating())[:10], 'tags': paginate(request,\n models.Tag.objects.hottest())[:10], 'questions': paginate(request,\n objects_list=models.Question.objects.get_hot()), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_hot())})\n\n\ndef profile(request, id):\n return render(request, 'user_settings.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'profile':\n get_object_or_404(models.CustomUser, pk=id)})\n\n\n<mask token>\n\n\ndef question_page(request, id):\n return render(request, 'questions.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'question':\n get_object_or_404(models.Question, pk=id), 'answers': paginate(\n request, objects_list=models.Answer.objects.get_hot_for_answer(id)),\n 'page_objects': paginate(request, objects_list=models.Answer.\n objects.get_hot_for_answer(id))})\n\n\ndef tag(request, id):\n return render(request, 'tag_find.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[0:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[0:10], 'tag':\n get_object_or_404(models.Tag, pk=id), 'questions': paginate(request,\n models.Question.objects.get_by_tag(tag_id=id)), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_by_tag(\n tag_id=id))})\n\n\n<mask token>\n\n\n@login_required(login_url='/log_in/')\ndef new_answer(request, id):\n if models.Question.objects.filter(id=id).exists():\n if request.method == 'POST':\n form = AnswerForm(request.POST)\n if form.is_valid():\n answeredQuestion = get_object_or_404(models.Question, pk=id)\n answer = models.Answer.objects.create(author=request.user,\n create_date=timezone.now(), text=form.cleaned_data[\n 'text'], question_id=answeredQuestion.id)\n answer.save()\n return redirect('/question/{}/add_answer/'.format(id))\n else:\n form = AnswerForm()\n return render(request, 'questions.html', {'form': form, 'question':\n get_object_or_404(models.Question, pk=id), 'answers': paginate(\n request, models.Answer.objects.get_hot_for_answer(id)), 'tags':\n paginate(request, models.Tag.objects.hottest())[:10], 'users':\n paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects': paginate(request, models.Answer.objects.\n get_hot_for_answer(id))})\n else:\n raise Http404\n\n\n@login_required(login_url='/log_in/')\ndef ask(request):\n error = True\n if request.method == 'POST':\n firstly = False\n form = AskForm(request.POST)\n if form.is_valid():\n ques = models.Question.objects.create(author=request.user,\n create_date=timezone.now(), is_active=True, title=form.\n cleaned_data['title'], text=form.cleaned_data['text'])\n ques.save()\n for tagTitle in form.cleaned_data['tags'].split():\n tag = models.Tag.objects.get_or_create(title=tagTitle)[0]\n ques.tags.add(tag)\n ques.save()\n return redirect('/question/{}/'.format(ques.id))\n else:\n error = False\n else:\n form = AskForm()\n firstly = True\n return render(request, 'new_ask.html', {'firstly': firstly, 'error':\n error, 'form': form, 'tags': paginate(request, models.Tag.objects.\n hottest())[:10], 'users': paginate(request, models.CustomUser.\n objects.by_rating())[:10]})\n\n\ndef signin(request):\n last_page = request.GET['next']\n if last_page == '/logout' or last_page == '/login':\n last_page = '/'\n error = False\n if request.method == 'POST':\n user = authenticate(username=request.POST['nickname'], password=\n request.POST['password'])\n if user is not None:\n login(request, user)\n return redirect(last_page)\n else:\n error = True\n return render(request, 'login.html', {'error': error, 'last_page':\n last_page, 'tags': paginate(request, models.Tag.objects.hottest()),\n 'users': paginate(request, models.CustomUser.objects.by_rating())})\n\n\ndef registration(request):\n if request.method == 'POST':\n user_form = UserRegistrationForm(request.POST, request.FILES)\n print(user_form)\n if user_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n login(request, user)\n return redirect(request.GET.get('next') if request.GET.get(\n 'next') != '' else '/')\n else:\n print(user_form.errors)\n else:\n user_form = UserRegistrationForm()\n return render(request, 'registration.html', {'form': user_form})\n\n\ndef signout(request):\n if not request.user.is_authenticated:\n raise Http404\n logout(request)\n return redirect('/')\n\n\n<mask token>\n\n\n@require_POST\ndef like_question(request):\n question_id = request.POST.get('question_id', '')\n like_type = request.POST.get('like_type', '')\n question = get_object_or_404(Question, pk=question_id)\n if not question:\n return JsonResponse({'status': 'error'})\n if like_type == 'like':\n question.rating += 1\n elif like_type == 'dislike':\n question.rating -= 1\n question.save()\n return JsonResponse({'status': 'ok'})\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef top(request):\n return render(request, 'new_questions.html', {'title': 'Топ вопросов',\n 'questions': paginate(request, models.Question.objects.get_hot()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.\n get_hot())})\n\n\ndef new(request):\n return render(request, 'new_questions.html', {'title': 'Новые',\n 'questions': paginate(request, models.Question.objects.get_new()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.\n get_new())})\n\n\ndef hot(request, id=1):\n \"\"\"docstring for Main_menu\"\"\"\n return render(request, 'hot.html', {'users': paginate(request, models.\n CustomUser.objects.by_rating())[:10], 'tags': paginate(request,\n models.Tag.objects.hottest())[:10], 'questions': paginate(request,\n objects_list=models.Question.objects.get_hot()), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_hot())})\n\n\ndef profile(request, id):\n return render(request, 'user_settings.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'profile':\n get_object_or_404(models.CustomUser, pk=id)})\n\n\ndef user_questions(request, id):\n \"\"\"docstring for Main_menu\"\"\"\n return render(request, 'user_question.html', {'questions': paginate(\n request, models.Question.objects.get_by_user(user_id=id)), 'tags':\n paginate(request, models.Tag.objects.hottest())[:10], 'users':\n paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects': paginate(request, models.Question.objects.\n get_by_user(user_id=id))})\n\n\ndef question_page(request, id):\n return render(request, 'questions.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'question':\n get_object_or_404(models.Question, pk=id), 'answers': paginate(\n request, objects_list=models.Answer.objects.get_hot_for_answer(id)),\n 'page_objects': paginate(request, objects_list=models.Answer.\n objects.get_hot_for_answer(id))})\n\n\ndef tag(request, id):\n return render(request, 'tag_find.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[0:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[0:10], 'tag':\n get_object_or_404(models.Tag, pk=id), 'questions': paginate(request,\n models.Question.objects.get_by_tag(tag_id=id)), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_by_tag(\n tag_id=id))})\n\n\n<mask token>\n\n\n@login_required(login_url='/log_in/')\ndef new_answer(request, id):\n if models.Question.objects.filter(id=id).exists():\n if request.method == 'POST':\n form = AnswerForm(request.POST)\n if form.is_valid():\n answeredQuestion = get_object_or_404(models.Question, pk=id)\n answer = models.Answer.objects.create(author=request.user,\n create_date=timezone.now(), text=form.cleaned_data[\n 'text'], question_id=answeredQuestion.id)\n answer.save()\n return redirect('/question/{}/add_answer/'.format(id))\n else:\n form = AnswerForm()\n return render(request, 'questions.html', {'form': form, 'question':\n get_object_or_404(models.Question, pk=id), 'answers': paginate(\n request, models.Answer.objects.get_hot_for_answer(id)), 'tags':\n paginate(request, models.Tag.objects.hottest())[:10], 'users':\n paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects': paginate(request, models.Answer.objects.\n get_hot_for_answer(id))})\n else:\n raise Http404\n\n\n@login_required(login_url='/log_in/')\ndef ask(request):\n error = True\n if request.method == 'POST':\n firstly = False\n form = AskForm(request.POST)\n if form.is_valid():\n ques = models.Question.objects.create(author=request.user,\n create_date=timezone.now(), is_active=True, title=form.\n cleaned_data['title'], text=form.cleaned_data['text'])\n ques.save()\n for tagTitle in form.cleaned_data['tags'].split():\n tag = models.Tag.objects.get_or_create(title=tagTitle)[0]\n ques.tags.add(tag)\n ques.save()\n return redirect('/question/{}/'.format(ques.id))\n else:\n error = False\n else:\n form = AskForm()\n firstly = True\n return render(request, 'new_ask.html', {'firstly': firstly, 'error':\n error, 'form': form, 'tags': paginate(request, models.Tag.objects.\n hottest())[:10], 'users': paginate(request, models.CustomUser.\n objects.by_rating())[:10]})\n\n\ndef signin(request):\n last_page = request.GET['next']\n if last_page == '/logout' or last_page == '/login':\n last_page = '/'\n error = False\n if request.method == 'POST':\n user = authenticate(username=request.POST['nickname'], password=\n request.POST['password'])\n if user is not None:\n login(request, user)\n return redirect(last_page)\n else:\n error = True\n return render(request, 'login.html', {'error': error, 'last_page':\n last_page, 'tags': paginate(request, models.Tag.objects.hottest()),\n 'users': paginate(request, models.CustomUser.objects.by_rating())})\n\n\ndef registration(request):\n if request.method == 'POST':\n user_form = UserRegistrationForm(request.POST, request.FILES)\n print(user_form)\n if user_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n login(request, user)\n return redirect(request.GET.get('next') if request.GET.get(\n 'next') != '' else '/')\n else:\n print(user_form.errors)\n else:\n user_form = UserRegistrationForm()\n return render(request, 'registration.html', {'form': user_form})\n\n\ndef signout(request):\n if not request.user.is_authenticated:\n raise Http404\n logout(request)\n return redirect('/')\n\n\n<mask token>\n\n\n@require_POST\ndef like_question(request):\n question_id = request.POST.get('question_id', '')\n like_type = request.POST.get('like_type', '')\n question = get_object_or_404(Question, pk=question_id)\n if not question:\n return JsonResponse({'status': 'error'})\n if like_type == 'like':\n question.rating += 1\n elif like_type == 'dislike':\n question.rating -= 1\n question.save()\n return JsonResponse({'status': 'ok'})\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef index(request):\n return render(request, 'new_questions.html', {'title': 'Вопросы',\n 'questions': paginate(request, models.Question.objects.all()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.all())})\n\n\ndef top(request):\n return render(request, 'new_questions.html', {'title': 'Топ вопросов',\n 'questions': paginate(request, models.Question.objects.get_hot()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.\n get_hot())})\n\n\ndef new(request):\n return render(request, 'new_questions.html', {'title': 'Новые',\n 'questions': paginate(request, models.Question.objects.get_new()),\n 'tags': paginate(request, models.Tag.objects.hottest())[:10],\n 'users': paginate(request, models.CustomUser.objects.by_rating())[:\n 10], 'page_objects': paginate(request, models.Question.objects.\n get_new())})\n\n\ndef hot(request, id=1):\n \"\"\"docstring for Main_menu\"\"\"\n return render(request, 'hot.html', {'users': paginate(request, models.\n CustomUser.objects.by_rating())[:10], 'tags': paginate(request,\n models.Tag.objects.hottest())[:10], 'questions': paginate(request,\n objects_list=models.Question.objects.get_hot()), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_hot())})\n\n\ndef profile(request, id):\n return render(request, 'user_settings.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'profile':\n get_object_or_404(models.CustomUser, pk=id)})\n\n\ndef user_questions(request, id):\n \"\"\"docstring for Main_menu\"\"\"\n return render(request, 'user_question.html', {'questions': paginate(\n request, models.Question.objects.get_by_user(user_id=id)), 'tags':\n paginate(request, models.Tag.objects.hottest())[:10], 'users':\n paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects': paginate(request, models.Question.objects.\n get_by_user(user_id=id))})\n\n\ndef question_page(request, id):\n return render(request, 'questions.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'question':\n get_object_or_404(models.Question, pk=id), 'answers': paginate(\n request, objects_list=models.Answer.objects.get_hot_for_answer(id)),\n 'page_objects': paginate(request, objects_list=models.Answer.\n objects.get_hot_for_answer(id))})\n\n\ndef tag(request, id):\n return render(request, 'tag_find.html', {'users': paginate(request,\n models.CustomUser.objects.by_rating())[0:10], 'tags': paginate(\n request, models.Tag.objects.hottest())[0:10], 'tag':\n get_object_or_404(models.Tag, pk=id), 'questions': paginate(request,\n models.Question.objects.get_by_tag(tag_id=id)), 'page_objects':\n paginate(request, objects_list=models.Question.objects.get_by_tag(\n tag_id=id))})\n\n\ndef edit(request):\n user = get_object_or_404(models.CustomUser, username=request.user)\n if request.method == 'POST':\n form = UserSettingsForm(instance=user, data=request.POST, files=\n request.FILES)\n if form.is_valid():\n form.save()\n return profile(request, user.id)\n else:\n form = UserSettingsForm(instance=user)\n return render(request, 'edit.html', {'form': form, 'tags': paginate(\n request, models.Tag.objects.hottest())[:10], 'users': paginate(\n request, models.CustomUser.objects.by_rating())[:10]})\n\n\n@login_required(login_url='/log_in/')\ndef new_answer(request, id):\n if models.Question.objects.filter(id=id).exists():\n if request.method == 'POST':\n form = AnswerForm(request.POST)\n if form.is_valid():\n answeredQuestion = get_object_or_404(models.Question, pk=id)\n answer = models.Answer.objects.create(author=request.user,\n create_date=timezone.now(), text=form.cleaned_data[\n 'text'], question_id=answeredQuestion.id)\n answer.save()\n return redirect('/question/{}/add_answer/'.format(id))\n else:\n form = AnswerForm()\n return render(request, 'questions.html', {'form': form, 'question':\n get_object_or_404(models.Question, pk=id), 'answers': paginate(\n request, models.Answer.objects.get_hot_for_answer(id)), 'tags':\n paginate(request, models.Tag.objects.hottest())[:10], 'users':\n paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects': paginate(request, models.Answer.objects.\n get_hot_for_answer(id))})\n else:\n raise Http404\n\n\n@login_required(login_url='/log_in/')\ndef ask(request):\n error = True\n if request.method == 'POST':\n firstly = False\n form = AskForm(request.POST)\n if form.is_valid():\n ques = models.Question.objects.create(author=request.user,\n create_date=timezone.now(), is_active=True, title=form.\n cleaned_data['title'], text=form.cleaned_data['text'])\n ques.save()\n for tagTitle in form.cleaned_data['tags'].split():\n tag = models.Tag.objects.get_or_create(title=tagTitle)[0]\n ques.tags.add(tag)\n ques.save()\n return redirect('/question/{}/'.format(ques.id))\n else:\n error = False\n else:\n form = AskForm()\n firstly = True\n return render(request, 'new_ask.html', {'firstly': firstly, 'error':\n error, 'form': form, 'tags': paginate(request, models.Tag.objects.\n hottest())[:10], 'users': paginate(request, models.CustomUser.\n objects.by_rating())[:10]})\n\n\ndef signin(request):\n last_page = request.GET['next']\n if last_page == '/logout' or last_page == '/login':\n last_page = '/'\n error = False\n if request.method == 'POST':\n user = authenticate(username=request.POST['nickname'], password=\n request.POST['password'])\n if user is not None:\n login(request, user)\n return redirect(last_page)\n else:\n error = True\n return render(request, 'login.html', {'error': error, 'last_page':\n last_page, 'tags': paginate(request, models.Tag.objects.hottest()),\n 'users': paginate(request, models.CustomUser.objects.by_rating())})\n\n\ndef registration(request):\n if request.method == 'POST':\n user_form = UserRegistrationForm(request.POST, request.FILES)\n print(user_form)\n if user_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n login(request, user)\n return redirect(request.GET.get('next') if request.GET.get(\n 'next') != '' else '/')\n else:\n print(user_form.errors)\n else:\n user_form = UserRegistrationForm()\n return render(request, 'registration.html', {'form': user_form})\n\n\ndef signout(request):\n if not request.user.is_authenticated:\n raise Http404\n logout(request)\n return redirect('/')\n\n\ndef paginate(request, objects_list):\n paginator = Paginator(objects_list, 30)\n page = request.GET.get('page')\n try:\n objects = paginator.page(page)\n except PageNotAnInteger:\n objects = paginator.page(1)\n except EmptyPage:\n objects = paginator.page(paginator.num_pages)\n return objects\n\n\n@require_POST\ndef like_question(request):\n question_id = request.POST.get('question_id', '')\n like_type = request.POST.get('like_type', '')\n question = get_object_or_404(Question, pk=question_id)\n if not question:\n return JsonResponse({'status': 'error'})\n if like_type == 'like':\n question.rating += 1\n elif like_type == 'dislike':\n question.rating -= 1\n question.save()\n return JsonResponse({'status': 'ok'})\n\n\n@require_POST\ndef like_answer(request):\n answer_id = request.POST.get('answer_id', '')\n like_type = request.POST.get('like_type', '')\n answer = get_object_or_404(Answer, pk=answer_id)\n if not answer:\n return JsonResponse({'status': 'error'})\n if like_type == 'like':\n answer.rating += 1\n elif like_type == 'dislike':\n answer.rating -= 1\n answer.save()\n return JsonResponse({'status': 'ok'})\n\n\n@require_POST\ndef approve_answer(request):\n answer_id = request.POST.get('answer_id', '')\n answer = get_object_or_404(Answer, pk=answer_id)\n if not answer:\n return JsonResponse({'status': 'error'})\n answer.approved = not answer.approved\n answer.save()\n return JsonResponse({'status': 'ok'})\n", "step-5": "# from django.shortcuts import render\n# from django.http import HttpResponse\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.views import generic\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_POST\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\nfrom . import models\nfrom django.utils import timezone\nfrom questions.forms import UserRegistrationForm, UserLoginForm, UserSettingsForm, AskForm, AnswerForm, UserForm\n\n# from .models import Post \n\n# Create your views here.\n\t\t\ndef index(request):\n return render(request, 'new_questions.html', {\n 'title': 'Вопросы',\n 'questions': paginate(request, models.Question.objects.all()),\n 'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects' : paginate(request, models.Question.objects.all()),\n })\n\ndef top(request):\n return render(request, 'new_questions.html', {\n 'title': 'Топ вопросов',\n 'questions': paginate(request, models.Question.objects.get_hot()),\n 'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects' : paginate(request, models.Question.objects.get_hot()),\n })\n\ndef new(request):\n return render(request, 'new_questions.html', {\n 'title': 'Новые',\n 'questions': paginate(request, models.Question.objects.get_new()),\n 'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects' : paginate(request, models.Question.objects.get_new()),\n })\n\n\ndef hot(request, id=1):\n\t\"\"\"docstring for Main_menu\"\"\"\n\treturn render(request, \"hot.html\", {\n\t\t'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n\t\t'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n\t\t\"questions\" : paginate(request, objects_list = models.Question.objects.get_hot()),\n\t\t\"page_objects\" : paginate(request, objects_list = models.Question.objects.get_hot()),\n\t\t})\ndef profile(request, id):\n\treturn render(request, \"user_settings.html\", {\n\t\t'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n\t\t'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n\t\t\"profile\": get_object_or_404(models.CustomUser, pk=id),\n\t\t})\n\ndef user_questions(request, id):\t#Переделай вид страницы! не красиво!\n\t\"\"\"docstring for Main_menu\"\"\"\n\treturn render(request, \"user_question.html\", {\n\t\t'questions': paginate(request, models.Question.objects.get_by_user(user_id=id)),\n 'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects' : paginate(request, models.Question.objects.get_by_user(user_id=id)),\n\t\t})\n\ndef question_page(request, id):\n\treturn render(request, \"questions.html\", {\n\t\t'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n\t\t'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n\t\t\"question\": get_object_or_404(models.Question, pk=id) ,\n\t\t\"answers\": paginate(request, objects_list = models.Answer.objects.get_hot_for_answer(id)),\n\t\t\"page_objects\": paginate(request, objects_list = models.Answer.objects.get_hot_for_answer(id)),\n\t\t})\n\ndef tag(request, id):\n return render(request, 'tag_find.html', {\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[0:10],\n 'tags' : paginate(request, models.Tag.objects.hottest())[0:10],\n 'tag' : get_object_or_404(models.Tag, pk=id) ,\n 'questions': paginate(request, models.Question.objects.get_by_tag(tag_id=id)),\n \"page_objects\": paginate(request, objects_list = models.Question.objects.get_by_tag(tag_id=id)),\n })\n\n\ndef edit(request):\n user = get_object_or_404(models.CustomUser, username=request.user)\n\n if request.method == 'POST':\n form = UserSettingsForm(instance=user,\n data=request.POST,\n files=request.FILES\n )\n if form.is_valid():\n form.save()\n return profile(request, user.id)\n else:\n form = UserSettingsForm(instance=user)\n\n return render(request, 'edit.html', {\n 'form': form,\n 'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n })\n\n@login_required(login_url='/log_in/')\ndef new_answer(request, id):\n if models.Question.objects.filter(id=id).exists():\n if request.method == 'POST':\n form = AnswerForm(request.POST)\n if form.is_valid():\n #answeredQuestion = Question.objects.get_by_id(id)[0]\n answeredQuestion = get_object_or_404(models.Question, pk=id)\n answer = models.Answer.objects.create(author=request.user,\n create_date=timezone.now(),\n text=form.cleaned_data['text'],\n question_id=answeredQuestion.id)\n answer.save()\n return redirect('/question/{}/add_answer/'.format(id))\n else:\n form = AnswerForm()\n #return render(request, 'question/new_answer.html', {'form': form})\n return render(request, 'questions.html', {\n 'form': form,\n 'question': get_object_or_404(models.Question, pk=id),\n 'answers' : paginate(request, models.Answer.objects.get_hot_for_answer(id)),\n 'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n 'page_objects' : paginate(request, models.Answer.objects.get_hot_for_answer(id)),\n })\n else:\n raise Http404\n\n@login_required(login_url='/log_in/')\ndef ask(request):\n error = True\n if request.method == 'POST':\n firstly = False\n form = AskForm(request.POST)\n if form.is_valid():\n ques = models.Question.objects.create(author=request.user,\n create_date=timezone.now(),\n is_active=True,\n title=form.cleaned_data['title'],\n text=form.cleaned_data['text'])\n ques.save()\n\n for tagTitle in form.cleaned_data['tags'].split():\n tag = models.Tag.objects.get_or_create(title=tagTitle)[0]\n ques.tags.add(tag)\n ques.save()\n #return question(request, ques.id)\n return redirect('/question/{}/'.format(ques.id))\n else:\n error = False\n else:\n form = AskForm()\n firstly = True\n return render(request, 'new_ask.html', {\n 'firstly': firstly,\n 'error': error,\n 'form': form,\n 'tags' : paginate(request, models.Tag.objects.hottest())[:10],\n 'users' : paginate(request, models.CustomUser.objects.by_rating())[:10],\n })\n\ndef signin(request):\n last_page = request.GET['next']\n if last_page == '/logout' or last_page == '/login':\n last_page = '/'\n error = False\n if request.method == 'POST':\n user = authenticate(username=request.POST['nickname'], password=request.POST['password'])\n if user is not None:\n login(request, user) # Авторизуем пользователя\n return redirect(last_page)\n else:\n error = True\n return render(request, 'login.html',\n {'error': error,\n 'last_page': last_page,\n 'tags' : paginate(request, models.Tag.objects.hottest()),\n 'users' : paginate(request, models.CustomUser.objects.by_rating()),\n })\n\ndef registration(request):\n if request.method == 'POST':\n user_form = UserRegistrationForm(request.POST, request.FILES)\n print(user_form)\n if user_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n login(request, user)\n return redirect(request.GET.get('next') if request.GET.get('next') != '' else '/')\n else:\n print(user_form.errors)\n else:\n user_form = UserRegistrationForm()\n return render(request,'registration.html',\n {'form':user_form,})\n\ndef signout(request):\n if not request.user.is_authenticated:\n raise Http404\n logout(request)\n #return redirect(request.GET['from'])\n return redirect('/')\n\n\ndef paginate(request, objects_list):\n paginator = Paginator(objects_list, 30)\n page = request.GET.get('page')\n try:\n objects = paginator.page(page)\n except PageNotAnInteger:\n objects = paginator.page(1)\n except EmptyPage:\n objects = paginator.page(paginator.num_pages)\n\n return objects\n\n@require_POST\ndef like_question(request):\n question_id = request.POST.get('question_id', '')\n like_type = request.POST.get('like_type', '')\n question =get_object_or_404(Question, pk=question_id)\n if not question:\n return JsonResponse({\"status\": \"error\"})\n\n if (like_type == 'like'):\n question.rating += 1\n elif (like_type == 'dislike'):\n question.rating -= 1\n question.save()\n\n return JsonResponse({\"status\": \"ok\"})\n\n@require_POST\ndef like_answer(request):\n answer_id = request.POST.get('answer_id', '')\n like_type = request.POST.get('like_type', '')\n answer =get_object_or_404(Answer, pk=answer_id)\n if not answer:\n return JsonResponse({\"status\": \"error\"})\n\n if (like_type == 'like'):\n answer.rating += 1\n elif (like_type == 'dislike'):\n answer.rating -= 1\n answer.save()\n\n return JsonResponse({\"status\": \"ok\"})\n\n\n@require_POST\ndef approve_answer(request):\n answer_id = request.POST.get('answer_id', '')\n answer =get_object_or_404(Answer, pk=answer_id)\n if not answer:\n return JsonResponse({\"status\": \"error\"})\n\n answer.approved = not answer.approved\n answer.save()\n\n return JsonResponse({\"status\": \"ok\"})", "step-ids": [ 8, 12, 13, 18, 20 ] }
[ 8, 12, 13, 18, 20 ]
<|reserved_special_token_0|> class OrderForm(ModelForm): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class Meta: model = Order fields = 'stock', 'order', 'volume', 'price', 'trader', 'market' class UploadFileForm(Form): file = FileField() <|reserved_special_token_1|> <|reserved_special_token_0|> class OrderForm(ModelForm): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def clean(self): """Validates the data. Ensures the trader has enough cash or shares to complete the requested order.""" cleaned_data = self.cleaned_data if cleaned_data.get('order') and cleaned_data.get('stock' ) and cleaned_data.get('volume') and cleaned_data.get('price'): t = cleaned_data['trader'] if cleaned_data['order'] == 'B': open_orders = Order.objects.filter(trader=t, order='B', completed=False) open_order_value = float(sum([(o.volume * o.price) for o in open_orders])) open_order_value += int(cleaned_data['volume']) * float( cleaned_data['price']) if open_order_value > t.cash: raise ValidationError("You don't have enough cash!") elif cleaned_data['order'] == 'S': open_orders = sum(Order.objects.filter(trader=t, order='S', stock=cleaned_data['stock'], completed=False). values_list('volume', flat=True)) open_orders += cleaned_data['volume'] if open_orders > t.holding_set.get(stock=cleaned_data['stock'] ).shares: raise ValidationError("You don't have enough shares!") return cleaned_data class Meta: model = Order fields = 'stock', 'order', 'volume', 'price', 'trader', 'market' class UploadFileForm(Form): file = FileField() <|reserved_special_token_1|> <|reserved_special_token_0|> class OrderForm(ModelForm): <|reserved_special_token_0|> PRICE_CHOICES = [(i * 0.01, str(i * 0.01)) for i in range(1, 201)] price = ChoiceField(choices=PRICE_CHOICES) trader = ModelChoiceField(label='', queryset=Trader.objects.all(), widget=HiddenInput()) market = ModelChoiceField(label='', queryset=Market.objects.all(), widget=HiddenInput()) def clean(self): """Validates the data. Ensures the trader has enough cash or shares to complete the requested order.""" cleaned_data = self.cleaned_data if cleaned_data.get('order') and cleaned_data.get('stock' ) and cleaned_data.get('volume') and cleaned_data.get('price'): t = cleaned_data['trader'] if cleaned_data['order'] == 'B': open_orders = Order.objects.filter(trader=t, order='B', completed=False) open_order_value = float(sum([(o.volume * o.price) for o in open_orders])) open_order_value += int(cleaned_data['volume']) * float( cleaned_data['price']) if open_order_value > t.cash: raise ValidationError("You don't have enough cash!") elif cleaned_data['order'] == 'S': open_orders = sum(Order.objects.filter(trader=t, order='S', stock=cleaned_data['stock'], completed=False). values_list('volume', flat=True)) open_orders += cleaned_data['volume'] if open_orders > t.holding_set.get(stock=cleaned_data['stock'] ).shares: raise ValidationError("You don't have enough shares!") return cleaned_data class Meta: model = Order fields = 'stock', 'order', 'volume', 'price', 'trader', 'market' class UploadFileForm(Form): file = FileField() <|reserved_special_token_1|> <|reserved_special_token_0|> class OrderForm(ModelForm): """Order form used in trader view.""" PRICE_CHOICES = [(i * 0.01, str(i * 0.01)) for i in range(1, 201)] price = ChoiceField(choices=PRICE_CHOICES) trader = ModelChoiceField(label='', queryset=Trader.objects.all(), widget=HiddenInput()) market = ModelChoiceField(label='', queryset=Market.objects.all(), widget=HiddenInput()) def clean(self): """Validates the data. Ensures the trader has enough cash or shares to complete the requested order.""" cleaned_data = self.cleaned_data if cleaned_data.get('order') and cleaned_data.get('stock' ) and cleaned_data.get('volume') and cleaned_data.get('price'): t = cleaned_data['trader'] if cleaned_data['order'] == 'B': open_orders = Order.objects.filter(trader=t, order='B', completed=False) open_order_value = float(sum([(o.volume * o.price) for o in open_orders])) open_order_value += int(cleaned_data['volume']) * float( cleaned_data['price']) if open_order_value > t.cash: raise ValidationError("You don't have enough cash!") elif cleaned_data['order'] == 'S': open_orders = sum(Order.objects.filter(trader=t, order='S', stock=cleaned_data['stock'], completed=False). values_list('volume', flat=True)) open_orders += cleaned_data['volume'] if open_orders > t.holding_set.get(stock=cleaned_data['stock'] ).shares: raise ValidationError("You don't have enough shares!") return cleaned_data class Meta: model = Order fields = 'stock', 'order', 'volume', 'price', 'trader', 'market' class UploadFileForm(Form): file = FileField() <|reserved_special_token_1|> from django.forms import ModelForm, ChoiceField, Form, FileField, ModelChoiceField, HiddenInput, ValidationError from market.models import * class OrderForm(ModelForm): """Order form used in trader view.""" # from http://stackoverflow.com/questions/1697702/how-to-pass-initial-parameter-to-djangos-modelform-instance/1697770#1697770 # price from http://stackoverflow.com/questions/6473895/how-to-restrict-values-in-a-django-decimalfield # restricts prices to 0.0 through 2.0 PRICE_CHOICES = [(i*.01, str(i*.01)) for i in range(1,201)] price = ChoiceField(choices=PRICE_CHOICES) trader = ModelChoiceField(label='', queryset=Trader.objects.all(), widget=HiddenInput()) market = ModelChoiceField(label='', queryset=Market.objects.all(), widget=HiddenInput()) def clean(self): """Validates the data. Ensures the trader has enough cash or shares to complete the requested order.""" cleaned_data = self.cleaned_data if cleaned_data.get('order') and cleaned_data.get('stock') \ and cleaned_data.get('volume') and cleaned_data.get('price'): t = cleaned_data['trader'] if cleaned_data['order'] == 'B': # buy order open_orders = Order.objects.filter(trader=t, order='B', completed=False) open_order_value = float(sum([o.volume * o.price for o in open_orders])) open_order_value += int(cleaned_data['volume']) * float(cleaned_data['price']) if open_order_value > t.cash: raise ValidationError("You don't have enough cash!") elif cleaned_data['order'] == 'S': # sell order! open_orders = sum(Order.objects.filter(trader=t, order='S', stock=cleaned_data['stock'], completed=False).values_list('volume', flat=True)) open_orders += cleaned_data['volume'] if open_orders > t.holding_set.get(stock=cleaned_data['stock']).shares: raise ValidationError("You don't have enough shares!") return cleaned_data class Meta: model = Order fields = ('stock', 'order', 'volume', 'price', 'trader', 'market') class UploadFileForm(Form): file = FileField()
flexible
{ "blob_id": "044e3479c32357e22ca3165d8601d8bd2a439fcb", "index": 2329, "step-1": "<mask token>\n\n\nclass OrderForm(ModelForm):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n model = Order\n fields = 'stock', 'order', 'volume', 'price', 'trader', 'market'\n\n\nclass UploadFileForm(Form):\n file = FileField()\n", "step-2": "<mask token>\n\n\nclass OrderForm(ModelForm):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def clean(self):\n \"\"\"Validates the data. Ensures the trader has enough cash or shares\n to complete the requested order.\"\"\"\n cleaned_data = self.cleaned_data\n if cleaned_data.get('order') and cleaned_data.get('stock'\n ) and cleaned_data.get('volume') and cleaned_data.get('price'):\n t = cleaned_data['trader']\n if cleaned_data['order'] == 'B':\n open_orders = Order.objects.filter(trader=t, order='B',\n completed=False)\n open_order_value = float(sum([(o.volume * o.price) for o in\n open_orders]))\n open_order_value += int(cleaned_data['volume']) * float(\n cleaned_data['price'])\n if open_order_value > t.cash:\n raise ValidationError(\"You don't have enough cash!\")\n elif cleaned_data['order'] == 'S':\n open_orders = sum(Order.objects.filter(trader=t, order='S',\n stock=cleaned_data['stock'], completed=False).\n values_list('volume', flat=True))\n open_orders += cleaned_data['volume']\n if open_orders > t.holding_set.get(stock=cleaned_data['stock']\n ).shares:\n raise ValidationError(\"You don't have enough shares!\")\n return cleaned_data\n\n\n class Meta:\n model = Order\n fields = 'stock', 'order', 'volume', 'price', 'trader', 'market'\n\n\nclass UploadFileForm(Form):\n file = FileField()\n", "step-3": "<mask token>\n\n\nclass OrderForm(ModelForm):\n <mask token>\n PRICE_CHOICES = [(i * 0.01, str(i * 0.01)) for i in range(1, 201)]\n price = ChoiceField(choices=PRICE_CHOICES)\n trader = ModelChoiceField(label='', queryset=Trader.objects.all(),\n widget=HiddenInput())\n market = ModelChoiceField(label='', queryset=Market.objects.all(),\n widget=HiddenInput())\n\n def clean(self):\n \"\"\"Validates the data. Ensures the trader has enough cash or shares\n to complete the requested order.\"\"\"\n cleaned_data = self.cleaned_data\n if cleaned_data.get('order') and cleaned_data.get('stock'\n ) and cleaned_data.get('volume') and cleaned_data.get('price'):\n t = cleaned_data['trader']\n if cleaned_data['order'] == 'B':\n open_orders = Order.objects.filter(trader=t, order='B',\n completed=False)\n open_order_value = float(sum([(o.volume * o.price) for o in\n open_orders]))\n open_order_value += int(cleaned_data['volume']) * float(\n cleaned_data['price'])\n if open_order_value > t.cash:\n raise ValidationError(\"You don't have enough cash!\")\n elif cleaned_data['order'] == 'S':\n open_orders = sum(Order.objects.filter(trader=t, order='S',\n stock=cleaned_data['stock'], completed=False).\n values_list('volume', flat=True))\n open_orders += cleaned_data['volume']\n if open_orders > t.holding_set.get(stock=cleaned_data['stock']\n ).shares:\n raise ValidationError(\"You don't have enough shares!\")\n return cleaned_data\n\n\n class Meta:\n model = Order\n fields = 'stock', 'order', 'volume', 'price', 'trader', 'market'\n\n\nclass UploadFileForm(Form):\n file = FileField()\n", "step-4": "<mask token>\n\n\nclass OrderForm(ModelForm):\n \"\"\"Order form used in trader view.\"\"\"\n PRICE_CHOICES = [(i * 0.01, str(i * 0.01)) for i in range(1, 201)]\n price = ChoiceField(choices=PRICE_CHOICES)\n trader = ModelChoiceField(label='', queryset=Trader.objects.all(),\n widget=HiddenInput())\n market = ModelChoiceField(label='', queryset=Market.objects.all(),\n widget=HiddenInput())\n\n def clean(self):\n \"\"\"Validates the data. Ensures the trader has enough cash or shares\n to complete the requested order.\"\"\"\n cleaned_data = self.cleaned_data\n if cleaned_data.get('order') and cleaned_data.get('stock'\n ) and cleaned_data.get('volume') and cleaned_data.get('price'):\n t = cleaned_data['trader']\n if cleaned_data['order'] == 'B':\n open_orders = Order.objects.filter(trader=t, order='B',\n completed=False)\n open_order_value = float(sum([(o.volume * o.price) for o in\n open_orders]))\n open_order_value += int(cleaned_data['volume']) * float(\n cleaned_data['price'])\n if open_order_value > t.cash:\n raise ValidationError(\"You don't have enough cash!\")\n elif cleaned_data['order'] == 'S':\n open_orders = sum(Order.objects.filter(trader=t, order='S',\n stock=cleaned_data['stock'], completed=False).\n values_list('volume', flat=True))\n open_orders += cleaned_data['volume']\n if open_orders > t.holding_set.get(stock=cleaned_data['stock']\n ).shares:\n raise ValidationError(\"You don't have enough shares!\")\n return cleaned_data\n\n\n class Meta:\n model = Order\n fields = 'stock', 'order', 'volume', 'price', 'trader', 'market'\n\n\nclass UploadFileForm(Form):\n file = FileField()\n", "step-5": "from django.forms import ModelForm, ChoiceField, Form, FileField, ModelChoiceField, HiddenInput, ValidationError\nfrom market.models import *\n\nclass OrderForm(ModelForm):\n \"\"\"Order form used in trader view.\"\"\"\n # from http://stackoverflow.com/questions/1697702/how-to-pass-initial-parameter-to-djangos-modelform-instance/1697770#1697770\n # price from http://stackoverflow.com/questions/6473895/how-to-restrict-values-in-a-django-decimalfield\n\n # restricts prices to 0.0 through 2.0\n PRICE_CHOICES = [(i*.01, str(i*.01)) for i in range(1,201)]\n price = ChoiceField(choices=PRICE_CHOICES)\n trader = ModelChoiceField(label='', queryset=Trader.objects.all(), widget=HiddenInput())\n market = ModelChoiceField(label='', queryset=Market.objects.all(), widget=HiddenInput())\n\n def clean(self):\n \"\"\"Validates the data. Ensures the trader has enough cash or shares\n to complete the requested order.\"\"\"\n\n cleaned_data = self.cleaned_data\n if cleaned_data.get('order') and cleaned_data.get('stock') \\\n and cleaned_data.get('volume') and cleaned_data.get('price'):\n t = cleaned_data['trader']\n if cleaned_data['order'] == 'B': # buy order\n open_orders = Order.objects.filter(trader=t,\n order='B', completed=False)\n open_order_value = float(sum([o.volume * o.price for o in open_orders]))\n open_order_value += int(cleaned_data['volume']) * float(cleaned_data['price'])\n\n if open_order_value > t.cash:\n raise ValidationError(\"You don't have enough cash!\")\n\n elif cleaned_data['order'] == 'S': # sell order!\n open_orders = sum(Order.objects.filter(trader=t, order='S',\n stock=cleaned_data['stock'],\n completed=False).values_list('volume', flat=True))\n open_orders += cleaned_data['volume']\n\n if open_orders > t.holding_set.get(stock=cleaned_data['stock']).shares:\n raise ValidationError(\"You don't have enough shares!\")\n return cleaned_data\n\n class Meta:\n model = Order\n fields = ('stock', 'order', 'volume', 'price', 'trader', 'market')\n\nclass UploadFileForm(Form):\n file = FileField()\n", "step-ids": [ 3, 4, 5, 6, 8 ] }
[ 3, 4, 5, 6, 8 ]
<|reserved_special_token_0|> class ModelBase(unittest.TestCase): <|reserved_special_token_0|> <|reserved_special_token_0|> def get(self, url): """Process a GET request to the app""" return self.app.get(get_url(url), follow_redirects=True) <|reserved_special_token_0|> def verify_object(self, data): """Verify the model object data""" rv = self.get(data[self.id_field]) result = not is_404(rv) if result: for key, value in data: if not in_response(rv, value): return False return result def get_add_form(self): """Test that the "add" form is accessible and contains all the fields """ rv = self.get(self.add_url) assert not is_404(rv) assert in_response(rv, 'Add {}'.format(self.nice_name)) for field, name in self.fields: assert in_response(rv, name) return rv <|reserved_special_token_0|> def get_delete_confirmation_form(self, data): """Test that the delete confirmation form is accessible""" self.add_success(data) rv = self.get((data[self.id_field], self.delete_url)) assert not is_404(rv) assert in_response(rv, 'Delete {}'.format(data[self.name_field])) return rv def add_success(self, data): """Test that adding a model with the given data succeeds""" rv = self.post(self.add_url, data) assert not in_response(rv, 'Add {}'.format(self.nice_name)) assert self.verify_object(data) return rv def edit_success(self, id_, data): """Test that updating a model with the given data succeeds""" rv = self.post((id_, self.edit_url), data) assert not in_response(rv, 'Edit {}'.format(data[self.name_field])) assert self.verify_object(data) return rv <|reserved_special_token_0|> def delete_success(self, id_): """Test that deleting the specified model succeeds""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert not self.verify_object({self.id_field: id_}) return rv def add_fail(self, data, message): """Test that adding a model with the given data fails""" rv = self.post(self.add_url, data) assert in_response(rv, 'Add {}'.format(self.nice_name)) assert in_response(rv, message) return rv <|reserved_special_token_0|> <|reserved_special_token_0|> def delete_fail(self, id_, message): """Test that deleting the specified model fails""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert in_response(rv, message) assert self.verify_object({self.id_field: id_}) return rv def bad_data_fail(self, good_data, bad_data, message): """Test that adding and updating a model with the given data fails """ self.add_fail(bad_data, message) self.update_fail(good_data, bad_data, message) def add_required_field_fail(self, field, data): """Test that adding a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() data[field] = '' self.add_fail(data, message) assert not self.verify_object(data) del data[field] self.add_fail(data, message) assert not self.verify_object(data) <|reserved_special_token_0|> def required_field_fail(self, field, data): """Test that adding and updating a model with a blank or missing required field fails """ self.add_required_field_fail(field, data) self.update_required_field_fail(field, data) def add_existing_key_fail(self, data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) return self.add_fail(data, message) <|reserved_special_token_0|> def existing_key_fail(self, data, new_data): """Test that adding and updating a model with an existing key fails """ message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) self.add_fail(data, message) rv = self.add_success(new_data) assert not in_response(rv, message) self.update_fail(data, message) assert self.verify_object(new_data) <|reserved_special_token_0|> <|reserved_special_token_0|> class CategoryTestCase(ClosetTestBase, ModelBase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/categories' self.name = 'category' self.nice_name = 'Category' self.fields = {'name': 'Name', 'parent': 'Parent'} self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'}, 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': { 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'}, 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent': 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent': 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug': 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''}, 'keyword': {'name': 'Add', 'slug': 'add-1'}} def setUp(self): super(CategoryTestCase, self).setUp() self.authenticate() def test_get_category_forms(self): """Test that the category forms are accessible""" self.get_add_form() self.get_edit_form(self.test_data['pants']) self.get_delete_confirmation_form(self.test_data['shirts']) def test_add_category(self): """Test that adding a category works""" self.add_success(self.test_data['pants']) def test_update_category(self): """Test that updating a category works""" self.update_success(self.test_data['pants'], self.test_data['shirts']) def test_delete_category(self): """Test that deleting a category works""" self.add_success(self.test_data['pants']) self.delete_success('pants') def test_add_child_category(self): """Test that adding a child category works""" self.add_success(self.test_data['pants']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') def test_update_child_category(self): """Test that updating child categories works""" self.add_success(self.test_data['pants']) self.add_success(self.test_data['shirts']) self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') self.edit_success('jeans', self.test_data['t-shirts']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') assert not in_response(rv, 'Jeans') assert not in_response(rv, 'T-Shirts') rv = self.get('shirts') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'T-Shirts') assert not in_response(rv, 'Jeans') def test_name_required(self): """Test that adding/updating a category without a name fails""" self.required_field_fail('name', self.test_data['pants']) def test_parent_does_not_exist(self): """Test that adding/updating a category with a non-existent parent fails """ self.bad_data_fail(self.test_data['pants'], self.test_data['hats'], 'Parent does not exist') def test_category_already_exists(self): self.existing_key_fail(self.test_data['pants'], self.test_data[ 'shirts']) def test_categories_are_sorted(self): """Test that categories are sorted alphabetically by name""" self.data_sorted(self.test_data['shirts'], self.test_data['pants']) def test_delete_category_does_not_exist(self): """Test that deleting a category that doesn't exist fails""" self.delete_does_not_exist_fail('hats') def test_add_category_slug_special(self): """Test that adding a category with an incorrect name fails""" self.add_success(self.test_data['polo-shirts']) assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts')) self.add_fail(self.test_data['symbols'], '') self.add_success('Add') def test_update_category_slug_special(self): """Test that updating a category with an incorrect slug fails""" rv = self.app.post(self.get_category_url('add'), data=dict(name= 'Pants', slug='pants'), follow_redirects=True) rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True ) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name=':)', slug=':)'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Add', slug='add'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug "add" is not allowed' in rv.data <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ClosetTestCase(ClosetTestBase): <|reserved_special_token_0|> <|reserved_special_token_0|> class ModelBase(unittest.TestCase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/' self.add_url = 'add' self.edit_url = 'edit' self.delete_url = 'delete' self.name = '' self.nice_name = '' self.name_field = 'name' self.id_field = 'slug' self.fields = {} def get_url(self, *args): """Create a URL from a tuple of strings based on the base url""" try: url = '/'.join((self.base_url,) + args) except TypeError: url = '/'.join((self.base_url,) + args[0]) return url.rstrip('/') def get(self, url): """Process a GET request to the app""" return self.app.get(get_url(url), follow_redirects=True) def post(self, url, data): """Process a POST request to the app""" return self.app.post(get_url(url), data=data, follow_redirects=True) def verify_object(self, data): """Verify the model object data""" rv = self.get(data[self.id_field]) result = not is_404(rv) if result: for key, value in data: if not in_response(rv, value): return False return result def get_add_form(self): """Test that the "add" form is accessible and contains all the fields """ rv = self.get(self.add_url) assert not is_404(rv) assert in_response(rv, 'Add {}'.format(self.nice_name)) for field, name in self.fields: assert in_response(rv, name) return rv def get_edit_form(self, data): """Test that the edit form is accessible and contains all the fields """ self.add_success(data) rv = self.get((data[self.id_field], self.edit_url)) assert not is_404(rv) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) for field, name in self.fields: assert in_response(rv, name) return rv def get_delete_confirmation_form(self, data): """Test that the delete confirmation form is accessible""" self.add_success(data) rv = self.get((data[self.id_field], self.delete_url)) assert not is_404(rv) assert in_response(rv, 'Delete {}'.format(data[self.name_field])) return rv def add_success(self, data): """Test that adding a model with the given data succeeds""" rv = self.post(self.add_url, data) assert not in_response(rv, 'Add {}'.format(self.nice_name)) assert self.verify_object(data) return rv def edit_success(self, id_, data): """Test that updating a model with the given data succeeds""" rv = self.post((id_, self.edit_url), data) assert not in_response(rv, 'Edit {}'.format(data[self.name_field])) assert self.verify_object(data) return rv def update_success(self, data, new_data): """Test that updating a model with the given data succeeds""" self.add_success(data) return self.edit_success(data[self.id_field], new_data) def delete_success(self, id_): """Test that deleting the specified model succeeds""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert not self.verify_object({self.id_field: id_}) return rv def add_fail(self, data, message): """Test that adding a model with the given data fails""" rv = self.post(self.add_url, data) assert in_response(rv, 'Add {}'.format(self.nice_name)) assert in_response(rv, message) return rv def edit_fail(self, id_, data, message): """Test that updating a model with the given data fails""" rv = self.post((id_, self.edit_url), data) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) assert in_response(rv, message) return rv def update_fail(self, data, new_data, message): """Test that updating a model with the given data fails""" self.add_success(data) return self.edit_fail(data[self.id_field], new_data, message) def delete_fail(self, id_, message): """Test that deleting the specified model fails""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert in_response(rv, message) assert self.verify_object({self.id_field: id_}) return rv def bad_data_fail(self, good_data, bad_data, message): """Test that adding and updating a model with the given data fails """ self.add_fail(bad_data, message) self.update_fail(good_data, bad_data, message) def add_required_field_fail(self, field, data): """Test that adding a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() data[field] = '' self.add_fail(data, message) assert not self.verify_object(data) del data[field] self.add_fail(data, message) assert not self.verify_object(data) def update_required_field_fail(self, field, data): """Test that updating a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() id_ = data[self.id_field] self.add_success(data) data[field] = '' self.edit_fail(id_, data, message) assert not self.verify_object(data) del data[field] self.edit_fail(id_, data, message) assert not self.verify_object(data) def required_field_fail(self, field, data): """Test that adding and updating a model with a blank or missing required field fails """ self.add_required_field_fail(field, data) self.update_required_field_fail(field, data) def add_existing_key_fail(self, data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) return self.add_fail(data, message) def update_existing_key_fail(self, data, new_data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) rv = self.add_success(new_data) assert not in_response(rv, message) rv = self.update_fail(data, message) assert self.verify_object(new_data) return rv def existing_key_fail(self, data, new_data): """Test that adding and updating a model with an existing key fails """ message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) self.add_fail(data, message) rv = self.add_success(new_data) assert not in_response(rv, message) self.update_fail(data, message) assert self.verify_object(new_data) def data_sorted(self, before_data, after_data, url): """Test that the models will be sorted in the correct order""" self.add_success(after_data) self.add_success(before_data) rv = self.get(url) after_index = rv.data.index(after_data[self.name_field].encode()) before_index = rv.data.index(before_data[self.name_field].encode()) assert after_index > before_index def delete_does_not_exist_fail(self, id_): """Test that deleting a model that does not exist fails""" assert is_404(self.get((id_, self.delete_url))) self.delete_fail(id_, 'does not exist') class CategoryTestCase(ClosetTestBase, ModelBase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/categories' self.name = 'category' self.nice_name = 'Category' self.fields = {'name': 'Name', 'parent': 'Parent'} self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'}, 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': { 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'}, 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent': 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent': 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug': 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''}, 'keyword': {'name': 'Add', 'slug': 'add-1'}} def setUp(self): super(CategoryTestCase, self).setUp() self.authenticate() def test_get_category_forms(self): """Test that the category forms are accessible""" self.get_add_form() self.get_edit_form(self.test_data['pants']) self.get_delete_confirmation_form(self.test_data['shirts']) def test_add_category(self): """Test that adding a category works""" self.add_success(self.test_data['pants']) def test_update_category(self): """Test that updating a category works""" self.update_success(self.test_data['pants'], self.test_data['shirts']) def test_delete_category(self): """Test that deleting a category works""" self.add_success(self.test_data['pants']) self.delete_success('pants') def test_add_child_category(self): """Test that adding a child category works""" self.add_success(self.test_data['pants']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') def test_update_child_category(self): """Test that updating child categories works""" self.add_success(self.test_data['pants']) self.add_success(self.test_data['shirts']) self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') self.edit_success('jeans', self.test_data['t-shirts']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') assert not in_response(rv, 'Jeans') assert not in_response(rv, 'T-Shirts') rv = self.get('shirts') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'T-Shirts') assert not in_response(rv, 'Jeans') def test_name_required(self): """Test that adding/updating a category without a name fails""" self.required_field_fail('name', self.test_data['pants']) def test_parent_does_not_exist(self): """Test that adding/updating a category with a non-existent parent fails """ self.bad_data_fail(self.test_data['pants'], self.test_data['hats'], 'Parent does not exist') def test_category_already_exists(self): self.existing_key_fail(self.test_data['pants'], self.test_data[ 'shirts']) def test_categories_are_sorted(self): """Test that categories are sorted alphabetically by name""" self.data_sorted(self.test_data['shirts'], self.test_data['pants']) def test_delete_category_does_not_exist(self): """Test that deleting a category that doesn't exist fails""" self.delete_does_not_exist_fail('hats') def test_add_category_slug_special(self): """Test that adding a category with an incorrect name fails""" self.add_success(self.test_data['polo-shirts']) assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts')) self.add_fail(self.test_data['symbols'], '') self.add_success('Add') def test_update_category_slug_special(self): """Test that updating a category with an incorrect slug fails""" rv = self.app.post(self.get_category_url('add'), data=dict(name= 'Pants', slug='pants'), follow_redirects=True) rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True ) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name=':)', slug=':)'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Add', slug='add'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug "add" is not allowed' in rv.data <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ClosetTestCase(ClosetTestBase): <|reserved_special_token_0|> def test_login_logout(self): """Make sure login and logout works""" rv = self.login(closet.app.config['USERNAME'], closet.app.config[ 'PASSWORD']) assert b'You were logged in' in rv.data rv = self.logout() assert b'You were logged out' in rv.data rv = self.login(closet.app.config['USERNAME'] + 'x', closet.app. config['PASSWORD']) assert b'Invalid username' in rv.data rv = self.login(closet.app.config['USERNAME'], closet.app.config[ 'PASSWORD'] + 'x') assert b'Invalid password' in rv.data class ModelBase(unittest.TestCase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/' self.add_url = 'add' self.edit_url = 'edit' self.delete_url = 'delete' self.name = '' self.nice_name = '' self.name_field = 'name' self.id_field = 'slug' self.fields = {} def get_url(self, *args): """Create a URL from a tuple of strings based on the base url""" try: url = '/'.join((self.base_url,) + args) except TypeError: url = '/'.join((self.base_url,) + args[0]) return url.rstrip('/') def get(self, url): """Process a GET request to the app""" return self.app.get(get_url(url), follow_redirects=True) def post(self, url, data): """Process a POST request to the app""" return self.app.post(get_url(url), data=data, follow_redirects=True) def verify_object(self, data): """Verify the model object data""" rv = self.get(data[self.id_field]) result = not is_404(rv) if result: for key, value in data: if not in_response(rv, value): return False return result def get_add_form(self): """Test that the "add" form is accessible and contains all the fields """ rv = self.get(self.add_url) assert not is_404(rv) assert in_response(rv, 'Add {}'.format(self.nice_name)) for field, name in self.fields: assert in_response(rv, name) return rv def get_edit_form(self, data): """Test that the edit form is accessible and contains all the fields """ self.add_success(data) rv = self.get((data[self.id_field], self.edit_url)) assert not is_404(rv) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) for field, name in self.fields: assert in_response(rv, name) return rv def get_delete_confirmation_form(self, data): """Test that the delete confirmation form is accessible""" self.add_success(data) rv = self.get((data[self.id_field], self.delete_url)) assert not is_404(rv) assert in_response(rv, 'Delete {}'.format(data[self.name_field])) return rv def add_success(self, data): """Test that adding a model with the given data succeeds""" rv = self.post(self.add_url, data) assert not in_response(rv, 'Add {}'.format(self.nice_name)) assert self.verify_object(data) return rv def edit_success(self, id_, data): """Test that updating a model with the given data succeeds""" rv = self.post((id_, self.edit_url), data) assert not in_response(rv, 'Edit {}'.format(data[self.name_field])) assert self.verify_object(data) return rv def update_success(self, data, new_data): """Test that updating a model with the given data succeeds""" self.add_success(data) return self.edit_success(data[self.id_field], new_data) def delete_success(self, id_): """Test that deleting the specified model succeeds""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert not self.verify_object({self.id_field: id_}) return rv def add_fail(self, data, message): """Test that adding a model with the given data fails""" rv = self.post(self.add_url, data) assert in_response(rv, 'Add {}'.format(self.nice_name)) assert in_response(rv, message) return rv def edit_fail(self, id_, data, message): """Test that updating a model with the given data fails""" rv = self.post((id_, self.edit_url), data) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) assert in_response(rv, message) return rv def update_fail(self, data, new_data, message): """Test that updating a model with the given data fails""" self.add_success(data) return self.edit_fail(data[self.id_field], new_data, message) def delete_fail(self, id_, message): """Test that deleting the specified model fails""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert in_response(rv, message) assert self.verify_object({self.id_field: id_}) return rv def bad_data_fail(self, good_data, bad_data, message): """Test that adding and updating a model with the given data fails """ self.add_fail(bad_data, message) self.update_fail(good_data, bad_data, message) def add_required_field_fail(self, field, data): """Test that adding a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() data[field] = '' self.add_fail(data, message) assert not self.verify_object(data) del data[field] self.add_fail(data, message) assert not self.verify_object(data) def update_required_field_fail(self, field, data): """Test that updating a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() id_ = data[self.id_field] self.add_success(data) data[field] = '' self.edit_fail(id_, data, message) assert not self.verify_object(data) del data[field] self.edit_fail(id_, data, message) assert not self.verify_object(data) def required_field_fail(self, field, data): """Test that adding and updating a model with a blank or missing required field fails """ self.add_required_field_fail(field, data) self.update_required_field_fail(field, data) def add_existing_key_fail(self, data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) return self.add_fail(data, message) def update_existing_key_fail(self, data, new_data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) rv = self.add_success(new_data) assert not in_response(rv, message) rv = self.update_fail(data, message) assert self.verify_object(new_data) return rv def existing_key_fail(self, data, new_data): """Test that adding and updating a model with an existing key fails """ message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) self.add_fail(data, message) rv = self.add_success(new_data) assert not in_response(rv, message) self.update_fail(data, message) assert self.verify_object(new_data) def data_sorted(self, before_data, after_data, url): """Test that the models will be sorted in the correct order""" self.add_success(after_data) self.add_success(before_data) rv = self.get(url) after_index = rv.data.index(after_data[self.name_field].encode()) before_index = rv.data.index(before_data[self.name_field].encode()) assert after_index > before_index def delete_does_not_exist_fail(self, id_): """Test that deleting a model that does not exist fails""" assert is_404(self.get((id_, self.delete_url))) self.delete_fail(id_, 'does not exist') class CategoryTestCase(ClosetTestBase, ModelBase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/categories' self.name = 'category' self.nice_name = 'Category' self.fields = {'name': 'Name', 'parent': 'Parent'} self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'}, 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': { 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'}, 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent': 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent': 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug': 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''}, 'keyword': {'name': 'Add', 'slug': 'add-1'}} def setUp(self): super(CategoryTestCase, self).setUp() self.authenticate() def test_get_category_forms(self): """Test that the category forms are accessible""" self.get_add_form() self.get_edit_form(self.test_data['pants']) self.get_delete_confirmation_form(self.test_data['shirts']) def test_add_category(self): """Test that adding a category works""" self.add_success(self.test_data['pants']) def test_update_category(self): """Test that updating a category works""" self.update_success(self.test_data['pants'], self.test_data['shirts']) def test_delete_category(self): """Test that deleting a category works""" self.add_success(self.test_data['pants']) self.delete_success('pants') def test_add_child_category(self): """Test that adding a child category works""" self.add_success(self.test_data['pants']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') def test_update_child_category(self): """Test that updating child categories works""" self.add_success(self.test_data['pants']) self.add_success(self.test_data['shirts']) self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') self.edit_success('jeans', self.test_data['t-shirts']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') assert not in_response(rv, 'Jeans') assert not in_response(rv, 'T-Shirts') rv = self.get('shirts') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'T-Shirts') assert not in_response(rv, 'Jeans') def test_name_required(self): """Test that adding/updating a category without a name fails""" self.required_field_fail('name', self.test_data['pants']) def test_parent_does_not_exist(self): """Test that adding/updating a category with a non-existent parent fails """ self.bad_data_fail(self.test_data['pants'], self.test_data['hats'], 'Parent does not exist') def test_category_already_exists(self): self.existing_key_fail(self.test_data['pants'], self.test_data[ 'shirts']) def test_categories_are_sorted(self): """Test that categories are sorted alphabetically by name""" self.data_sorted(self.test_data['shirts'], self.test_data['pants']) def test_delete_category_does_not_exist(self): """Test that deleting a category that doesn't exist fails""" self.delete_does_not_exist_fail('hats') def test_add_category_slug_special(self): """Test that adding a category with an incorrect name fails""" self.add_success(self.test_data['polo-shirts']) assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts')) self.add_fail(self.test_data['symbols'], '') self.add_success('Add') def test_update_category_slug_special(self): """Test that updating a category with an incorrect slug fails""" rv = self.app.post(self.get_category_url('add'), data=dict(name= 'Pants', slug='pants'), follow_redirects=True) rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True ) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name=':)', slug=':)'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Add', slug='add'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug "add" is not allowed' in rv.data <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ClosetTestBase(unittest.TestCase): def setUp(self): """Set up test environment befor each test""" self.db_fd, closet.app.config['DATABASE'] = tempfile.mkstemp() closet.app.config['TESTING'] = True self.app = closet.app.test_client() closet.init_db() <|reserved_special_token_0|> def login(self, username, password): """Login to test website as specified user with the specified password """ return self.app.post('/login', data=dict(username=username, password=password), follow_redirects=True) <|reserved_special_token_0|> def authenticate(self): """Login to test website as the standard test user""" self.login(closet.app.config['USERNAME'], closet.app.config['PASSWORD'] ) class ClosetTestCase(ClosetTestBase): def test_empty_db(self): """Start with a blank database.""" rv = self.app.get('/') assert b'Your closet is empty.' in rv.data def test_login_logout(self): """Make sure login and logout works""" rv = self.login(closet.app.config['USERNAME'], closet.app.config[ 'PASSWORD']) assert b'You were logged in' in rv.data rv = self.logout() assert b'You were logged out' in rv.data rv = self.login(closet.app.config['USERNAME'] + 'x', closet.app. config['PASSWORD']) assert b'Invalid username' in rv.data rv = self.login(closet.app.config['USERNAME'], closet.app.config[ 'PASSWORD'] + 'x') assert b'Invalid password' in rv.data class ModelBase(unittest.TestCase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/' self.add_url = 'add' self.edit_url = 'edit' self.delete_url = 'delete' self.name = '' self.nice_name = '' self.name_field = 'name' self.id_field = 'slug' self.fields = {} def get_url(self, *args): """Create a URL from a tuple of strings based on the base url""" try: url = '/'.join((self.base_url,) + args) except TypeError: url = '/'.join((self.base_url,) + args[0]) return url.rstrip('/') def get(self, url): """Process a GET request to the app""" return self.app.get(get_url(url), follow_redirects=True) def post(self, url, data): """Process a POST request to the app""" return self.app.post(get_url(url), data=data, follow_redirects=True) def verify_object(self, data): """Verify the model object data""" rv = self.get(data[self.id_field]) result = not is_404(rv) if result: for key, value in data: if not in_response(rv, value): return False return result def get_add_form(self): """Test that the "add" form is accessible and contains all the fields """ rv = self.get(self.add_url) assert not is_404(rv) assert in_response(rv, 'Add {}'.format(self.nice_name)) for field, name in self.fields: assert in_response(rv, name) return rv def get_edit_form(self, data): """Test that the edit form is accessible and contains all the fields """ self.add_success(data) rv = self.get((data[self.id_field], self.edit_url)) assert not is_404(rv) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) for field, name in self.fields: assert in_response(rv, name) return rv def get_delete_confirmation_form(self, data): """Test that the delete confirmation form is accessible""" self.add_success(data) rv = self.get((data[self.id_field], self.delete_url)) assert not is_404(rv) assert in_response(rv, 'Delete {}'.format(data[self.name_field])) return rv def add_success(self, data): """Test that adding a model with the given data succeeds""" rv = self.post(self.add_url, data) assert not in_response(rv, 'Add {}'.format(self.nice_name)) assert self.verify_object(data) return rv def edit_success(self, id_, data): """Test that updating a model with the given data succeeds""" rv = self.post((id_, self.edit_url), data) assert not in_response(rv, 'Edit {}'.format(data[self.name_field])) assert self.verify_object(data) return rv def update_success(self, data, new_data): """Test that updating a model with the given data succeeds""" self.add_success(data) return self.edit_success(data[self.id_field], new_data) def delete_success(self, id_): """Test that deleting the specified model succeeds""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert not self.verify_object({self.id_field: id_}) return rv def add_fail(self, data, message): """Test that adding a model with the given data fails""" rv = self.post(self.add_url, data) assert in_response(rv, 'Add {}'.format(self.nice_name)) assert in_response(rv, message) return rv def edit_fail(self, id_, data, message): """Test that updating a model with the given data fails""" rv = self.post((id_, self.edit_url), data) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) assert in_response(rv, message) return rv def update_fail(self, data, new_data, message): """Test that updating a model with the given data fails""" self.add_success(data) return self.edit_fail(data[self.id_field], new_data, message) def delete_fail(self, id_, message): """Test that deleting the specified model fails""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert in_response(rv, message) assert self.verify_object({self.id_field: id_}) return rv def bad_data_fail(self, good_data, bad_data, message): """Test that adding and updating a model with the given data fails """ self.add_fail(bad_data, message) self.update_fail(good_data, bad_data, message) def add_required_field_fail(self, field, data): """Test that adding a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() data[field] = '' self.add_fail(data, message) assert not self.verify_object(data) del data[field] self.add_fail(data, message) assert not self.verify_object(data) def update_required_field_fail(self, field, data): """Test that updating a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() id_ = data[self.id_field] self.add_success(data) data[field] = '' self.edit_fail(id_, data, message) assert not self.verify_object(data) del data[field] self.edit_fail(id_, data, message) assert not self.verify_object(data) def required_field_fail(self, field, data): """Test that adding and updating a model with a blank or missing required field fails """ self.add_required_field_fail(field, data) self.update_required_field_fail(field, data) def add_existing_key_fail(self, data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) return self.add_fail(data, message) def update_existing_key_fail(self, data, new_data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) rv = self.add_success(new_data) assert not in_response(rv, message) rv = self.update_fail(data, message) assert self.verify_object(new_data) return rv def existing_key_fail(self, data, new_data): """Test that adding and updating a model with an existing key fails """ message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) self.add_fail(data, message) rv = self.add_success(new_data) assert not in_response(rv, message) self.update_fail(data, message) assert self.verify_object(new_data) def data_sorted(self, before_data, after_data, url): """Test that the models will be sorted in the correct order""" self.add_success(after_data) self.add_success(before_data) rv = self.get(url) after_index = rv.data.index(after_data[self.name_field].encode()) before_index = rv.data.index(before_data[self.name_field].encode()) assert after_index > before_index def delete_does_not_exist_fail(self, id_): """Test that deleting a model that does not exist fails""" assert is_404(self.get((id_, self.delete_url))) self.delete_fail(id_, 'does not exist') class CategoryTestCase(ClosetTestBase, ModelBase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/categories' self.name = 'category' self.nice_name = 'Category' self.fields = {'name': 'Name', 'parent': 'Parent'} self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'}, 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': { 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'}, 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent': 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent': 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug': 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''}, 'keyword': {'name': 'Add', 'slug': 'add-1'}} def setUp(self): super(CategoryTestCase, self).setUp() self.authenticate() def test_get_category_forms(self): """Test that the category forms are accessible""" self.get_add_form() self.get_edit_form(self.test_data['pants']) self.get_delete_confirmation_form(self.test_data['shirts']) def test_add_category(self): """Test that adding a category works""" self.add_success(self.test_data['pants']) def test_update_category(self): """Test that updating a category works""" self.update_success(self.test_data['pants'], self.test_data['shirts']) def test_delete_category(self): """Test that deleting a category works""" self.add_success(self.test_data['pants']) self.delete_success('pants') def test_add_child_category(self): """Test that adding a child category works""" self.add_success(self.test_data['pants']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') def test_update_child_category(self): """Test that updating child categories works""" self.add_success(self.test_data['pants']) self.add_success(self.test_data['shirts']) self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') self.edit_success('jeans', self.test_data['t-shirts']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') assert not in_response(rv, 'Jeans') assert not in_response(rv, 'T-Shirts') rv = self.get('shirts') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'T-Shirts') assert not in_response(rv, 'Jeans') def test_name_required(self): """Test that adding/updating a category without a name fails""" self.required_field_fail('name', self.test_data['pants']) def test_parent_does_not_exist(self): """Test that adding/updating a category with a non-existent parent fails """ self.bad_data_fail(self.test_data['pants'], self.test_data['hats'], 'Parent does not exist') def test_category_already_exists(self): self.existing_key_fail(self.test_data['pants'], self.test_data[ 'shirts']) def test_categories_are_sorted(self): """Test that categories are sorted alphabetically by name""" self.data_sorted(self.test_data['shirts'], self.test_data['pants']) def test_delete_category_does_not_exist(self): """Test that deleting a category that doesn't exist fails""" self.delete_does_not_exist_fail('hats') def test_add_category_slug_special(self): """Test that adding a category with an incorrect name fails""" self.add_success(self.test_data['polo-shirts']) assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts')) self.add_fail(self.test_data['symbols'], '') self.add_success('Add') def test_update_category_slug_special(self): """Test that updating a category with an incorrect slug fails""" rv = self.app.post(self.get_category_url('add'), data=dict(name= 'Pants', slug='pants'), follow_redirects=True) rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True ) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name=':)', slug=':)'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data= dict(name='Add', slug='add'), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug "add" is not allowed' in rv.data <|reserved_special_token_0|> <|reserved_special_token_1|> import os import closet import unittest import tempfile def in_response(response, value): return value.encode() in response.data def is_404(response): response.status_code == 404 class ClosetTestBase(unittest.TestCase): def setUp(self): """Set up test environment befor each test""" self.db_fd, closet.app.config['DATABASE'] = tempfile.mkstemp() closet.app.config['TESTING'] = True self.app = closet.app.test_client() closet.init_db() def tearDown(self): """Tear down test environment after each test""" os.close(self.db_fd) os.unlink(closet.app.config['DATABASE']) def login(self, username, password): """Login to test website as specified user with the specified password """ return self.app.post('/login', data=dict( username=username, password=password ), follow_redirects=True) def logout(self): """Logout of test website""" return self.app.get('/logout', follow_redirects=True) def authenticate(self): """Login to test website as the standard test user""" self.login(closet.app.config['USERNAME'], closet.app.config['PASSWORD']) class ClosetTestCase(ClosetTestBase): # Generic Tests def test_empty_db(self): """Start with a blank database.""" rv = self.app.get('/') assert b'Your closet is empty.' in rv.data def test_login_logout(self): """Make sure login and logout works""" rv = self.login(closet.app.config['USERNAME'], closet.app.config['PASSWORD']) assert b'You were logged in' in rv.data rv = self.logout() assert b'You were logged out' in rv.data rv = self.login(closet.app.config['USERNAME'] + 'x', closet.app.config['PASSWORD']) assert b'Invalid username' in rv.data rv = self.login(closet.app.config['USERNAME'], closet.app.config['PASSWORD'] + 'x') assert b'Invalid password' in rv.data class ModelBase(unittest.TestCase): # Model based view test helpers def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/' self.add_url = 'add' self.edit_url = 'edit' self.delete_url = 'delete' self.name = '' self.nice_name = '' self.name_field = 'name' self.id_field = 'slug' self.fields = {} def get_url(self, *args): """Create a URL from a tuple of strings based on the base url""" try: url = '/'.join((self.base_url, ) + args) except TypeError: url = '/'.join((self.base_url, ) + args[0]) return url.rstrip('/') def get(self, url): """Process a GET request to the app""" return self.app.get(get_url(url), follow_redirects=True) def post(self, url, data): """Process a POST request to the app""" return self.app.post(get_url(url), data=data, follow_redirects=True) def verify_object(self, data): """Verify the model object data""" rv = self.get(data[self.id_field]) result = not is_404(rv) if result: for key, value in data: if not in_response(rv, value): return False return result def get_add_form(self): """Test that the "add" form is accessible and contains all the fields """ rv = self.get(self.add_url) assert not is_404(rv) assert in_response(rv, 'Add {}'.format(self.nice_name)) for field, name in self.fields: assert in_response(rv, name) return rv def get_edit_form(self, data): """Test that the edit form is accessible and contains all the fields """ self.add_success(data) rv = self.get((data[self.id_field], self.edit_url)) assert not is_404(rv) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) for field, name in self.fields: assert in_response(rv, name) return rv def get_delete_confirmation_form(self, data): """Test that the delete confirmation form is accessible""" self.add_success(data) rv = self.get((data[self.id_field], self.delete_url)) assert not is_404(rv) assert in_response(rv, 'Delete {}'.format(data[self.name_field])) return rv def add_success(self, data): """Test that adding a model with the given data succeeds""" rv = self.post(self.add_url, data) assert not in_response(rv, 'Add {}'.format(self.nice_name)) assert self.verify_object(data) return rv def edit_success(self, id_, data): """Test that updating a model with the given data succeeds""" rv = self.post((id_, self.edit_url), data) assert not in_response(rv, 'Edit {}'.format(data[self.name_field])) assert self.verify_object(data) return rv def update_success(self, data, new_data): """Test that updating a model with the given data succeeds""" self.add_success(data) return self.edit_success(data[self.id_field], new_data) def delete_success(self, id_): """Test that deleting the specified model succeeds""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert not self.verify_object({self.id_field: id_}) return rv def add_fail(self, data, message): """Test that adding a model with the given data fails""" rv = self.post(self.add_url, data) assert in_response(rv, 'Add {}'.format(self.nice_name)) assert in_response(rv, message) return rv def edit_fail(self, id_, data, message): """Test that updating a model with the given data fails""" rv = self.post((id_, self.edit_url), data) assert in_response(rv, 'Edit {}'.format(data[self.name_field])) assert in_response(rv, message) return rv def update_fail(self, data, new_data, message): """Test that updating a model with the given data fails""" self.add_success(data) return self.edit_fail(data[self.id_field], new_data, message) def delete_fail(self, id_, message): """Test that deleting the specified model fails""" rv = self.post((id_, self.delete_url), dict(post='yes')) assert in_response(rv, message) assert self.verify_object({self.id_field: id_}) return rv def bad_data_fail(self, good_data, bad_data, message): """Test that adding and updating a model with the given data fails """ self.add_fail(bad_data, message) self.update_fail(good_data, bad_data, message) def add_required_field_fail(self, field, data): """Test that adding a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() data[field] = '' self.add_fail(data, message) assert not self.verify_object(data) del data[field] self.add_fail(data, message) assert not self.verify_object(data) def update_required_field_fail(self, field, data): """Test that updating a model with a blank or missing required field fails """ message = '{} is required'.format(self.fields[field]) data = data.copy() id_ = data[self.id_field] self.add_success(data) data[field] = '' self.edit_fail(id_, data, message) assert not self.verify_object(data) del data[field] self.edit_fail(id_, data, message) assert not self.verify_object(data) # Delete base model? def required_field_fail(self, field, data): """Test that adding and updating a model with a blank or missing required field fails """ self.add_required_field_fail(field, data) self.update_required_field_fail(field, data) def add_existing_key_fail(self, data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) return self.add_fail(data, message) def update_existing_key_fail(self, data, new_data): """Test that adding a model with an existing key fails""" message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) rv = self.add_success(new_data) assert not in_response(rv, message) rv = self.update_fail(data, message) assert self.verify_object(new_data) return rv def existing_key_fail(self, data, new_data): """Test that adding and updating a model with an existing key fails """ message = 'exists' rv = self.add_success(data) assert not in_response(rv, message) self.add_fail(data, message) rv = self.add_success(new_data) assert not in_response(rv, message) self.update_fail(data, message) assert self.verify_object(new_data) def data_sorted(self, before_data, after_data, url): """Test that the models will be sorted in the correct order""" self.add_success(after_data) self.add_success(before_data) rv = self.get(url) after_index = rv.data.index(after_data[self.name_field].encode()) before_index = rv.data.index(before_data[self.name_field].encode()) assert after_index > before_index def delete_does_not_exist_fail(self, id_): """Test that deleting a model that does not exist fails""" assert is_404(self.get((id_, self.delete_url))) self.delete_fail(id_, 'does not exist') class CategoryTestCase(ClosetTestBase, ModelBase): def __init__(self, *args, **kwargs): super(ModelBase, self).__init__(*args, **kwargs) self.base_url = '/categories' self.name = 'category' self.nice_name = 'Category' self.fields = { 'name': 'Name', 'parent': 'Parent'} self.test_data = { 'pants': { 'name': 'Pants', 'slug': 'pants'}, 'shirts': { 'name': 'Shirts', 'slug': 'shirts'}, 'jeans': { 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'}, 't-shirts': { 'name': 'T-shirts', 'slug': 't-shirts', 'parent': 'shirts'}, 'hats': { 'name': 'Hats', 'slug': 'hats', 'parent': 'spam'}, 'polo-shirts': { 'name': 'Polo Shirts', 'slug': 'polo-shirts'}, 'symbols': { 'name': ':)', 'slug': ''}, 'keyword': { 'name': 'Add', 'slug': 'add-1'}} def setUp(self): super(CategoryTestCase, self).setUp() self.authenticate() def test_get_category_forms(self): """Test that the category forms are accessible""" self.get_add_form() self.get_edit_form(self.test_data['pants']) self.get_delete_confirmation_form(self.test_data['shirts']) def test_add_category(self): """Test that adding a category works""" self.add_success(self.test_data['pants']) def test_update_category(self): """Test that updating a category works""" self.update_success(self.test_data['pants'], self.test_data['shirts']) def test_delete_category(self): """Test that deleting a category works""" self.add_success(self.test_data['pants']) self.delete_success('pants') def test_add_child_category(self): """Test that adding a child category works""" self.add_success(self.test_data['pants']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') def test_update_child_category(self): """Test that updating child categories works""" self.add_success(self.test_data['pants']) self.add_success(self.test_data['shirts']) self.add_success(self.test_data['jeans']) rv = self.get('pants') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'Jeans') self.edit_success('jeans', self.test_data['t-shirts']) rv = self.get('pants') assert in_response(rv, 'This category is empty.') assert not in_response(rv, 'Jeans') assert not in_response(rv, 'T-Shirts') rv = self.get('shirts') assert not in_response(rv, 'This category is empty.') assert in_response(rv, 'T-Shirts') assert not in_response(rv, 'Jeans') def test_name_required(self): """Test that adding/updating a category without a name fails""" self.required_field_fail('name', self.test_data['pants']) def test_parent_does_not_exist(self): """Test that adding/updating a category with a non-existent parent fails """ self.bad_data_fail(self.test_data['pants'], self.test_data['hats'], 'Parent does not exist') def test_category_already_exists(self): self.existing_key_fail( self.test_data['pants'], self.test_data['shirts']) def test_categories_are_sorted(self): """Test that categories are sorted alphabetically by name""" self.data_sorted(self.test_data['shirts'], self.test_data['pants']) def test_delete_category_does_not_exist(self): """Test that deleting a category that doesn't exist fails""" self.delete_does_not_exist_fail('hats') def test_add_category_slug_special(self): """Test that adding a category with an incorrect name fails""" self.add_success(self.test_data['polo-shirts']) assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts')) self.add_fail(self.test_data['symbols'], '') self.add_success('Add') def test_update_category_slug_special(self): """Test that updating a category with an incorrect slug fails""" rv = self.app.post(self.get_category_url('add'), data=dict( name='Pants', slug='pants' ), follow_redirects=True) rv = self.app.post(self.get_category_url('pants', 'edit'), data=dict( name='Polo Shirts', slug='polo shirts' ), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data=dict( name=':)', slug=':)' ), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug is formatted incorrectly' in rv.data rv = self.app.post(self.get_category_url('pants', 'edit'), data=dict( name='Add', slug='add' ), follow_redirects=True) assert b'Edit Pants' in rv.data assert b'Slug "add" is not allowed' in rv.data if __name__ == '__main__': unittest.main()
flexible
{ "blob_id": "a5856e12c281ed6a252f499a380f9c51082ea740", "index": 3711, "step-1": "<mask token>\n\n\nclass ModelBase(unittest.TestCase):\n <mask token>\n <mask token>\n\n def get(self, url):\n \"\"\"Process a GET request to the app\"\"\"\n return self.app.get(get_url(url), follow_redirects=True)\n <mask token>\n\n def verify_object(self, data):\n \"\"\"Verify the model object data\"\"\"\n rv = self.get(data[self.id_field])\n result = not is_404(rv)\n if result:\n for key, value in data:\n if not in_response(rv, value):\n return False\n return result\n\n def get_add_form(self):\n \"\"\"Test that the \"add\" form is accessible and contains all the\n fields\n \"\"\"\n rv = self.get(self.add_url)\n assert not is_404(rv)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n <mask token>\n\n def get_delete_confirmation_form(self, data):\n \"\"\"Test that the delete confirmation form is accessible\"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.delete_url))\n assert not is_404(rv)\n assert in_response(rv, 'Delete {}'.format(data[self.name_field]))\n return rv\n\n def add_success(self, data):\n \"\"\"Test that adding a model with the given data succeeds\"\"\"\n rv = self.post(self.add_url, data)\n assert not in_response(rv, 'Add {}'.format(self.nice_name))\n assert self.verify_object(data)\n return rv\n\n def edit_success(self, id_, data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert not in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert self.verify_object(data)\n return rv\n <mask token>\n\n def delete_success(self, id_):\n \"\"\"Test that deleting the specified model succeeds\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert not self.verify_object({self.id_field: id_})\n return rv\n\n def add_fail(self, data, message):\n \"\"\"Test that adding a model with the given data fails\"\"\"\n rv = self.post(self.add_url, data)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n assert in_response(rv, message)\n return rv\n <mask token>\n <mask token>\n\n def delete_fail(self, id_, message):\n \"\"\"Test that deleting the specified model fails\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert in_response(rv, message)\n assert self.verify_object({self.id_field: id_})\n return rv\n\n def bad_data_fail(self, good_data, bad_data, message):\n \"\"\"Test that adding and updating a model with the given data\n fails\n \"\"\"\n self.add_fail(bad_data, message)\n self.update_fail(good_data, bad_data, message)\n\n def add_required_field_fail(self, field, data):\n \"\"\"Test that adding a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n data[field] = ''\n self.add_fail(data, message)\n assert not self.verify_object(data)\n del data[field]\n self.add_fail(data, message)\n assert not self.verify_object(data)\n <mask token>\n\n def required_field_fail(self, field, data):\n \"\"\"Test that adding and updating a model with a blank or missing\n required field fails\n \"\"\"\n self.add_required_field_fail(field, data)\n self.update_required_field_fail(field, data)\n\n def add_existing_key_fail(self, data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n return self.add_fail(data, message)\n <mask token>\n\n def existing_key_fail(self, data, new_data):\n \"\"\"Test that adding and updating a model with an existing key\n fails\n \"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n self.add_fail(data, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n self.update_fail(data, message)\n assert self.verify_object(new_data)\n <mask token>\n <mask token>\n\n\nclass CategoryTestCase(ClosetTestBase, ModelBase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/categories'\n self.name = 'category'\n self.nice_name = 'Category'\n self.fields = {'name': 'Name', 'parent': 'Parent'}\n self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'},\n 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': {\n 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'},\n 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent':\n 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent':\n 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug':\n 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''},\n 'keyword': {'name': 'Add', 'slug': 'add-1'}}\n\n def setUp(self):\n super(CategoryTestCase, self).setUp()\n self.authenticate()\n\n def test_get_category_forms(self):\n \"\"\"Test that the category forms are accessible\"\"\"\n self.get_add_form()\n self.get_edit_form(self.test_data['pants'])\n self.get_delete_confirmation_form(self.test_data['shirts'])\n\n def test_add_category(self):\n \"\"\"Test that adding a category works\"\"\"\n self.add_success(self.test_data['pants'])\n\n def test_update_category(self):\n \"\"\"Test that updating a category works\"\"\"\n self.update_success(self.test_data['pants'], self.test_data['shirts'])\n\n def test_delete_category(self):\n \"\"\"Test that deleting a category works\"\"\"\n self.add_success(self.test_data['pants'])\n self.delete_success('pants')\n\n def test_add_child_category(self):\n \"\"\"Test that adding a child category works\"\"\"\n self.add_success(self.test_data['pants'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n\n def test_update_child_category(self):\n \"\"\"Test that updating child categories works\"\"\"\n self.add_success(self.test_data['pants'])\n self.add_success(self.test_data['shirts'])\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n self.edit_success('jeans', self.test_data['t-shirts'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n assert not in_response(rv, 'Jeans')\n assert not in_response(rv, 'T-Shirts')\n rv = self.get('shirts')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'T-Shirts')\n assert not in_response(rv, 'Jeans')\n\n def test_name_required(self):\n \"\"\"Test that adding/updating a category without a name fails\"\"\"\n self.required_field_fail('name', self.test_data['pants'])\n\n def test_parent_does_not_exist(self):\n \"\"\"Test that adding/updating a category with a non-existent\n parent fails\n \"\"\"\n self.bad_data_fail(self.test_data['pants'], self.test_data['hats'],\n 'Parent does not exist')\n\n def test_category_already_exists(self):\n self.existing_key_fail(self.test_data['pants'], self.test_data[\n 'shirts'])\n\n def test_categories_are_sorted(self):\n \"\"\"Test that categories are sorted alphabetically by name\"\"\"\n self.data_sorted(self.test_data['shirts'], self.test_data['pants'])\n\n def test_delete_category_does_not_exist(self):\n \"\"\"Test that deleting a category that doesn't exist fails\"\"\"\n self.delete_does_not_exist_fail('hats')\n\n def test_add_category_slug_special(self):\n \"\"\"Test that adding a category with an incorrect name fails\"\"\"\n self.add_success(self.test_data['polo-shirts'])\n assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts'))\n self.add_fail(self.test_data['symbols'], '')\n self.add_success('Add')\n\n def test_update_category_slug_special(self):\n \"\"\"Test that updating a category with an incorrect slug fails\"\"\"\n rv = self.app.post(self.get_category_url('add'), data=dict(name=\n 'Pants', slug='pants'), follow_redirects=True)\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True\n )\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name=':)', slug=':)'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Add', slug='add'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug \"add\" is not allowed' in rv.data\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass ClosetTestCase(ClosetTestBase):\n <mask token>\n <mask token>\n\n\nclass ModelBase(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/'\n self.add_url = 'add'\n self.edit_url = 'edit'\n self.delete_url = 'delete'\n self.name = ''\n self.nice_name = ''\n self.name_field = 'name'\n self.id_field = 'slug'\n self.fields = {}\n\n def get_url(self, *args):\n \"\"\"Create a URL from a tuple of strings based on the base url\"\"\"\n try:\n url = '/'.join((self.base_url,) + args)\n except TypeError:\n url = '/'.join((self.base_url,) + args[0])\n return url.rstrip('/')\n\n def get(self, url):\n \"\"\"Process a GET request to the app\"\"\"\n return self.app.get(get_url(url), follow_redirects=True)\n\n def post(self, url, data):\n \"\"\"Process a POST request to the app\"\"\"\n return self.app.post(get_url(url), data=data, follow_redirects=True)\n\n def verify_object(self, data):\n \"\"\"Verify the model object data\"\"\"\n rv = self.get(data[self.id_field])\n result = not is_404(rv)\n if result:\n for key, value in data:\n if not in_response(rv, value):\n return False\n return result\n\n def get_add_form(self):\n \"\"\"Test that the \"add\" form is accessible and contains all the\n fields\n \"\"\"\n rv = self.get(self.add_url)\n assert not is_404(rv)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_edit_form(self, data):\n \"\"\"Test that the edit form is accessible and contains all the\n fields\n \"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.edit_url))\n assert not is_404(rv)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_delete_confirmation_form(self, data):\n \"\"\"Test that the delete confirmation form is accessible\"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.delete_url))\n assert not is_404(rv)\n assert in_response(rv, 'Delete {}'.format(data[self.name_field]))\n return rv\n\n def add_success(self, data):\n \"\"\"Test that adding a model with the given data succeeds\"\"\"\n rv = self.post(self.add_url, data)\n assert not in_response(rv, 'Add {}'.format(self.nice_name))\n assert self.verify_object(data)\n return rv\n\n def edit_success(self, id_, data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert not in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert self.verify_object(data)\n return rv\n\n def update_success(self, data, new_data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n self.add_success(data)\n return self.edit_success(data[self.id_field], new_data)\n\n def delete_success(self, id_):\n \"\"\"Test that deleting the specified model succeeds\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert not self.verify_object({self.id_field: id_})\n return rv\n\n def add_fail(self, data, message):\n \"\"\"Test that adding a model with the given data fails\"\"\"\n rv = self.post(self.add_url, data)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n assert in_response(rv, message)\n return rv\n\n def edit_fail(self, id_, data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert in_response(rv, message)\n return rv\n\n def update_fail(self, data, new_data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n self.add_success(data)\n return self.edit_fail(data[self.id_field], new_data, message)\n\n def delete_fail(self, id_, message):\n \"\"\"Test that deleting the specified model fails\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert in_response(rv, message)\n assert self.verify_object({self.id_field: id_})\n return rv\n\n def bad_data_fail(self, good_data, bad_data, message):\n \"\"\"Test that adding and updating a model with the given data\n fails\n \"\"\"\n self.add_fail(bad_data, message)\n self.update_fail(good_data, bad_data, message)\n\n def add_required_field_fail(self, field, data):\n \"\"\"Test that adding a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n data[field] = ''\n self.add_fail(data, message)\n assert not self.verify_object(data)\n del data[field]\n self.add_fail(data, message)\n assert not self.verify_object(data)\n\n def update_required_field_fail(self, field, data):\n \"\"\"Test that updating a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n id_ = data[self.id_field]\n self.add_success(data)\n data[field] = ''\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n del data[field]\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n\n def required_field_fail(self, field, data):\n \"\"\"Test that adding and updating a model with a blank or missing\n required field fails\n \"\"\"\n self.add_required_field_fail(field, data)\n self.update_required_field_fail(field, data)\n\n def add_existing_key_fail(self, data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n return self.add_fail(data, message)\n\n def update_existing_key_fail(self, data, new_data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n rv = self.update_fail(data, message)\n assert self.verify_object(new_data)\n return rv\n\n def existing_key_fail(self, data, new_data):\n \"\"\"Test that adding and updating a model with an existing key\n fails\n \"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n self.add_fail(data, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n self.update_fail(data, message)\n assert self.verify_object(new_data)\n\n def data_sorted(self, before_data, after_data, url):\n \"\"\"Test that the models will be sorted in the correct order\"\"\"\n self.add_success(after_data)\n self.add_success(before_data)\n rv = self.get(url)\n after_index = rv.data.index(after_data[self.name_field].encode())\n before_index = rv.data.index(before_data[self.name_field].encode())\n assert after_index > before_index\n\n def delete_does_not_exist_fail(self, id_):\n \"\"\"Test that deleting a model that does not exist fails\"\"\"\n assert is_404(self.get((id_, self.delete_url)))\n self.delete_fail(id_, 'does not exist')\n\n\nclass CategoryTestCase(ClosetTestBase, ModelBase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/categories'\n self.name = 'category'\n self.nice_name = 'Category'\n self.fields = {'name': 'Name', 'parent': 'Parent'}\n self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'},\n 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': {\n 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'},\n 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent':\n 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent':\n 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug':\n 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''},\n 'keyword': {'name': 'Add', 'slug': 'add-1'}}\n\n def setUp(self):\n super(CategoryTestCase, self).setUp()\n self.authenticate()\n\n def test_get_category_forms(self):\n \"\"\"Test that the category forms are accessible\"\"\"\n self.get_add_form()\n self.get_edit_form(self.test_data['pants'])\n self.get_delete_confirmation_form(self.test_data['shirts'])\n\n def test_add_category(self):\n \"\"\"Test that adding a category works\"\"\"\n self.add_success(self.test_data['pants'])\n\n def test_update_category(self):\n \"\"\"Test that updating a category works\"\"\"\n self.update_success(self.test_data['pants'], self.test_data['shirts'])\n\n def test_delete_category(self):\n \"\"\"Test that deleting a category works\"\"\"\n self.add_success(self.test_data['pants'])\n self.delete_success('pants')\n\n def test_add_child_category(self):\n \"\"\"Test that adding a child category works\"\"\"\n self.add_success(self.test_data['pants'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n\n def test_update_child_category(self):\n \"\"\"Test that updating child categories works\"\"\"\n self.add_success(self.test_data['pants'])\n self.add_success(self.test_data['shirts'])\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n self.edit_success('jeans', self.test_data['t-shirts'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n assert not in_response(rv, 'Jeans')\n assert not in_response(rv, 'T-Shirts')\n rv = self.get('shirts')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'T-Shirts')\n assert not in_response(rv, 'Jeans')\n\n def test_name_required(self):\n \"\"\"Test that adding/updating a category without a name fails\"\"\"\n self.required_field_fail('name', self.test_data['pants'])\n\n def test_parent_does_not_exist(self):\n \"\"\"Test that adding/updating a category with a non-existent\n parent fails\n \"\"\"\n self.bad_data_fail(self.test_data['pants'], self.test_data['hats'],\n 'Parent does not exist')\n\n def test_category_already_exists(self):\n self.existing_key_fail(self.test_data['pants'], self.test_data[\n 'shirts'])\n\n def test_categories_are_sorted(self):\n \"\"\"Test that categories are sorted alphabetically by name\"\"\"\n self.data_sorted(self.test_data['shirts'], self.test_data['pants'])\n\n def test_delete_category_does_not_exist(self):\n \"\"\"Test that deleting a category that doesn't exist fails\"\"\"\n self.delete_does_not_exist_fail('hats')\n\n def test_add_category_slug_special(self):\n \"\"\"Test that adding a category with an incorrect name fails\"\"\"\n self.add_success(self.test_data['polo-shirts'])\n assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts'))\n self.add_fail(self.test_data['symbols'], '')\n self.add_success('Add')\n\n def test_update_category_slug_special(self):\n \"\"\"Test that updating a category with an incorrect slug fails\"\"\"\n rv = self.app.post(self.get_category_url('add'), data=dict(name=\n 'Pants', slug='pants'), follow_redirects=True)\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True\n )\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name=':)', slug=':)'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Add', slug='add'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug \"add\" is not allowed' in rv.data\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass ClosetTestCase(ClosetTestBase):\n <mask token>\n\n def test_login_logout(self):\n \"\"\"Make sure login and logout works\"\"\"\n rv = self.login(closet.app.config['USERNAME'], closet.app.config[\n 'PASSWORD'])\n assert b'You were logged in' in rv.data\n rv = self.logout()\n assert b'You were logged out' in rv.data\n rv = self.login(closet.app.config['USERNAME'] + 'x', closet.app.\n config['PASSWORD'])\n assert b'Invalid username' in rv.data\n rv = self.login(closet.app.config['USERNAME'], closet.app.config[\n 'PASSWORD'] + 'x')\n assert b'Invalid password' in rv.data\n\n\nclass ModelBase(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/'\n self.add_url = 'add'\n self.edit_url = 'edit'\n self.delete_url = 'delete'\n self.name = ''\n self.nice_name = ''\n self.name_field = 'name'\n self.id_field = 'slug'\n self.fields = {}\n\n def get_url(self, *args):\n \"\"\"Create a URL from a tuple of strings based on the base url\"\"\"\n try:\n url = '/'.join((self.base_url,) + args)\n except TypeError:\n url = '/'.join((self.base_url,) + args[0])\n return url.rstrip('/')\n\n def get(self, url):\n \"\"\"Process a GET request to the app\"\"\"\n return self.app.get(get_url(url), follow_redirects=True)\n\n def post(self, url, data):\n \"\"\"Process a POST request to the app\"\"\"\n return self.app.post(get_url(url), data=data, follow_redirects=True)\n\n def verify_object(self, data):\n \"\"\"Verify the model object data\"\"\"\n rv = self.get(data[self.id_field])\n result = not is_404(rv)\n if result:\n for key, value in data:\n if not in_response(rv, value):\n return False\n return result\n\n def get_add_form(self):\n \"\"\"Test that the \"add\" form is accessible and contains all the\n fields\n \"\"\"\n rv = self.get(self.add_url)\n assert not is_404(rv)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_edit_form(self, data):\n \"\"\"Test that the edit form is accessible and contains all the\n fields\n \"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.edit_url))\n assert not is_404(rv)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_delete_confirmation_form(self, data):\n \"\"\"Test that the delete confirmation form is accessible\"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.delete_url))\n assert not is_404(rv)\n assert in_response(rv, 'Delete {}'.format(data[self.name_field]))\n return rv\n\n def add_success(self, data):\n \"\"\"Test that adding a model with the given data succeeds\"\"\"\n rv = self.post(self.add_url, data)\n assert not in_response(rv, 'Add {}'.format(self.nice_name))\n assert self.verify_object(data)\n return rv\n\n def edit_success(self, id_, data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert not in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert self.verify_object(data)\n return rv\n\n def update_success(self, data, new_data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n self.add_success(data)\n return self.edit_success(data[self.id_field], new_data)\n\n def delete_success(self, id_):\n \"\"\"Test that deleting the specified model succeeds\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert not self.verify_object({self.id_field: id_})\n return rv\n\n def add_fail(self, data, message):\n \"\"\"Test that adding a model with the given data fails\"\"\"\n rv = self.post(self.add_url, data)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n assert in_response(rv, message)\n return rv\n\n def edit_fail(self, id_, data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert in_response(rv, message)\n return rv\n\n def update_fail(self, data, new_data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n self.add_success(data)\n return self.edit_fail(data[self.id_field], new_data, message)\n\n def delete_fail(self, id_, message):\n \"\"\"Test that deleting the specified model fails\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert in_response(rv, message)\n assert self.verify_object({self.id_field: id_})\n return rv\n\n def bad_data_fail(self, good_data, bad_data, message):\n \"\"\"Test that adding and updating a model with the given data\n fails\n \"\"\"\n self.add_fail(bad_data, message)\n self.update_fail(good_data, bad_data, message)\n\n def add_required_field_fail(self, field, data):\n \"\"\"Test that adding a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n data[field] = ''\n self.add_fail(data, message)\n assert not self.verify_object(data)\n del data[field]\n self.add_fail(data, message)\n assert not self.verify_object(data)\n\n def update_required_field_fail(self, field, data):\n \"\"\"Test that updating a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n id_ = data[self.id_field]\n self.add_success(data)\n data[field] = ''\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n del data[field]\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n\n def required_field_fail(self, field, data):\n \"\"\"Test that adding and updating a model with a blank or missing\n required field fails\n \"\"\"\n self.add_required_field_fail(field, data)\n self.update_required_field_fail(field, data)\n\n def add_existing_key_fail(self, data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n return self.add_fail(data, message)\n\n def update_existing_key_fail(self, data, new_data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n rv = self.update_fail(data, message)\n assert self.verify_object(new_data)\n return rv\n\n def existing_key_fail(self, data, new_data):\n \"\"\"Test that adding and updating a model with an existing key\n fails\n \"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n self.add_fail(data, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n self.update_fail(data, message)\n assert self.verify_object(new_data)\n\n def data_sorted(self, before_data, after_data, url):\n \"\"\"Test that the models will be sorted in the correct order\"\"\"\n self.add_success(after_data)\n self.add_success(before_data)\n rv = self.get(url)\n after_index = rv.data.index(after_data[self.name_field].encode())\n before_index = rv.data.index(before_data[self.name_field].encode())\n assert after_index > before_index\n\n def delete_does_not_exist_fail(self, id_):\n \"\"\"Test that deleting a model that does not exist fails\"\"\"\n assert is_404(self.get((id_, self.delete_url)))\n self.delete_fail(id_, 'does not exist')\n\n\nclass CategoryTestCase(ClosetTestBase, ModelBase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/categories'\n self.name = 'category'\n self.nice_name = 'Category'\n self.fields = {'name': 'Name', 'parent': 'Parent'}\n self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'},\n 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': {\n 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'},\n 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent':\n 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent':\n 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug':\n 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''},\n 'keyword': {'name': 'Add', 'slug': 'add-1'}}\n\n def setUp(self):\n super(CategoryTestCase, self).setUp()\n self.authenticate()\n\n def test_get_category_forms(self):\n \"\"\"Test that the category forms are accessible\"\"\"\n self.get_add_form()\n self.get_edit_form(self.test_data['pants'])\n self.get_delete_confirmation_form(self.test_data['shirts'])\n\n def test_add_category(self):\n \"\"\"Test that adding a category works\"\"\"\n self.add_success(self.test_data['pants'])\n\n def test_update_category(self):\n \"\"\"Test that updating a category works\"\"\"\n self.update_success(self.test_data['pants'], self.test_data['shirts'])\n\n def test_delete_category(self):\n \"\"\"Test that deleting a category works\"\"\"\n self.add_success(self.test_data['pants'])\n self.delete_success('pants')\n\n def test_add_child_category(self):\n \"\"\"Test that adding a child category works\"\"\"\n self.add_success(self.test_data['pants'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n\n def test_update_child_category(self):\n \"\"\"Test that updating child categories works\"\"\"\n self.add_success(self.test_data['pants'])\n self.add_success(self.test_data['shirts'])\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n self.edit_success('jeans', self.test_data['t-shirts'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n assert not in_response(rv, 'Jeans')\n assert not in_response(rv, 'T-Shirts')\n rv = self.get('shirts')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'T-Shirts')\n assert not in_response(rv, 'Jeans')\n\n def test_name_required(self):\n \"\"\"Test that adding/updating a category without a name fails\"\"\"\n self.required_field_fail('name', self.test_data['pants'])\n\n def test_parent_does_not_exist(self):\n \"\"\"Test that adding/updating a category with a non-existent\n parent fails\n \"\"\"\n self.bad_data_fail(self.test_data['pants'], self.test_data['hats'],\n 'Parent does not exist')\n\n def test_category_already_exists(self):\n self.existing_key_fail(self.test_data['pants'], self.test_data[\n 'shirts'])\n\n def test_categories_are_sorted(self):\n \"\"\"Test that categories are sorted alphabetically by name\"\"\"\n self.data_sorted(self.test_data['shirts'], self.test_data['pants'])\n\n def test_delete_category_does_not_exist(self):\n \"\"\"Test that deleting a category that doesn't exist fails\"\"\"\n self.delete_does_not_exist_fail('hats')\n\n def test_add_category_slug_special(self):\n \"\"\"Test that adding a category with an incorrect name fails\"\"\"\n self.add_success(self.test_data['polo-shirts'])\n assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts'))\n self.add_fail(self.test_data['symbols'], '')\n self.add_success('Add')\n\n def test_update_category_slug_special(self):\n \"\"\"Test that updating a category with an incorrect slug fails\"\"\"\n rv = self.app.post(self.get_category_url('add'), data=dict(name=\n 'Pants', slug='pants'), follow_redirects=True)\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True\n )\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name=':)', slug=':)'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Add', slug='add'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug \"add\" is not allowed' in rv.data\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass ClosetTestBase(unittest.TestCase):\n\n def setUp(self):\n \"\"\"Set up test environment befor each test\"\"\"\n self.db_fd, closet.app.config['DATABASE'] = tempfile.mkstemp()\n closet.app.config['TESTING'] = True\n self.app = closet.app.test_client()\n closet.init_db()\n <mask token>\n\n def login(self, username, password):\n \"\"\"Login to test website as specified user with the specified\n password\n \"\"\"\n return self.app.post('/login', data=dict(username=username,\n password=password), follow_redirects=True)\n <mask token>\n\n def authenticate(self):\n \"\"\"Login to test website as the standard test user\"\"\"\n self.login(closet.app.config['USERNAME'], closet.app.config['PASSWORD']\n )\n\n\nclass ClosetTestCase(ClosetTestBase):\n\n def test_empty_db(self):\n \"\"\"Start with a blank database.\"\"\"\n rv = self.app.get('/')\n assert b'Your closet is empty.' in rv.data\n\n def test_login_logout(self):\n \"\"\"Make sure login and logout works\"\"\"\n rv = self.login(closet.app.config['USERNAME'], closet.app.config[\n 'PASSWORD'])\n assert b'You were logged in' in rv.data\n rv = self.logout()\n assert b'You were logged out' in rv.data\n rv = self.login(closet.app.config['USERNAME'] + 'x', closet.app.\n config['PASSWORD'])\n assert b'Invalid username' in rv.data\n rv = self.login(closet.app.config['USERNAME'], closet.app.config[\n 'PASSWORD'] + 'x')\n assert b'Invalid password' in rv.data\n\n\nclass ModelBase(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/'\n self.add_url = 'add'\n self.edit_url = 'edit'\n self.delete_url = 'delete'\n self.name = ''\n self.nice_name = ''\n self.name_field = 'name'\n self.id_field = 'slug'\n self.fields = {}\n\n def get_url(self, *args):\n \"\"\"Create a URL from a tuple of strings based on the base url\"\"\"\n try:\n url = '/'.join((self.base_url,) + args)\n except TypeError:\n url = '/'.join((self.base_url,) + args[0])\n return url.rstrip('/')\n\n def get(self, url):\n \"\"\"Process a GET request to the app\"\"\"\n return self.app.get(get_url(url), follow_redirects=True)\n\n def post(self, url, data):\n \"\"\"Process a POST request to the app\"\"\"\n return self.app.post(get_url(url), data=data, follow_redirects=True)\n\n def verify_object(self, data):\n \"\"\"Verify the model object data\"\"\"\n rv = self.get(data[self.id_field])\n result = not is_404(rv)\n if result:\n for key, value in data:\n if not in_response(rv, value):\n return False\n return result\n\n def get_add_form(self):\n \"\"\"Test that the \"add\" form is accessible and contains all the\n fields\n \"\"\"\n rv = self.get(self.add_url)\n assert not is_404(rv)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_edit_form(self, data):\n \"\"\"Test that the edit form is accessible and contains all the\n fields\n \"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.edit_url))\n assert not is_404(rv)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_delete_confirmation_form(self, data):\n \"\"\"Test that the delete confirmation form is accessible\"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.delete_url))\n assert not is_404(rv)\n assert in_response(rv, 'Delete {}'.format(data[self.name_field]))\n return rv\n\n def add_success(self, data):\n \"\"\"Test that adding a model with the given data succeeds\"\"\"\n rv = self.post(self.add_url, data)\n assert not in_response(rv, 'Add {}'.format(self.nice_name))\n assert self.verify_object(data)\n return rv\n\n def edit_success(self, id_, data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert not in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert self.verify_object(data)\n return rv\n\n def update_success(self, data, new_data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n self.add_success(data)\n return self.edit_success(data[self.id_field], new_data)\n\n def delete_success(self, id_):\n \"\"\"Test that deleting the specified model succeeds\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert not self.verify_object({self.id_field: id_})\n return rv\n\n def add_fail(self, data, message):\n \"\"\"Test that adding a model with the given data fails\"\"\"\n rv = self.post(self.add_url, data)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n assert in_response(rv, message)\n return rv\n\n def edit_fail(self, id_, data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert in_response(rv, message)\n return rv\n\n def update_fail(self, data, new_data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n self.add_success(data)\n return self.edit_fail(data[self.id_field], new_data, message)\n\n def delete_fail(self, id_, message):\n \"\"\"Test that deleting the specified model fails\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert in_response(rv, message)\n assert self.verify_object({self.id_field: id_})\n return rv\n\n def bad_data_fail(self, good_data, bad_data, message):\n \"\"\"Test that adding and updating a model with the given data\n fails\n \"\"\"\n self.add_fail(bad_data, message)\n self.update_fail(good_data, bad_data, message)\n\n def add_required_field_fail(self, field, data):\n \"\"\"Test that adding a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n data[field] = ''\n self.add_fail(data, message)\n assert not self.verify_object(data)\n del data[field]\n self.add_fail(data, message)\n assert not self.verify_object(data)\n\n def update_required_field_fail(self, field, data):\n \"\"\"Test that updating a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n id_ = data[self.id_field]\n self.add_success(data)\n data[field] = ''\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n del data[field]\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n\n def required_field_fail(self, field, data):\n \"\"\"Test that adding and updating a model with a blank or missing\n required field fails\n \"\"\"\n self.add_required_field_fail(field, data)\n self.update_required_field_fail(field, data)\n\n def add_existing_key_fail(self, data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n return self.add_fail(data, message)\n\n def update_existing_key_fail(self, data, new_data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n rv = self.update_fail(data, message)\n assert self.verify_object(new_data)\n return rv\n\n def existing_key_fail(self, data, new_data):\n \"\"\"Test that adding and updating a model with an existing key\n fails\n \"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n self.add_fail(data, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n self.update_fail(data, message)\n assert self.verify_object(new_data)\n\n def data_sorted(self, before_data, after_data, url):\n \"\"\"Test that the models will be sorted in the correct order\"\"\"\n self.add_success(after_data)\n self.add_success(before_data)\n rv = self.get(url)\n after_index = rv.data.index(after_data[self.name_field].encode())\n before_index = rv.data.index(before_data[self.name_field].encode())\n assert after_index > before_index\n\n def delete_does_not_exist_fail(self, id_):\n \"\"\"Test that deleting a model that does not exist fails\"\"\"\n assert is_404(self.get((id_, self.delete_url)))\n self.delete_fail(id_, 'does not exist')\n\n\nclass CategoryTestCase(ClosetTestBase, ModelBase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/categories'\n self.name = 'category'\n self.nice_name = 'Category'\n self.fields = {'name': 'Name', 'parent': 'Parent'}\n self.test_data = {'pants': {'name': 'Pants', 'slug': 'pants'},\n 'shirts': {'name': 'Shirts', 'slug': 'shirts'}, 'jeans': {\n 'name': 'Jeans', 'slug': 'jeans', 'parent': 'pants'},\n 't-shirts': {'name': 'T-shirts', 'slug': 't-shirts', 'parent':\n 'shirts'}, 'hats': {'name': 'Hats', 'slug': 'hats', 'parent':\n 'spam'}, 'polo-shirts': {'name': 'Polo Shirts', 'slug':\n 'polo-shirts'}, 'symbols': {'name': ':)', 'slug': ''},\n 'keyword': {'name': 'Add', 'slug': 'add-1'}}\n\n def setUp(self):\n super(CategoryTestCase, self).setUp()\n self.authenticate()\n\n def test_get_category_forms(self):\n \"\"\"Test that the category forms are accessible\"\"\"\n self.get_add_form()\n self.get_edit_form(self.test_data['pants'])\n self.get_delete_confirmation_form(self.test_data['shirts'])\n\n def test_add_category(self):\n \"\"\"Test that adding a category works\"\"\"\n self.add_success(self.test_data['pants'])\n\n def test_update_category(self):\n \"\"\"Test that updating a category works\"\"\"\n self.update_success(self.test_data['pants'], self.test_data['shirts'])\n\n def test_delete_category(self):\n \"\"\"Test that deleting a category works\"\"\"\n self.add_success(self.test_data['pants'])\n self.delete_success('pants')\n\n def test_add_child_category(self):\n \"\"\"Test that adding a child category works\"\"\"\n self.add_success(self.test_data['pants'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n\n def test_update_child_category(self):\n \"\"\"Test that updating child categories works\"\"\"\n self.add_success(self.test_data['pants'])\n self.add_success(self.test_data['shirts'])\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n self.edit_success('jeans', self.test_data['t-shirts'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n assert not in_response(rv, 'Jeans')\n assert not in_response(rv, 'T-Shirts')\n rv = self.get('shirts')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'T-Shirts')\n assert not in_response(rv, 'Jeans')\n\n def test_name_required(self):\n \"\"\"Test that adding/updating a category without a name fails\"\"\"\n self.required_field_fail('name', self.test_data['pants'])\n\n def test_parent_does_not_exist(self):\n \"\"\"Test that adding/updating a category with a non-existent\n parent fails\n \"\"\"\n self.bad_data_fail(self.test_data['pants'], self.test_data['hats'],\n 'Parent does not exist')\n\n def test_category_already_exists(self):\n self.existing_key_fail(self.test_data['pants'], self.test_data[\n 'shirts'])\n\n def test_categories_are_sorted(self):\n \"\"\"Test that categories are sorted alphabetically by name\"\"\"\n self.data_sorted(self.test_data['shirts'], self.test_data['pants'])\n\n def test_delete_category_does_not_exist(self):\n \"\"\"Test that deleting a category that doesn't exist fails\"\"\"\n self.delete_does_not_exist_fail('hats')\n\n def test_add_category_slug_special(self):\n \"\"\"Test that adding a category with an incorrect name fails\"\"\"\n self.add_success(self.test_data['polo-shirts'])\n assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts'))\n self.add_fail(self.test_data['symbols'], '')\n self.add_success('Add')\n\n def test_update_category_slug_special(self):\n \"\"\"Test that updating a category with an incorrect slug fails\"\"\"\n rv = self.app.post(self.get_category_url('add'), data=dict(name=\n 'Pants', slug='pants'), follow_redirects=True)\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Polo Shirts', slug='polo shirts'), follow_redirects=True\n )\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name=':)', slug=':)'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=\n dict(name='Add', slug='add'), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug \"add\" is not allowed' in rv.data\n\n\n<mask token>\n", "step-5": "import os\nimport closet\nimport unittest\nimport tempfile\n\n\ndef in_response(response, value):\n return value.encode() in response.data\n\n\ndef is_404(response):\n response.status_code == 404\n\n\nclass ClosetTestBase(unittest.TestCase):\n\n def setUp(self):\n \"\"\"Set up test environment befor each test\"\"\"\n self.db_fd, closet.app.config['DATABASE'] = tempfile.mkstemp()\n closet.app.config['TESTING'] = True\n self.app = closet.app.test_client()\n closet.init_db()\n\n def tearDown(self):\n \"\"\"Tear down test environment after each test\"\"\"\n os.close(self.db_fd)\n os.unlink(closet.app.config['DATABASE'])\n\n def login(self, username, password):\n \"\"\"Login to test website as specified user with the specified\n password\n \"\"\"\n return self.app.post('/login', data=dict(\n username=username,\n password=password\n ), follow_redirects=True)\n\n def logout(self):\n \"\"\"Logout of test website\"\"\"\n return self.app.get('/logout', follow_redirects=True)\n\n def authenticate(self):\n \"\"\"Login to test website as the standard test user\"\"\"\n self.login(closet.app.config['USERNAME'],\n closet.app.config['PASSWORD'])\n\n\nclass ClosetTestCase(ClosetTestBase):\n\n # Generic Tests\n\n def test_empty_db(self):\n \"\"\"Start with a blank database.\"\"\"\n rv = self.app.get('/')\n assert b'Your closet is empty.' in rv.data\n\n def test_login_logout(self):\n \"\"\"Make sure login and logout works\"\"\"\n rv = self.login(closet.app.config['USERNAME'],\n closet.app.config['PASSWORD'])\n assert b'You were logged in' in rv.data\n rv = self.logout()\n assert b'You were logged out' in rv.data\n rv = self.login(closet.app.config['USERNAME'] + 'x',\n closet.app.config['PASSWORD'])\n assert b'Invalid username' in rv.data\n rv = self.login(closet.app.config['USERNAME'],\n closet.app.config['PASSWORD'] + 'x')\n assert b'Invalid password' in rv.data\n\n\nclass ModelBase(unittest.TestCase):\n\n # Model based view test helpers\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/'\n self.add_url = 'add'\n self.edit_url = 'edit'\n self.delete_url = 'delete'\n self.name = ''\n self.nice_name = ''\n self.name_field = 'name'\n self.id_field = 'slug'\n self.fields = {}\n\n def get_url(self, *args):\n \"\"\"Create a URL from a tuple of strings based on the base url\"\"\"\n try:\n url = '/'.join((self.base_url, ) + args)\n except TypeError:\n url = '/'.join((self.base_url, ) + args[0])\n return url.rstrip('/')\n\n def get(self, url):\n \"\"\"Process a GET request to the app\"\"\"\n return self.app.get(get_url(url), follow_redirects=True)\n\n def post(self, url, data):\n \"\"\"Process a POST request to the app\"\"\"\n return self.app.post(get_url(url), data=data, follow_redirects=True)\n\n def verify_object(self, data):\n \"\"\"Verify the model object data\"\"\"\n rv = self.get(data[self.id_field])\n result = not is_404(rv)\n if result:\n for key, value in data:\n if not in_response(rv, value):\n return False\n return result\n\n def get_add_form(self):\n \"\"\"Test that the \"add\" form is accessible and contains all the\n fields\n \"\"\"\n rv = self.get(self.add_url)\n assert not is_404(rv)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_edit_form(self, data):\n \"\"\"Test that the edit form is accessible and contains all the\n fields\n \"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.edit_url))\n assert not is_404(rv)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n for field, name in self.fields:\n assert in_response(rv, name)\n return rv\n\n def get_delete_confirmation_form(self, data):\n \"\"\"Test that the delete confirmation form is accessible\"\"\"\n self.add_success(data)\n rv = self.get((data[self.id_field], self.delete_url))\n assert not is_404(rv)\n assert in_response(rv, 'Delete {}'.format(data[self.name_field]))\n return rv\n\n def add_success(self, data):\n \"\"\"Test that adding a model with the given data succeeds\"\"\"\n rv = self.post(self.add_url, data)\n assert not in_response(rv, 'Add {}'.format(self.nice_name))\n assert self.verify_object(data)\n return rv\n\n def edit_success(self, id_, data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert not in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert self.verify_object(data)\n return rv\n\n def update_success(self, data, new_data):\n \"\"\"Test that updating a model with the given data succeeds\"\"\"\n self.add_success(data)\n return self.edit_success(data[self.id_field], new_data)\n\n def delete_success(self, id_):\n \"\"\"Test that deleting the specified model succeeds\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert not self.verify_object({self.id_field: id_})\n return rv\n\n def add_fail(self, data, message):\n \"\"\"Test that adding a model with the given data fails\"\"\"\n rv = self.post(self.add_url, data)\n assert in_response(rv, 'Add {}'.format(self.nice_name))\n assert in_response(rv, message)\n return rv\n\n def edit_fail(self, id_, data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n rv = self.post((id_, self.edit_url), data)\n assert in_response(rv, 'Edit {}'.format(data[self.name_field]))\n assert in_response(rv, message)\n return rv\n\n def update_fail(self, data, new_data, message):\n \"\"\"Test that updating a model with the given data fails\"\"\"\n self.add_success(data)\n return self.edit_fail(data[self.id_field], new_data, message)\n\n def delete_fail(self, id_, message):\n \"\"\"Test that deleting the specified model fails\"\"\"\n rv = self.post((id_, self.delete_url), dict(post='yes'))\n assert in_response(rv, message)\n assert self.verify_object({self.id_field: id_})\n return rv\n\n def bad_data_fail(self, good_data, bad_data, message):\n \"\"\"Test that adding and updating a model with the given data\n fails\n \"\"\"\n self.add_fail(bad_data, message)\n self.update_fail(good_data, bad_data, message)\n\n def add_required_field_fail(self, field, data):\n \"\"\"Test that adding a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n\n data[field] = ''\n self.add_fail(data, message)\n assert not self.verify_object(data)\n\n del data[field]\n self.add_fail(data, message)\n assert not self.verify_object(data)\n\n def update_required_field_fail(self, field, data):\n \"\"\"Test that updating a model with a blank or missing required\n field fails\n \"\"\"\n message = '{} is required'.format(self.fields[field])\n data = data.copy()\n id_ = data[self.id_field]\n self.add_success(data)\n\n data[field] = ''\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n\n del data[field]\n self.edit_fail(id_, data, message)\n assert not self.verify_object(data)\n\n # Delete base model?\n\n def required_field_fail(self, field, data):\n \"\"\"Test that adding and updating a model with a blank or missing\n required field fails\n \"\"\"\n self.add_required_field_fail(field, data)\n self.update_required_field_fail(field, data)\n\n def add_existing_key_fail(self, data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n return self.add_fail(data, message)\n\n def update_existing_key_fail(self, data, new_data):\n \"\"\"Test that adding a model with an existing key fails\"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n rv = self.update_fail(data, message)\n assert self.verify_object(new_data)\n return rv\n\n def existing_key_fail(self, data, new_data):\n \"\"\"Test that adding and updating a model with an existing key\n fails\n \"\"\"\n message = 'exists'\n rv = self.add_success(data)\n assert not in_response(rv, message)\n self.add_fail(data, message)\n rv = self.add_success(new_data)\n assert not in_response(rv, message)\n self.update_fail(data, message)\n assert self.verify_object(new_data)\n\n def data_sorted(self, before_data, after_data, url):\n \"\"\"Test that the models will be sorted in the correct order\"\"\"\n self.add_success(after_data)\n self.add_success(before_data)\n\n rv = self.get(url)\n after_index = rv.data.index(after_data[self.name_field].encode())\n before_index = rv.data.index(before_data[self.name_field].encode())\n assert after_index > before_index\n\n def delete_does_not_exist_fail(self, id_):\n \"\"\"Test that deleting a model that does not exist fails\"\"\"\n assert is_404(self.get((id_, self.delete_url)))\n self.delete_fail(id_, 'does not exist')\n\n\nclass CategoryTestCase(ClosetTestBase, ModelBase):\n\n def __init__(self, *args, **kwargs):\n super(ModelBase, self).__init__(*args, **kwargs)\n self.base_url = '/categories'\n self.name = 'category'\n self.nice_name = 'Category'\n self.fields = {\n 'name': 'Name',\n 'parent': 'Parent'}\n self.test_data = {\n 'pants': {\n 'name': 'Pants',\n 'slug': 'pants'},\n 'shirts': {\n 'name': 'Shirts',\n 'slug': 'shirts'},\n 'jeans': {\n 'name': 'Jeans',\n 'slug': 'jeans',\n 'parent': 'pants'},\n 't-shirts': {\n 'name': 'T-shirts',\n 'slug': 't-shirts',\n 'parent': 'shirts'},\n 'hats': {\n 'name': 'Hats',\n 'slug': 'hats',\n 'parent': 'spam'},\n 'polo-shirts': {\n 'name': 'Polo Shirts',\n 'slug': 'polo-shirts'},\n 'symbols': {\n 'name': ':)',\n 'slug': ''},\n 'keyword': {\n 'name': 'Add',\n 'slug': 'add-1'}}\n\n def setUp(self):\n super(CategoryTestCase, self).setUp()\n self.authenticate()\n\n def test_get_category_forms(self):\n \"\"\"Test that the category forms are accessible\"\"\"\n self.get_add_form()\n self.get_edit_form(self.test_data['pants'])\n self.get_delete_confirmation_form(self.test_data['shirts'])\n\n def test_add_category(self):\n \"\"\"Test that adding a category works\"\"\"\n self.add_success(self.test_data['pants'])\n\n def test_update_category(self):\n \"\"\"Test that updating a category works\"\"\"\n self.update_success(self.test_data['pants'], self.test_data['shirts'])\n\n def test_delete_category(self):\n \"\"\"Test that deleting a category works\"\"\"\n self.add_success(self.test_data['pants'])\n self.delete_success('pants')\n\n def test_add_child_category(self):\n \"\"\"Test that adding a child category works\"\"\"\n self.add_success(self.test_data['pants'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n\n def test_update_child_category(self):\n \"\"\"Test that updating child categories works\"\"\"\n self.add_success(self.test_data['pants'])\n self.add_success(self.test_data['shirts'])\n\n self.add_success(self.test_data['jeans'])\n rv = self.get('pants')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'Jeans')\n\n self.edit_success('jeans', self.test_data['t-shirts'])\n rv = self.get('pants')\n assert in_response(rv, 'This category is empty.')\n assert not in_response(rv, 'Jeans')\n assert not in_response(rv, 'T-Shirts')\n rv = self.get('shirts')\n assert not in_response(rv, 'This category is empty.')\n assert in_response(rv, 'T-Shirts')\n assert not in_response(rv, 'Jeans')\n\n def test_name_required(self):\n \"\"\"Test that adding/updating a category without a name fails\"\"\"\n self.required_field_fail('name', self.test_data['pants'])\n\n def test_parent_does_not_exist(self):\n \"\"\"Test that adding/updating a category with a non-existent\n parent fails\n \"\"\"\n self.bad_data_fail(self.test_data['pants'],\n self.test_data['hats'], 'Parent does not exist')\n\n def test_category_already_exists(self):\n self.existing_key_fail(\n self.test_data['pants'],\n self.test_data['shirts'])\n\n def test_categories_are_sorted(self):\n \"\"\"Test that categories are sorted alphabetically by name\"\"\"\n self.data_sorted(self.test_data['shirts'], self.test_data['pants'])\n\n def test_delete_category_does_not_exist(self):\n \"\"\"Test that deleting a category that doesn't exist fails\"\"\"\n self.delete_does_not_exist_fail('hats')\n\n def test_add_category_slug_special(self):\n \"\"\"Test that adding a category with an incorrect name fails\"\"\"\n self.add_success(self.test_data['polo-shirts'])\n assert self.verify_object(dict(name='Polo Shirts', slug='polo-shirts'))\n\n self.add_fail(self.test_data['symbols'], '')\n\n self.add_success('Add')\n\n def test_update_category_slug_special(self):\n \"\"\"Test that updating a category with an incorrect slug fails\"\"\"\n rv = self.app.post(self.get_category_url('add'), data=dict(\n name='Pants', slug='pants'\n ), follow_redirects=True)\n\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=dict(\n name='Polo Shirts', slug='polo shirts'\n ), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=dict(\n name=':)', slug=':)'\n ), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug is formatted incorrectly' in rv.data\n\n rv = self.app.post(self.get_category_url('pants', 'edit'), data=dict(\n name='Add', slug='add'\n ), follow_redirects=True)\n assert b'Edit Pants' in rv.data\n assert b'Slug \"add\" is not allowed' in rv.data\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-ids": [ 31, 43, 44, 49, 56 ] }
[ 31, 43, 44, 49, 56 ]
#!/usr/bin/env python3 import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl import torchmetrics class BaselineModule(pl.LightningModule): def __init__(self, input_size, num_classes=4, lr=3e-4): super().__init__() self.backbone = nn.Sequential( # CBR-Tiny arXiv:1902.07208 nn.Conv2d(3, 64, 5), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(64, 256, 5), nn.BatchNorm2d(256), nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(256, 512, 5), nn.BatchNorm2d(512), nn.ReLU(), nn.MaxPool2d(3, 2), nn.AdaptiveAvgPool2d((1, 1)), ) hidden_size = self._get_hidden_size(input_size) self.classifier = nn.Linear(hidden_size, num_classes) self.lr = lr self.train_acc = torchmetrics.Accuracy() self.val_acc = torchmetrics.Accuracy() def _get_hidden_size(self, input_size): self.backbone(torch.randn(1, 3, input_size, input_size)) def forward(self, input_tensor): hidden = self.backbone(input_tensor) return self.classifier(hidden.squeeze()) def training_step(self, batch, batch_idx): input_tensor, target = batch logits = self(input_tensor) loss = F.cross_entropy(logits, target) self.train_acc(F.softmax(logits, 1), target) self.log('train_acc', self.train_acc, on_epoch=True) self.log('train_loss', loss, on_epoch=True) return loss def validation_step(self, batch, batch_idx): input_tensor, target = batch logits = self(input_tensor) loss = F.cross_entropy(logits, target) self.val_acc(F.softmax(logits, 1), target) self.log('val_acc', self.val_acc, on_epoch=True) self.log('val_loss', loss, on_epoch=True) def configure_optimizers(self): optimizer = torch.optim.Adam(self.parameters(), lr=self.lr) return optimizer
normal
{ "blob_id": "7d43b20ebee2f4cd509bbd896c9e6ae8b2c4b354", "index": 7128, "step-1": "<mask token>\n\n\nclass BaselineModule(pl.LightningModule):\n <mask token>\n\n def _get_hidden_size(self, input_size):\n self.backbone(torch.randn(1, 3, input_size, input_size))\n\n def forward(self, input_tensor):\n hidden = self.backbone(input_tensor)\n return self.classifier(hidden.squeeze())\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass BaselineModule(pl.LightningModule):\n <mask token>\n\n def _get_hidden_size(self, input_size):\n self.backbone(torch.randn(1, 3, input_size, input_size))\n\n def forward(self, input_tensor):\n hidden = self.backbone(input_tensor)\n return self.classifier(hidden.squeeze())\n\n def training_step(self, batch, batch_idx):\n input_tensor, target = batch\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n self.train_acc(F.softmax(logits, 1), target)\n self.log('train_acc', self.train_acc, on_epoch=True)\n self.log('train_loss', loss, on_epoch=True)\n return loss\n\n def validation_step(self, batch, batch_idx):\n input_tensor, target = batch\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n self.val_acc(F.softmax(logits, 1), target)\n self.log('val_acc', self.val_acc, on_epoch=True)\n self.log('val_loss', loss, on_epoch=True)\n <mask token>\n", "step-3": "<mask token>\n\n\nclass BaselineModule(pl.LightningModule):\n <mask token>\n\n def _get_hidden_size(self, input_size):\n self.backbone(torch.randn(1, 3, input_size, input_size))\n\n def forward(self, input_tensor):\n hidden = self.backbone(input_tensor)\n return self.classifier(hidden.squeeze())\n\n def training_step(self, batch, batch_idx):\n input_tensor, target = batch\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n self.train_acc(F.softmax(logits, 1), target)\n self.log('train_acc', self.train_acc, on_epoch=True)\n self.log('train_loss', loss, on_epoch=True)\n return loss\n\n def validation_step(self, batch, batch_idx):\n input_tensor, target = batch\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n self.val_acc(F.softmax(logits, 1), target)\n self.log('val_acc', self.val_acc, on_epoch=True)\n self.log('val_loss', loss, on_epoch=True)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)\n return optimizer\n", "step-4": "<mask token>\n\n\nclass BaselineModule(pl.LightningModule):\n\n def __init__(self, input_size, num_classes=4, lr=0.0003):\n super().__init__()\n self.backbone = nn.Sequential(nn.Conv2d(3, 64, 5), nn.BatchNorm2d(\n 64), nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(64, 256, 5), nn.\n BatchNorm2d(256), nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(256,\n 512, 5), nn.BatchNorm2d(512), nn.ReLU(), nn.MaxPool2d(3, 2), nn\n .AdaptiveAvgPool2d((1, 1)))\n hidden_size = self._get_hidden_size(input_size)\n self.classifier = nn.Linear(hidden_size, num_classes)\n self.lr = lr\n self.train_acc = torchmetrics.Accuracy()\n self.val_acc = torchmetrics.Accuracy()\n\n def _get_hidden_size(self, input_size):\n self.backbone(torch.randn(1, 3, input_size, input_size))\n\n def forward(self, input_tensor):\n hidden = self.backbone(input_tensor)\n return self.classifier(hidden.squeeze())\n\n def training_step(self, batch, batch_idx):\n input_tensor, target = batch\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n self.train_acc(F.softmax(logits, 1), target)\n self.log('train_acc', self.train_acc, on_epoch=True)\n self.log('train_loss', loss, on_epoch=True)\n return loss\n\n def validation_step(self, batch, batch_idx):\n input_tensor, target = batch\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n self.val_acc(F.softmax(logits, 1), target)\n self.log('val_acc', self.val_acc, on_epoch=True)\n self.log('val_loss', loss, on_epoch=True)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)\n return optimizer\n", "step-5": "#!/usr/bin/env python3\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pytorch_lightning as pl\nimport torchmetrics\n\nclass BaselineModule(pl.LightningModule):\n def __init__(self, input_size, num_classes=4, lr=3e-4):\n super().__init__()\n\n self.backbone = nn.Sequential( # CBR-Tiny arXiv:1902.07208\n nn.Conv2d(3, 64, 5),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(3, 2),\n nn.Conv2d(64, 256, 5),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.MaxPool2d(3, 2),\n nn.Conv2d(256, 512, 5),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.MaxPool2d(3, 2),\n nn.AdaptiveAvgPool2d((1, 1)),\n )\n\n hidden_size = self._get_hidden_size(input_size)\n\n self.classifier = nn.Linear(hidden_size, num_classes)\n self.lr = lr\n\n self.train_acc = torchmetrics.Accuracy()\n self.val_acc = torchmetrics.Accuracy()\n\n def _get_hidden_size(self, input_size):\n self.backbone(torch.randn(1, 3, input_size, input_size))\n\n def forward(self, input_tensor):\n hidden = self.backbone(input_tensor)\n return self.classifier(hidden.squeeze())\n\n def training_step(self, batch, batch_idx):\n input_tensor, target = batch\n\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n\n self.train_acc(F.softmax(logits, 1), target)\n self.log('train_acc', self.train_acc, on_epoch=True)\n self.log('train_loss', loss, on_epoch=True)\n\n return loss\n\n def validation_step(self, batch, batch_idx):\n input_tensor, target = batch\n\n logits = self(input_tensor)\n loss = F.cross_entropy(logits, target)\n\n self.val_acc(F.softmax(logits, 1), target)\n self.log('val_acc', self.val_acc, on_epoch=True)\n self.log('val_loss', loss, on_epoch=True)\n\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)\n return optimizer\n", "step-ids": [ 3, 5, 6, 7, 9 ] }
[ 3, 5, 6, 7, 9 ]
import os class User(object): def __init__(self, meta): meta.update({ 'groups': meta.get('groups', []) + [meta['username']] }) self.meta = meta @property def username(self): return self.meta['username'] @property def groups(self): return self.meta['groups'] @property def home_path(self): return os.path.join('/home', self.username) @property def is_root(self): return self.username == 'root' def own(self, node): if self.is_root: return True return node.owner == self.username def can_read(self, node): if self.is_root: return True if self.own(node) and node.owner_readable: return True if node.group in self.groups and node.group_readable: return True if node.other_readable: return True return False def can_write(self, node): if self.is_root: return True if self.own(node) and node.owner_writable: return True if node.group in self.groups and node.group_writable: return True if node.other_writable: return True return False def can_create(self, node): return self.can_write(node.parent) def can_remove(self, node): return self.can_write(node.parent) def __getitem__(self, key): return self.meta.__getitem__(key) def __repr__(self): return repr(self.meta) root_user = User({'username': 'root'})
normal
{ "blob_id": "aa47b7c74b9b6b8a7f014de4bd58236edeba485d", "index": 5971, "step-1": "<mask token>\n\n\nclass User(object):\n\n def __init__(self, meta):\n meta.update({'groups': meta.get('groups', []) + [meta['username']]})\n self.meta = meta\n\n @property\n def username(self):\n return self.meta['username']\n <mask token>\n <mask token>\n\n @property\n def is_root(self):\n return self.username == 'root'\n\n def own(self, node):\n if self.is_root:\n return True\n return node.owner == self.username\n\n def can_read(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_readable:\n return True\n if node.group in self.groups and node.group_readable:\n return True\n if node.other_readable:\n return True\n return False\n\n def can_write(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_writable:\n return True\n if node.group in self.groups and node.group_writable:\n return True\n if node.other_writable:\n return True\n return False\n\n def can_create(self, node):\n return self.can_write(node.parent)\n\n def can_remove(self, node):\n return self.can_write(node.parent)\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass User(object):\n\n def __init__(self, meta):\n meta.update({'groups': meta.get('groups', []) + [meta['username']]})\n self.meta = meta\n\n @property\n def username(self):\n return self.meta['username']\n\n @property\n def groups(self):\n return self.meta['groups']\n\n @property\n def home_path(self):\n return os.path.join('/home', self.username)\n\n @property\n def is_root(self):\n return self.username == 'root'\n\n def own(self, node):\n if self.is_root:\n return True\n return node.owner == self.username\n\n def can_read(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_readable:\n return True\n if node.group in self.groups and node.group_readable:\n return True\n if node.other_readable:\n return True\n return False\n\n def can_write(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_writable:\n return True\n if node.group in self.groups and node.group_writable:\n return True\n if node.other_writable:\n return True\n return False\n\n def can_create(self, node):\n return self.can_write(node.parent)\n\n def can_remove(self, node):\n return self.can_write(node.parent)\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass User(object):\n\n def __init__(self, meta):\n meta.update({'groups': meta.get('groups', []) + [meta['username']]})\n self.meta = meta\n\n @property\n def username(self):\n return self.meta['username']\n\n @property\n def groups(self):\n return self.meta['groups']\n\n @property\n def home_path(self):\n return os.path.join('/home', self.username)\n\n @property\n def is_root(self):\n return self.username == 'root'\n\n def own(self, node):\n if self.is_root:\n return True\n return node.owner == self.username\n\n def can_read(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_readable:\n return True\n if node.group in self.groups and node.group_readable:\n return True\n if node.other_readable:\n return True\n return False\n\n def can_write(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_writable:\n return True\n if node.group in self.groups and node.group_writable:\n return True\n if node.other_writable:\n return True\n return False\n\n def can_create(self, node):\n return self.can_write(node.parent)\n\n def can_remove(self, node):\n return self.can_write(node.parent)\n <mask token>\n\n def __repr__(self):\n return repr(self.meta)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass User(object):\n\n def __init__(self, meta):\n meta.update({'groups': meta.get('groups', []) + [meta['username']]})\n self.meta = meta\n\n @property\n def username(self):\n return self.meta['username']\n\n @property\n def groups(self):\n return self.meta['groups']\n\n @property\n def home_path(self):\n return os.path.join('/home', self.username)\n\n @property\n def is_root(self):\n return self.username == 'root'\n\n def own(self, node):\n if self.is_root:\n return True\n return node.owner == self.username\n\n def can_read(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_readable:\n return True\n if node.group in self.groups and node.group_readable:\n return True\n if node.other_readable:\n return True\n return False\n\n def can_write(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_writable:\n return True\n if node.group in self.groups and node.group_writable:\n return True\n if node.other_writable:\n return True\n return False\n\n def can_create(self, node):\n return self.can_write(node.parent)\n\n def can_remove(self, node):\n return self.can_write(node.parent)\n\n def __getitem__(self, key):\n return self.meta.__getitem__(key)\n\n def __repr__(self):\n return repr(self.meta)\n\n\n<mask token>\n", "step-5": "import os\n\n\nclass User(object):\n\n def __init__(self, meta):\n meta.update({\n 'groups': meta.get('groups', []) + [meta['username']]\n })\n self.meta = meta\n\n @property\n def username(self):\n return self.meta['username']\n\n @property\n def groups(self):\n return self.meta['groups']\n\n @property\n def home_path(self):\n return os.path.join('/home', self.username)\n\n @property\n def is_root(self):\n return self.username == 'root'\n\n def own(self, node):\n if self.is_root:\n return True\n return node.owner == self.username\n\n def can_read(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_readable:\n return True\n if node.group in self.groups and node.group_readable:\n return True\n if node.other_readable:\n return True\n return False\n\n def can_write(self, node):\n if self.is_root:\n return True\n if self.own(node) and node.owner_writable:\n return True\n if node.group in self.groups and node.group_writable:\n return True\n if node.other_writable:\n return True\n return False\n\n def can_create(self, node):\n return self.can_write(node.parent)\n\n def can_remove(self, node):\n return self.can_write(node.parent)\n\n def __getitem__(self, key):\n return self.meta.__getitem__(key)\n\n def __repr__(self):\n return repr(self.meta)\n\n\nroot_user = User({'username': 'root'})\n", "step-ids": [ 9, 11, 12, 13, 16 ] }
[ 9, 11, 12, 13, 16 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_urls(search_string, start): temp = [] url = 'http://www.google.com/search' payload = {'q': search_string, 'start': start} my_headers = {'User-agent': 'Mozilla/11.0'} r = requests.get(url, params=payload, headers=my_headers) soup = BeautifulSoup(r.text, 'html.parser') h3tags = soup.find_all('h3', class_='r') for h3 in h3tags: try: temp.append(re.search('url\\?q=(.+?)\\&sa', h3.a['href']).group(1)) except: continue return temp def main(): start = timer() result = [] arguments = docopt(__doc__, version= 'MakMan Google Scrapper & Mass Exploiter') search = arguments['<search>'] pages = arguments['<pages>'] processes = int(arguments['<processes>']) make_request = partial(get_urls, search) pagelist = [str(x * 10) for x in range(0, int(pages))] with Pool(processes) as p: tmp = p.map(make_request, pagelist) for x in tmp: result.extend(x) result = list(set(result)) print(*result, sep='\n') print('\nTotal URLs Scraped : %s ' % str(len(result))) print('Script Execution Time : %s ' % (timer() - start,)) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_urls(search_string, start): temp = [] url = 'http://www.google.com/search' payload = {'q': search_string, 'start': start} my_headers = {'User-agent': 'Mozilla/11.0'} r = requests.get(url, params=payload, headers=my_headers) soup = BeautifulSoup(r.text, 'html.parser') h3tags = soup.find_all('h3', class_='r') for h3 in h3tags: try: temp.append(re.search('url\\?q=(.+?)\\&sa', h3.a['href']).group(1)) except: continue return temp def main(): start = timer() result = [] arguments = docopt(__doc__, version= 'MakMan Google Scrapper & Mass Exploiter') search = arguments['<search>'] pages = arguments['<pages>'] processes = int(arguments['<processes>']) make_request = partial(get_urls, search) pagelist = [str(x * 10) for x in range(0, int(pages))] with Pool(processes) as p: tmp = p.map(make_request, pagelist) for x in tmp: result.extend(x) result = list(set(result)) print(*result, sep='\n') print('\nTotal URLs Scraped : %s ' % str(len(result))) print('Script Execution Time : %s ' % (timer() - start,)) if __name__ == '__main__': main() <|reserved_special_token_1|> <|reserved_special_token_0|> import re from functools import partial from multiprocessing import Pool from time import time as timer import requests from bs4 import BeautifulSoup from docopt import docopt def get_urls(search_string, start): temp = [] url = 'http://www.google.com/search' payload = {'q': search_string, 'start': start} my_headers = {'User-agent': 'Mozilla/11.0'} r = requests.get(url, params=payload, headers=my_headers) soup = BeautifulSoup(r.text, 'html.parser') h3tags = soup.find_all('h3', class_='r') for h3 in h3tags: try: temp.append(re.search('url\\?q=(.+?)\\&sa', h3.a['href']).group(1)) except: continue return temp def main(): start = timer() result = [] arguments = docopt(__doc__, version= 'MakMan Google Scrapper & Mass Exploiter') search = arguments['<search>'] pages = arguments['<pages>'] processes = int(arguments['<processes>']) make_request = partial(get_urls, search) pagelist = [str(x * 10) for x in range(0, int(pages))] with Pool(processes) as p: tmp = p.map(make_request, pagelist) for x in tmp: result.extend(x) result = list(set(result)) print(*result, sep='\n') print('\nTotal URLs Scraped : %s ' % str(len(result))) print('Script Execution Time : %s ' % (timer() - start,)) if __name__ == '__main__': main() <|reserved_special_token_1|> """Google Scraper Usage: web_scraper.py <search> <pages> <processes> web_scraper.py (-h | --help) Arguments: <search> String to be Searched <pages> Number of pages <processes> Number of parallel processes Options: -h, --help Show this screen. """ import re from functools import partial from multiprocessing import Pool from time import time as timer import requests from bs4 import BeautifulSoup from docopt import docopt def get_urls(search_string, start): temp = [] url = 'http://www.google.com/search' payload = {'q': search_string, 'start': start} my_headers = {'User-agent': 'Mozilla/11.0'} r = requests.get(url, params=payload, headers=my_headers) soup = BeautifulSoup(r.text, 'html.parser') h3tags = soup.find_all('h3', class_='r') for h3 in h3tags: try: temp.append(re.search('url\?q=(.+?)\&sa', h3.a['href']).group(1)) except: continue return temp def main(): start = timer() result = [] arguments = docopt(__doc__, version='MakMan Google Scrapper & Mass Exploiter') search = arguments['<search>'] pages = arguments['<pages>'] processes = int(arguments['<processes>']) ####Changes for Multi-Processing#### make_request = partial(get_urls, search) pagelist = [str(x * 10) for x in range(0, int(pages))] with Pool(processes) as p: tmp = p.map(make_request, pagelist) for x in tmp: result.extend(x) ####Changes for Multi-Processing#### result = list(set(result)) print(*result, sep='\n') print('\nTotal URLs Scraped : %s ' % str(len(result))) print('Script Execution Time : %s ' % (timer() - start,)) if __name__ == '__main__': main() # End
flexible
{ "blob_id": "68dcac07bbdb4dde983939be98ece127d963c254", "index": 3610, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_urls(search_string, start):\n temp = []\n url = 'http://www.google.com/search'\n payload = {'q': search_string, 'start': start}\n my_headers = {'User-agent': 'Mozilla/11.0'}\n r = requests.get(url, params=payload, headers=my_headers)\n soup = BeautifulSoup(r.text, 'html.parser')\n h3tags = soup.find_all('h3', class_='r')\n for h3 in h3tags:\n try:\n temp.append(re.search('url\\\\?q=(.+?)\\\\&sa', h3.a['href']).group(1))\n except:\n continue\n return temp\n\n\ndef main():\n start = timer()\n result = []\n arguments = docopt(__doc__, version=\n 'MakMan Google Scrapper & Mass Exploiter')\n search = arguments['<search>']\n pages = arguments['<pages>']\n processes = int(arguments['<processes>'])\n make_request = partial(get_urls, search)\n pagelist = [str(x * 10) for x in range(0, int(pages))]\n with Pool(processes) as p:\n tmp = p.map(make_request, pagelist)\n for x in tmp:\n result.extend(x)\n result = list(set(result))\n print(*result, sep='\\n')\n print('\\nTotal URLs Scraped : %s ' % str(len(result)))\n print('Script Execution Time : %s ' % (timer() - start,))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_urls(search_string, start):\n temp = []\n url = 'http://www.google.com/search'\n payload = {'q': search_string, 'start': start}\n my_headers = {'User-agent': 'Mozilla/11.0'}\n r = requests.get(url, params=payload, headers=my_headers)\n soup = BeautifulSoup(r.text, 'html.parser')\n h3tags = soup.find_all('h3', class_='r')\n for h3 in h3tags:\n try:\n temp.append(re.search('url\\\\?q=(.+?)\\\\&sa', h3.a['href']).group(1))\n except:\n continue\n return temp\n\n\ndef main():\n start = timer()\n result = []\n arguments = docopt(__doc__, version=\n 'MakMan Google Scrapper & Mass Exploiter')\n search = arguments['<search>']\n pages = arguments['<pages>']\n processes = int(arguments['<processes>'])\n make_request = partial(get_urls, search)\n pagelist = [str(x * 10) for x in range(0, int(pages))]\n with Pool(processes) as p:\n tmp = p.map(make_request, pagelist)\n for x in tmp:\n result.extend(x)\n result = list(set(result))\n print(*result, sep='\\n')\n print('\\nTotal URLs Scraped : %s ' % str(len(result)))\n print('Script Execution Time : %s ' % (timer() - start,))\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "<mask token>\nimport re\nfrom functools import partial\nfrom multiprocessing import Pool\nfrom time import time as timer\nimport requests\nfrom bs4 import BeautifulSoup\nfrom docopt import docopt\n\n\ndef get_urls(search_string, start):\n temp = []\n url = 'http://www.google.com/search'\n payload = {'q': search_string, 'start': start}\n my_headers = {'User-agent': 'Mozilla/11.0'}\n r = requests.get(url, params=payload, headers=my_headers)\n soup = BeautifulSoup(r.text, 'html.parser')\n h3tags = soup.find_all('h3', class_='r')\n for h3 in h3tags:\n try:\n temp.append(re.search('url\\\\?q=(.+?)\\\\&sa', h3.a['href']).group(1))\n except:\n continue\n return temp\n\n\ndef main():\n start = timer()\n result = []\n arguments = docopt(__doc__, version=\n 'MakMan Google Scrapper & Mass Exploiter')\n search = arguments['<search>']\n pages = arguments['<pages>']\n processes = int(arguments['<processes>'])\n make_request = partial(get_urls, search)\n pagelist = [str(x * 10) for x in range(0, int(pages))]\n with Pool(processes) as p:\n tmp = p.map(make_request, pagelist)\n for x in tmp:\n result.extend(x)\n result = list(set(result))\n print(*result, sep='\\n')\n print('\\nTotal URLs Scraped : %s ' % str(len(result)))\n print('Script Execution Time : %s ' % (timer() - start,))\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "\"\"\"Google Scraper\n \nUsage:\n web_scraper.py <search> <pages> <processes>\n web_scraper.py (-h | --help)\n \nArguments:\n <search> String to be Searched\n <pages> Number of pages\n <processes> Number of parallel processes\n \nOptions:\n -h, --help Show this screen.\n \n\"\"\"\n\nimport re\nfrom functools import partial\nfrom multiprocessing import Pool\nfrom time import time as timer\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom docopt import docopt\n\n\ndef get_urls(search_string, start):\n temp = []\n url = 'http://www.google.com/search'\n payload = {'q': search_string, 'start': start}\n my_headers = {'User-agent': 'Mozilla/11.0'}\n r = requests.get(url, params=payload, headers=my_headers)\n soup = BeautifulSoup(r.text, 'html.parser')\n h3tags = soup.find_all('h3', class_='r')\n for h3 in h3tags:\n try:\n temp.append(re.search('url\\?q=(.+?)\\&sa', h3.a['href']).group(1))\n except:\n continue\n return temp\n\n\ndef main():\n start = timer()\n result = []\n arguments = docopt(__doc__, version='MakMan Google Scrapper & Mass Exploiter')\n search = arguments['<search>']\n pages = arguments['<pages>']\n processes = int(arguments['<processes>'])\n ####Changes for Multi-Processing####\n make_request = partial(get_urls, search)\n pagelist = [str(x * 10) for x in range(0, int(pages))]\n with Pool(processes) as p:\n tmp = p.map(make_request, pagelist)\n for x in tmp:\n result.extend(x)\n ####Changes for Multi-Processing####\n result = list(set(result))\n print(*result, sep='\\n')\n print('\\nTotal URLs Scraped : %s ' % str(len(result)))\n print('Script Execution Time : %s ' % (timer() - start,))\n\n\nif __name__ == '__main__':\n main()\n\n # End\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class Ensemble(object): """Ensemble base_models on train data than fit/predict The object input is composed of 'n_splits', 'stacker' and list of 'base_models'. The __init__ method self-assign the inputs. The fit_predict method divides the dataset in 'n_splits' then it loops trough ammount of 'base_models' fitting all splits and then averaging it on a new column in the end. In the end, predictions are made with these new columns. If sought the use of voting ensemble, the ammount of models passed on base_models can be repeated. """ def __init__(self, n_splits, stacker, base_models): self.n_splits = n_splits self.stacker = stacker self.base_models = base_models def fit_predict(self, X, Y, T): X = np.array(X) Y = np.array(Y) T = np.array(T) folds = list(KFold(n_splits=self.n_splits, shuffle=True, random_state=42).split(X, Y)) S_train = np.zeros((X.shape[0], len(self.base_models))) S_test = np.zeros((T.shape[0], len(self.base_models))) print('------- FITTING Stacker - 2nd level -------') for i, clf in enumerate(self.base_models): S_test_i = np.zeros((T.shape[0], self.n_splits)) for j, (train_idx, test_idx) in enumerate(folds): X_train = X[train_idx] Y_train = Y[train_idx] X_holdout = X[test_idx] Y_holdout = Y[test_idx] clf.fit(X_train, Y_train) Y_pred = clf.predict(X_holdout)[:] print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j, r2_score(Y_holdout, Y_pred))) S_train[test_idx, i] = Y_pred S_test_i[:, j] = clf.predict(T)[:] S_test[:, i] = S_test_i.mean(axis=1) results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2') print( '\x1b[1;92mDONE! \x1b[0;0m\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})' .format(results.mean(), results.std() * 2)) self.stacker.fit(S_train, Y) final_prediction = self.stacker.predict(S_test)[:] return final_prediction <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> sns.set() <|reserved_special_token_0|> print('------- FITTING SVR -------') <|reserved_special_token_0|> print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(svr_cv_scores.mean(), svr_cv_scores.std() * 2)) print('------- FITTING XGBRegressor -------') <|reserved_special_token_0|> print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(xgb_cv_scores.mean(), xgb_cv_scores.std() * 2)) print('------- FITTING RandomForestRegressor -------') <|reserved_special_token_0|> print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(rf_cv_scores.mean(), rf_cv_scores.std() * 2)) class Ensemble(object): """Ensemble base_models on train data than fit/predict The object input is composed of 'n_splits', 'stacker' and list of 'base_models'. The __init__ method self-assign the inputs. The fit_predict method divides the dataset in 'n_splits' then it loops trough ammount of 'base_models' fitting all splits and then averaging it on a new column in the end. In the end, predictions are made with these new columns. If sought the use of voting ensemble, the ammount of models passed on base_models can be repeated. """ def __init__(self, n_splits, stacker, base_models): self.n_splits = n_splits self.stacker = stacker self.base_models = base_models def fit_predict(self, X, Y, T): X = np.array(X) Y = np.array(Y) T = np.array(T) folds = list(KFold(n_splits=self.n_splits, shuffle=True, random_state=42).split(X, Y)) S_train = np.zeros((X.shape[0], len(self.base_models))) S_test = np.zeros((T.shape[0], len(self.base_models))) print('------- FITTING Stacker - 2nd level -------') for i, clf in enumerate(self.base_models): S_test_i = np.zeros((T.shape[0], self.n_splits)) for j, (train_idx, test_idx) in enumerate(folds): X_train = X[train_idx] Y_train = Y[train_idx] X_holdout = X[test_idx] Y_holdout = Y[test_idx] clf.fit(X_train, Y_train) Y_pred = clf.predict(X_holdout)[:] print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j, r2_score(Y_holdout, Y_pred))) S_train[test_idx, i] = Y_pred S_test_i[:, j] = clf.predict(T)[:] S_test[:, i] = S_test_i.mean(axis=1) results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2') print( '\x1b[1;92mDONE! \x1b[0;0m\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})' .format(results.mean(), results.std() * 2)) self.stacker.fit(S_train, Y) final_prediction = self.stacker.predict(S_test)[:] return final_prediction <|reserved_special_token_0|> ax.set_axis_labels('Real prices', 'Predicted prices') plt.tick_params(axis='both', colors='gray') plt.title('Real vs Predicted prices on Boston Housing', fontweight='bold') plt.tight_layout() plt.show() <|reserved_special_token_1|> <|reserved_special_token_0|> sns.set() boston = datasets.load_boston() boston_pd = pd.DataFrame(boston.data) boston_pd.columns = boston.feature_names X, Y = boston_pd, boston.target X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1, random_state=42) print('------- FITTING SVR -------') svr_mdl = SVR(kernel='linear', C=0.11, epsilon=0.011, gamma=0.1) svr_cv_scores = cross_val_score(svr_mdl, X_train, Y_train, cv=5, scoring='r2') print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(svr_cv_scores.mean(), svr_cv_scores.std() * 2)) print('------- FITTING XGBRegressor -------') xgb_mdl = xgb.XGBRegressor(learning_rate=0.0503, n_estimators=339, max_depth=5, min_child_weight=2, gamma=0.17, subsample=0.84, colsample_bytree=0.85, reg_alpha=0.008, reg_lambda=1.2, scale_pos_weight=1, seed=42) xgb_cv_scores = cross_val_score(xgb_mdl, X_train, Y_train, cv=5, scoring='r2') print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(xgb_cv_scores.mean(), xgb_cv_scores.std() * 2)) print('------- FITTING RandomForestRegressor -------') rf_mdl = RandomForestRegressor(n_estimators=95, max_features='auto', max_depth=18, min_samples_split=2, min_samples_leaf=1, bootstrap=True, random_state=42) rf_cv_scores = cross_val_score(rf_mdl, X_train, Y_train, cv=5, scoring='r2') print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(rf_cv_scores.mean(), rf_cv_scores.std() * 2)) class Ensemble(object): """Ensemble base_models on train data than fit/predict The object input is composed of 'n_splits', 'stacker' and list of 'base_models'. The __init__ method self-assign the inputs. The fit_predict method divides the dataset in 'n_splits' then it loops trough ammount of 'base_models' fitting all splits and then averaging it on a new column in the end. In the end, predictions are made with these new columns. If sought the use of voting ensemble, the ammount of models passed on base_models can be repeated. """ def __init__(self, n_splits, stacker, base_models): self.n_splits = n_splits self.stacker = stacker self.base_models = base_models def fit_predict(self, X, Y, T): X = np.array(X) Y = np.array(Y) T = np.array(T) folds = list(KFold(n_splits=self.n_splits, shuffle=True, random_state=42).split(X, Y)) S_train = np.zeros((X.shape[0], len(self.base_models))) S_test = np.zeros((T.shape[0], len(self.base_models))) print('------- FITTING Stacker - 2nd level -------') for i, clf in enumerate(self.base_models): S_test_i = np.zeros((T.shape[0], self.n_splits)) for j, (train_idx, test_idx) in enumerate(folds): X_train = X[train_idx] Y_train = Y[train_idx] X_holdout = X[test_idx] Y_holdout = Y[test_idx] clf.fit(X_train, Y_train) Y_pred = clf.predict(X_holdout)[:] print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j, r2_score(Y_holdout, Y_pred))) S_train[test_idx, i] = Y_pred S_test_i[:, j] = clf.predict(T)[:] S_test[:, i] = S_test_i.mean(axis=1) results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2') print( '\x1b[1;92mDONE! \x1b[0;0m\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})' .format(results.mean(), results.std() * 2)) self.stacker.fit(S_train, Y) final_prediction = self.stacker.predict(S_test)[:] return final_prediction stack = Ensemble(n_splits=5, stacker=svr_mdl, base_models=(xgb_mdl, rf_mdl, xgb_mdl, svr_mdl, xgb_mdl)) stack_pred = stack.fit_predict(X_train, Y_train, X_test) custom_style = {'axes.labelcolor': 'white', 'xtick.color': 'white', 'ytick.color': 'white'} data = pd.DataFrame(data={'stack_pred': stack_pred, 'Y_test': Y_test}) ax = sns.lmplot(x='Y_test', y='stack_pred', data=data, truncate=True, size=5) ax.set_axis_labels('Real prices', 'Predicted prices') plt.tick_params(axis='both', colors='gray') plt.title('Real vs Predicted prices on Boston Housing', fontweight='bold') plt.tight_layout() plt.show() <|reserved_special_token_1|> import numpy as np import xgboost as xgb from sklearn import datasets import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import ElasticNet from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.model_selection import cross_val_score, train_test_split, KFold from sklearn.metrics import r2_score sns.set() boston = datasets.load_boston() boston_pd = pd.DataFrame(boston.data) boston_pd.columns = boston.feature_names X, Y = boston_pd, boston.target X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1, random_state=42) print('------- FITTING SVR -------') svr_mdl = SVR(kernel='linear', C=0.11, epsilon=0.011, gamma=0.1) svr_cv_scores = cross_val_score(svr_mdl, X_train, Y_train, cv=5, scoring='r2') print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(svr_cv_scores.mean(), svr_cv_scores.std() * 2)) print('------- FITTING XGBRegressor -------') xgb_mdl = xgb.XGBRegressor(learning_rate=0.0503, n_estimators=339, max_depth=5, min_child_weight=2, gamma=0.17, subsample=0.84, colsample_bytree=0.85, reg_alpha=0.008, reg_lambda=1.2, scale_pos_weight=1, seed=42) xgb_cv_scores = cross_val_score(xgb_mdl, X_train, Y_train, cv=5, scoring='r2') print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(xgb_cv_scores.mean(), xgb_cv_scores.std() * 2)) print('------- FITTING RandomForestRegressor -------') rf_mdl = RandomForestRegressor(n_estimators=95, max_features='auto', max_depth=18, min_samples_split=2, min_samples_leaf=1, bootstrap=True, random_state=42) rf_cv_scores = cross_val_score(rf_mdl, X_train, Y_train, cv=5, scoring='r2') print(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(rf_cv_scores.mean(), rf_cv_scores.std() * 2)) class Ensemble(object): """Ensemble base_models on train data than fit/predict The object input is composed of 'n_splits', 'stacker' and list of 'base_models'. The __init__ method self-assign the inputs. The fit_predict method divides the dataset in 'n_splits' then it loops trough ammount of 'base_models' fitting all splits and then averaging it on a new column in the end. In the end, predictions are made with these new columns. If sought the use of voting ensemble, the ammount of models passed on base_models can be repeated. """ def __init__(self, n_splits, stacker, base_models): self.n_splits = n_splits self.stacker = stacker self.base_models = base_models def fit_predict(self, X, Y, T): X = np.array(X) Y = np.array(Y) T = np.array(T) folds = list(KFold(n_splits=self.n_splits, shuffle=True, random_state=42).split(X, Y)) S_train = np.zeros((X.shape[0], len(self.base_models))) S_test = np.zeros((T.shape[0], len(self.base_models))) print('------- FITTING Stacker - 2nd level -------') for i, clf in enumerate(self.base_models): S_test_i = np.zeros((T.shape[0], self.n_splits)) for j, (train_idx, test_idx) in enumerate(folds): X_train = X[train_idx] Y_train = Y[train_idx] X_holdout = X[test_idx] Y_holdout = Y[test_idx] clf.fit(X_train, Y_train) Y_pred = clf.predict(X_holdout)[:] print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j, r2_score(Y_holdout, Y_pred))) S_train[test_idx, i] = Y_pred S_test_i[:, j] = clf.predict(T)[:] S_test[:, i] = S_test_i.mean(axis=1) results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2') print( '\x1b[1;92mDONE! \x1b[0;0m\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})' .format(results.mean(), results.std() * 2)) self.stacker.fit(S_train, Y) final_prediction = self.stacker.predict(S_test)[:] return final_prediction stack = Ensemble(n_splits=5, stacker=svr_mdl, base_models=(xgb_mdl, rf_mdl, xgb_mdl, svr_mdl, xgb_mdl)) stack_pred = stack.fit_predict(X_train, Y_train, X_test) custom_style = {'axes.labelcolor': 'white', 'xtick.color': 'white', 'ytick.color': 'white'} data = pd.DataFrame(data={'stack_pred': stack_pred, 'Y_test': Y_test}) ax = sns.lmplot(x='Y_test', y='stack_pred', data=data, truncate=True, size=5) ax.set_axis_labels('Real prices', 'Predicted prices') plt.tick_params(axis='both', colors='gray') plt.title('Real vs Predicted prices on Boston Housing', fontweight='bold') plt.tight_layout() plt.show() <|reserved_special_token_1|> #!/usr/bin/env python # Title : STACK_BostonHousing.py # Description : Stacking was the natural progression of our algorithms trial. # In here, we'll use prediction from a number of models in order # to improve accuracy as it add linearly independent data to our # dataset. Here we also use voting ensembler, using the best es- # timator three timers on the stack of second level models. # We'll find CV scores of each model on train_test_split then # stack the models on a 5-KFold of the data, finding final CV # score. We'll also plot the comparative graph of Real Prices vs # Predicted Prices # Author : Neves4 # Outputs : Figure with one plot : 'Real Prices vs Predicted prices' # Values : SVR CV Scores: 0.6798 (+/- 0.0895) # XGB CV Scores: 0.8784 (+/- 0.0598) # RF CV Scores: 0.8601 (+/- 0.0789) # STACK CV Scores: 0.8809 (+/- 0.0864) # License : MIT License #============================================================================== ##### IMPORTING ##### import numpy as np import xgboost as xgb from sklearn import datasets import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import ElasticNet from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.model_selection import cross_val_score, train_test_split, KFold from sklearn.metrics import r2_score sns.set() # set seaborn style ##### DECLARING AND TRAINING ##### # Carregamento do dataset do boston, conversão para o framework pandas e como a # nomenclatura não é automática, foi dado valor às colunas da tabela do pandas. # Para verificar como estão os dados, chamar print(boston_pd.head()) boston = datasets.load_boston() boston_pd = pd.DataFrame(boston.data) boston_pd.columns = boston.feature_names # É necessária então a divisão dos datasets, pelo método train_test_split. Para # encontrar o tamanho de cada tensor que foi dividido, print(X_train.shape) X, Y = boston_pd, boston.target X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.1, random_state = 42) # ##### 1ST LEVEL MODELS ##### # # ElasticNet - baseline model #0 # print("------- FITTING ElasticNet -------") # en_mdl = ElasticNet(alpha = 5.2, l1_ratio = 0.5, random_state = 42) # en_cv_scores = cross_val_score(en_mdl, X_train, Y_train, cv=5, scoring='r2') # print(" DONE! CV Scores: {:.4f} (+/- {:.4f})" .format(en_cv_scores.mean(),\ # en_cv_scores.std() * 2)) # SVR - baseline model #1 print("------- FITTING SVR -------") svr_mdl = SVR(kernel = 'linear', C = 0.11, epsilon = 0.011, gamma = 0.1) svr_cv_scores = cross_val_score(svr_mdl, X_train, Y_train, cv=5, scoring='r2') print(" DONE! CV Scores: {:.4f} (+/- {:.4f})" .format(svr_cv_scores.mean(),\ svr_cv_scores.std() * 2)) # XGBRegressor - baseline model #2 print("------- FITTING XGBRegressor -------") xgb_mdl = xgb.XGBRegressor(learning_rate = 0.0503, n_estimators = 339, max_depth = 5, min_child_weight = 2, gamma = 0.17, subsample = 0.84, colsample_bytree = 0.85, reg_alpha = 0.008, reg_lambda = 1.2, scale_pos_weight = 1, seed = 42) xgb_cv_scores = cross_val_score(xgb_mdl, X_train, Y_train, cv=5, scoring='r2') print(" DONE! CV Scores: {:.4f} (+/- {:.4f})" .format(xgb_cv_scores.mean(),\ xgb_cv_scores.std() * 2)) # RandomForestRegressor - baseline model #3 print("------- FITTING RandomForestRegressor -------") rf_mdl = RandomForestRegressor(n_estimators = 95, max_features = 'auto', max_depth = 18, min_samples_split = 2, min_samples_leaf = 1, bootstrap = True, random_state = 42) rf_cv_scores = cross_val_score(rf_mdl, X_train, Y_train, cv=5, scoring='r2') print(" DONE! CV Scores: {:.4f} (+/- {:.4f})" .format(rf_cv_scores.mean(),\ rf_cv_scores.std() * 2)) class Ensemble(object): """Ensemble base_models on train data than fit/predict The object input is composed of 'n_splits', 'stacker' and list of 'base_models'. The __init__ method self-assign the inputs. The fit_predict method divides the dataset in 'n_splits' then it loops trough ammount of 'base_models' fitting all splits and then averaging it on a new column in the end. In the end, predictions are made with these new columns. If sought the use of voting ensemble, the ammount of models passed on base_models can be repeated. """ def __init__(self, n_splits, stacker, base_models): self.n_splits = n_splits self.stacker = stacker self.base_models = base_models def fit_predict(self, X, Y, T): X = np.array(X) Y = np.array(Y) T = np.array(T) # Create folds on the dataset based on n_splits folds = list(KFold(n_splits = self.n_splits, shuffle = True, random_state = 42).split(X, Y)) S_train = np.zeros((X.shape[0], len(self.base_models))) S_test = np.zeros((T.shape[0], len(self.base_models))) # Loop trough base_models print("------- FITTING Stacker - 2nd level -------") for i, clf in enumerate(self.base_models): # Create a dummy to calculate predictions on all folds S_test_i = np.zeros((T.shape[0], self.n_splits)) # Loop trough data folds for j, (train_idx, test_idx) in enumerate(folds): X_train = X[train_idx] Y_train = Y[train_idx] X_holdout = X[test_idx] Y_holdout = Y[test_idx] clf.fit(X_train, Y_train) Y_pred = clf.predict(X_holdout)[:] print (" Model {}, fold {}. R^2 score: {:.4f}"\ .format(i, j, r2_score(Y_holdout, Y_pred))) S_train[test_idx, i] = Y_pred S_test_i[:, j] = clf.predict(T)[:] # Update test data with average of predictions from the dummy S_test[:, i] = S_test_i.mean(axis = 1) # Print final CV score results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2') print("\033[1;92mDONE! \033[0;0m\033[1;37mCV scores: {:.4f} (+/- {:.4f})" .format(results.mean(), results.std() * 2)) # After creating new features on the test data, fit the chosen stacker # on train data and finally predict on test data, then return self.stacker.fit(S_train, Y) final_prediction = self.stacker.predict(S_test)[:] return final_prediction stack = Ensemble(n_splits = 5, stacker = svr_mdl, base_models = (xgb_mdl, rf_mdl, xgb_mdl, svr_mdl, xgb_mdl)) stack_pred = stack.fit_predict(X_train, Y_train, X_test) ##### PLOTS ##### # Plot outputs using scatter. Ticks are diabled and everything else is the clea- # nest that I could. Predicted prices vs Real Prices custom_style = {'axes.labelcolor': 'white', 'xtick.color': 'white', 'ytick.color': 'white'} data = pd.DataFrame(data = {'stack_pred': stack_pred, 'Y_test': Y_test}) ax = sns.lmplot(x='Y_test', y='stack_pred', data = data, truncate=True, size=5) ax.set_axis_labels("Real prices", "Predicted prices") plt.tick_params(axis='both', colors='gray') plt.title("Real vs Predicted prices on Boston Housing", fontweight = 'bold') plt.tight_layout() plt.show()
flexible
{ "blob_id": "21c581131cff8cf2f4aa407055184d56865a6335", "index": 9783, "step-1": "<mask token>\n\n\nclass Ensemble(object):\n \"\"\"Ensemble base_models on train data than fit/predict\n\n The object input is composed of 'n_splits', 'stacker' and list of\n 'base_models'.\n\n The __init__ method self-assign the inputs.\n\n The fit_predict method divides the dataset in 'n_splits' then it loops\n trough ammount of 'base_models' fitting all splits and then averaging it on\n a new column in the end. In the end, predictions are made with these new\n columns.\n\n If sought the use of voting ensemble, the ammount of models passed on\n base_models can be repeated.\n \"\"\"\n\n def __init__(self, n_splits, stacker, base_models):\n self.n_splits = n_splits\n self.stacker = stacker\n self.base_models = base_models\n\n def fit_predict(self, X, Y, T):\n X = np.array(X)\n Y = np.array(Y)\n T = np.array(T)\n folds = list(KFold(n_splits=self.n_splits, shuffle=True,\n random_state=42).split(X, Y))\n S_train = np.zeros((X.shape[0], len(self.base_models)))\n S_test = np.zeros((T.shape[0], len(self.base_models)))\n print('------- FITTING Stacker - 2nd level -------')\n for i, clf in enumerate(self.base_models):\n S_test_i = np.zeros((T.shape[0], self.n_splits))\n for j, (train_idx, test_idx) in enumerate(folds):\n X_train = X[train_idx]\n Y_train = Y[train_idx]\n X_holdout = X[test_idx]\n Y_holdout = Y[test_idx]\n clf.fit(X_train, Y_train)\n Y_pred = clf.predict(X_holdout)[:]\n print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j,\n r2_score(Y_holdout, Y_pred)))\n S_train[test_idx, i] = Y_pred\n S_test_i[:, j] = clf.predict(T)[:]\n S_test[:, i] = S_test_i.mean(axis=1)\n results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2')\n print(\n '\\x1b[1;92mDONE! \\x1b[0;0m\\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})'\n .format(results.mean(), results.std() * 2))\n self.stacker.fit(S_train, Y)\n final_prediction = self.stacker.predict(S_test)[:]\n return final_prediction\n\n\n<mask token>\n", "step-2": "<mask token>\nsns.set()\n<mask token>\nprint('------- FITTING SVR -------')\n<mask token>\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(svr_cv_scores.mean(),\n svr_cv_scores.std() * 2))\nprint('------- FITTING XGBRegressor -------')\n<mask token>\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(xgb_cv_scores.mean(),\n xgb_cv_scores.std() * 2))\nprint('------- FITTING RandomForestRegressor -------')\n<mask token>\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(rf_cv_scores.mean(), \n rf_cv_scores.std() * 2))\n\n\nclass Ensemble(object):\n \"\"\"Ensemble base_models on train data than fit/predict\n\n The object input is composed of 'n_splits', 'stacker' and list of\n 'base_models'.\n\n The __init__ method self-assign the inputs.\n\n The fit_predict method divides the dataset in 'n_splits' then it loops\n trough ammount of 'base_models' fitting all splits and then averaging it on\n a new column in the end. In the end, predictions are made with these new\n columns.\n\n If sought the use of voting ensemble, the ammount of models passed on\n base_models can be repeated.\n \"\"\"\n\n def __init__(self, n_splits, stacker, base_models):\n self.n_splits = n_splits\n self.stacker = stacker\n self.base_models = base_models\n\n def fit_predict(self, X, Y, T):\n X = np.array(X)\n Y = np.array(Y)\n T = np.array(T)\n folds = list(KFold(n_splits=self.n_splits, shuffle=True,\n random_state=42).split(X, Y))\n S_train = np.zeros((X.shape[0], len(self.base_models)))\n S_test = np.zeros((T.shape[0], len(self.base_models)))\n print('------- FITTING Stacker - 2nd level -------')\n for i, clf in enumerate(self.base_models):\n S_test_i = np.zeros((T.shape[0], self.n_splits))\n for j, (train_idx, test_idx) in enumerate(folds):\n X_train = X[train_idx]\n Y_train = Y[train_idx]\n X_holdout = X[test_idx]\n Y_holdout = Y[test_idx]\n clf.fit(X_train, Y_train)\n Y_pred = clf.predict(X_holdout)[:]\n print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j,\n r2_score(Y_holdout, Y_pred)))\n S_train[test_idx, i] = Y_pred\n S_test_i[:, j] = clf.predict(T)[:]\n S_test[:, i] = S_test_i.mean(axis=1)\n results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2')\n print(\n '\\x1b[1;92mDONE! \\x1b[0;0m\\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})'\n .format(results.mean(), results.std() * 2))\n self.stacker.fit(S_train, Y)\n final_prediction = self.stacker.predict(S_test)[:]\n return final_prediction\n\n\n<mask token>\nax.set_axis_labels('Real prices', 'Predicted prices')\nplt.tick_params(axis='both', colors='gray')\nplt.title('Real vs Predicted prices on Boston Housing', fontweight='bold')\nplt.tight_layout()\nplt.show()\n", "step-3": "<mask token>\nsns.set()\nboston = datasets.load_boston()\nboston_pd = pd.DataFrame(boston.data)\nboston_pd.columns = boston.feature_names\nX, Y = boston_pd, boston.target\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1,\n random_state=42)\nprint('------- FITTING SVR -------')\nsvr_mdl = SVR(kernel='linear', C=0.11, epsilon=0.011, gamma=0.1)\nsvr_cv_scores = cross_val_score(svr_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(svr_cv_scores.mean(),\n svr_cv_scores.std() * 2))\nprint('------- FITTING XGBRegressor -------')\nxgb_mdl = xgb.XGBRegressor(learning_rate=0.0503, n_estimators=339,\n max_depth=5, min_child_weight=2, gamma=0.17, subsample=0.84,\n colsample_bytree=0.85, reg_alpha=0.008, reg_lambda=1.2,\n scale_pos_weight=1, seed=42)\nxgb_cv_scores = cross_val_score(xgb_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(xgb_cv_scores.mean(),\n xgb_cv_scores.std() * 2))\nprint('------- FITTING RandomForestRegressor -------')\nrf_mdl = RandomForestRegressor(n_estimators=95, max_features='auto',\n max_depth=18, min_samples_split=2, min_samples_leaf=1, bootstrap=True,\n random_state=42)\nrf_cv_scores = cross_val_score(rf_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(rf_cv_scores.mean(), \n rf_cv_scores.std() * 2))\n\n\nclass Ensemble(object):\n \"\"\"Ensemble base_models on train data than fit/predict\n\n The object input is composed of 'n_splits', 'stacker' and list of\n 'base_models'.\n\n The __init__ method self-assign the inputs.\n\n The fit_predict method divides the dataset in 'n_splits' then it loops\n trough ammount of 'base_models' fitting all splits and then averaging it on\n a new column in the end. In the end, predictions are made with these new\n columns.\n\n If sought the use of voting ensemble, the ammount of models passed on\n base_models can be repeated.\n \"\"\"\n\n def __init__(self, n_splits, stacker, base_models):\n self.n_splits = n_splits\n self.stacker = stacker\n self.base_models = base_models\n\n def fit_predict(self, X, Y, T):\n X = np.array(X)\n Y = np.array(Y)\n T = np.array(T)\n folds = list(KFold(n_splits=self.n_splits, shuffle=True,\n random_state=42).split(X, Y))\n S_train = np.zeros((X.shape[0], len(self.base_models)))\n S_test = np.zeros((T.shape[0], len(self.base_models)))\n print('------- FITTING Stacker - 2nd level -------')\n for i, clf in enumerate(self.base_models):\n S_test_i = np.zeros((T.shape[0], self.n_splits))\n for j, (train_idx, test_idx) in enumerate(folds):\n X_train = X[train_idx]\n Y_train = Y[train_idx]\n X_holdout = X[test_idx]\n Y_holdout = Y[test_idx]\n clf.fit(X_train, Y_train)\n Y_pred = clf.predict(X_holdout)[:]\n print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j,\n r2_score(Y_holdout, Y_pred)))\n S_train[test_idx, i] = Y_pred\n S_test_i[:, j] = clf.predict(T)[:]\n S_test[:, i] = S_test_i.mean(axis=1)\n results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2')\n print(\n '\\x1b[1;92mDONE! \\x1b[0;0m\\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})'\n .format(results.mean(), results.std() * 2))\n self.stacker.fit(S_train, Y)\n final_prediction = self.stacker.predict(S_test)[:]\n return final_prediction\n\n\nstack = Ensemble(n_splits=5, stacker=svr_mdl, base_models=(xgb_mdl, rf_mdl,\n xgb_mdl, svr_mdl, xgb_mdl))\nstack_pred = stack.fit_predict(X_train, Y_train, X_test)\ncustom_style = {'axes.labelcolor': 'white', 'xtick.color': 'white',\n 'ytick.color': 'white'}\ndata = pd.DataFrame(data={'stack_pred': stack_pred, 'Y_test': Y_test})\nax = sns.lmplot(x='Y_test', y='stack_pred', data=data, truncate=True, size=5)\nax.set_axis_labels('Real prices', 'Predicted prices')\nplt.tick_params(axis='both', colors='gray')\nplt.title('Real vs Predicted prices on Boston Housing', fontweight='bold')\nplt.tight_layout()\nplt.show()\n", "step-4": "import numpy as np\nimport xgboost as xgb\nfrom sklearn import datasets\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import cross_val_score, train_test_split, KFold\nfrom sklearn.metrics import r2_score\nsns.set()\nboston = datasets.load_boston()\nboston_pd = pd.DataFrame(boston.data)\nboston_pd.columns = boston.feature_names\nX, Y = boston_pd, boston.target\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1,\n random_state=42)\nprint('------- FITTING SVR -------')\nsvr_mdl = SVR(kernel='linear', C=0.11, epsilon=0.011, gamma=0.1)\nsvr_cv_scores = cross_val_score(svr_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(svr_cv_scores.mean(),\n svr_cv_scores.std() * 2))\nprint('------- FITTING XGBRegressor -------')\nxgb_mdl = xgb.XGBRegressor(learning_rate=0.0503, n_estimators=339,\n max_depth=5, min_child_weight=2, gamma=0.17, subsample=0.84,\n colsample_bytree=0.85, reg_alpha=0.008, reg_lambda=1.2,\n scale_pos_weight=1, seed=42)\nxgb_cv_scores = cross_val_score(xgb_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(xgb_cv_scores.mean(),\n xgb_cv_scores.std() * 2))\nprint('------- FITTING RandomForestRegressor -------')\nrf_mdl = RandomForestRegressor(n_estimators=95, max_features='auto',\n max_depth=18, min_samples_split=2, min_samples_leaf=1, bootstrap=True,\n random_state=42)\nrf_cv_scores = cross_val_score(rf_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(' DONE! CV Scores: {:.4f} (+/- {:.4f})'.format(rf_cv_scores.mean(), \n rf_cv_scores.std() * 2))\n\n\nclass Ensemble(object):\n \"\"\"Ensemble base_models on train data than fit/predict\n\n The object input is composed of 'n_splits', 'stacker' and list of\n 'base_models'.\n\n The __init__ method self-assign the inputs.\n\n The fit_predict method divides the dataset in 'n_splits' then it loops\n trough ammount of 'base_models' fitting all splits and then averaging it on\n a new column in the end. In the end, predictions are made with these new\n columns.\n\n If sought the use of voting ensemble, the ammount of models passed on\n base_models can be repeated.\n \"\"\"\n\n def __init__(self, n_splits, stacker, base_models):\n self.n_splits = n_splits\n self.stacker = stacker\n self.base_models = base_models\n\n def fit_predict(self, X, Y, T):\n X = np.array(X)\n Y = np.array(Y)\n T = np.array(T)\n folds = list(KFold(n_splits=self.n_splits, shuffle=True,\n random_state=42).split(X, Y))\n S_train = np.zeros((X.shape[0], len(self.base_models)))\n S_test = np.zeros((T.shape[0], len(self.base_models)))\n print('------- FITTING Stacker - 2nd level -------')\n for i, clf in enumerate(self.base_models):\n S_test_i = np.zeros((T.shape[0], self.n_splits))\n for j, (train_idx, test_idx) in enumerate(folds):\n X_train = X[train_idx]\n Y_train = Y[train_idx]\n X_holdout = X[test_idx]\n Y_holdout = Y[test_idx]\n clf.fit(X_train, Y_train)\n Y_pred = clf.predict(X_holdout)[:]\n print(' Model {}, fold {}. R^2 score: {:.4f}'.format(i, j,\n r2_score(Y_holdout, Y_pred)))\n S_train[test_idx, i] = Y_pred\n S_test_i[:, j] = clf.predict(T)[:]\n S_test[:, i] = S_test_i.mean(axis=1)\n results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2')\n print(\n '\\x1b[1;92mDONE! \\x1b[0;0m\\x1b[1;37mCV scores: {:.4f} (+/- {:.4f})'\n .format(results.mean(), results.std() * 2))\n self.stacker.fit(S_train, Y)\n final_prediction = self.stacker.predict(S_test)[:]\n return final_prediction\n\n\nstack = Ensemble(n_splits=5, stacker=svr_mdl, base_models=(xgb_mdl, rf_mdl,\n xgb_mdl, svr_mdl, xgb_mdl))\nstack_pred = stack.fit_predict(X_train, Y_train, X_test)\ncustom_style = {'axes.labelcolor': 'white', 'xtick.color': 'white',\n 'ytick.color': 'white'}\ndata = pd.DataFrame(data={'stack_pred': stack_pred, 'Y_test': Y_test})\nax = sns.lmplot(x='Y_test', y='stack_pred', data=data, truncate=True, size=5)\nax.set_axis_labels('Real prices', 'Predicted prices')\nplt.tick_params(axis='both', colors='gray')\nplt.title('Real vs Predicted prices on Boston Housing', fontweight='bold')\nplt.tight_layout()\nplt.show()\n", "step-5": "#!/usr/bin/env python\n# Title : STACK_BostonHousing.py\n# Description : Stacking was the natural progression of our algorithms trial.\n# In here, we'll use prediction from a number of models in order\n# to improve accuracy as it add linearly independent data to our\n# dataset. Here we also use voting ensembler, using the best es-\n# timator three timers on the stack of second level models.\n# We'll find CV scores of each model on train_test_split then\n# stack the models on a 5-KFold of the data, finding final CV\n# score. We'll also plot the comparative graph of Real Prices vs\n# Predicted Prices\n# Author : Neves4\n# Outputs : Figure with one plot : 'Real Prices vs Predicted prices'\n# Values : SVR CV Scores: 0.6798 (+/- 0.0895)\n# XGB CV Scores: 0.8784 (+/- 0.0598)\n# RF CV Scores: 0.8601 (+/- 0.0789)\n# STACK CV Scores: 0.8809 (+/- 0.0864)\n# License : MIT License\n#==============================================================================\n\n##### IMPORTING #####\nimport numpy as np\nimport xgboost as xgb\nfrom sklearn import datasets\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import cross_val_score, train_test_split, KFold\nfrom sklearn.metrics import r2_score\n\nsns.set() # set seaborn style\n\n##### DECLARING AND TRAINING #####\n# Carregamento do dataset do boston, conversão para o framework pandas e como a\n# nomenclatura não é automática, foi dado valor às colunas da tabela do pandas.\n# Para verificar como estão os dados, chamar print(boston_pd.head())\nboston = datasets.load_boston()\nboston_pd = pd.DataFrame(boston.data)\nboston_pd.columns = boston.feature_names\n\n# É necessária então a divisão dos datasets, pelo método train_test_split. Para\n# encontrar o tamanho de cada tensor que foi dividido, print(X_train.shape)\nX, Y = boston_pd, boston.target\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.1,\n random_state = 42)\n\n# ##### 1ST LEVEL MODELS #####\n# # ElasticNet - baseline model #0\n# print(\"------- FITTING ElasticNet -------\")\n# en_mdl = ElasticNet(alpha = 5.2, l1_ratio = 0.5, random_state = 42)\n# en_cv_scores = cross_val_score(en_mdl, X_train, Y_train, cv=5, scoring='r2')\n# print(\" DONE! CV Scores: {:.4f} (+/- {:.4f})\" .format(en_cv_scores.mean(),\\\n# en_cv_scores.std() * 2))\n\n# SVR - baseline model #1\nprint(\"------- FITTING SVR -------\")\nsvr_mdl = SVR(kernel = 'linear', C = 0.11, epsilon = 0.011, gamma = 0.1)\nsvr_cv_scores = cross_val_score(svr_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(\" DONE! CV Scores: {:.4f} (+/- {:.4f})\" .format(svr_cv_scores.mean(),\\\n svr_cv_scores.std() * 2))\n\n# XGBRegressor - baseline model #2\nprint(\"------- FITTING XGBRegressor -------\")\nxgb_mdl = xgb.XGBRegressor(learning_rate = 0.0503, n_estimators = 339,\n max_depth = 5, min_child_weight = 2, gamma = 0.17,\n subsample = 0.84, colsample_bytree = 0.85,\n reg_alpha = 0.008, reg_lambda = 1.2,\n scale_pos_weight = 1, seed = 42)\nxgb_cv_scores = cross_val_score(xgb_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(\" DONE! CV Scores: {:.4f} (+/- {:.4f})\" .format(xgb_cv_scores.mean(),\\\n xgb_cv_scores.std() * 2))\n\n# RandomForestRegressor - baseline model #3\nprint(\"------- FITTING RandomForestRegressor -------\")\nrf_mdl = RandomForestRegressor(n_estimators = 95, max_features = 'auto',\n max_depth = 18, min_samples_split = 2,\n min_samples_leaf = 1, bootstrap = True,\n random_state = 42)\nrf_cv_scores = cross_val_score(rf_mdl, X_train, Y_train, cv=5, scoring='r2')\nprint(\" DONE! CV Scores: {:.4f} (+/- {:.4f})\" .format(rf_cv_scores.mean(),\\\n rf_cv_scores.std() * 2))\n\nclass Ensemble(object):\n \"\"\"Ensemble base_models on train data than fit/predict\n\n The object input is composed of 'n_splits', 'stacker' and list of\n 'base_models'.\n\n The __init__ method self-assign the inputs.\n\n The fit_predict method divides the dataset in 'n_splits' then it loops\n trough ammount of 'base_models' fitting all splits and then averaging it on\n a new column in the end. In the end, predictions are made with these new\n columns.\n\n If sought the use of voting ensemble, the ammount of models passed on\n base_models can be repeated.\n \"\"\"\n\n def __init__(self, n_splits, stacker, base_models):\n self.n_splits = n_splits\n self.stacker = stacker\n self.base_models = base_models\n\n def fit_predict(self, X, Y, T):\n X = np.array(X)\n Y = np.array(Y)\n T = np.array(T)\n\n # Create folds on the dataset based on n_splits\n folds = list(KFold(n_splits = self.n_splits, shuffle = True,\n random_state = 42).split(X, Y))\n\n S_train = np.zeros((X.shape[0], len(self.base_models)))\n S_test = np.zeros((T.shape[0], len(self.base_models)))\n\n # Loop trough base_models\n print(\"------- FITTING Stacker - 2nd level -------\")\n for i, clf in enumerate(self.base_models):\n\n # Create a dummy to calculate predictions on all folds\n S_test_i = np.zeros((T.shape[0], self.n_splits))\n\n # Loop trough data folds\n for j, (train_idx, test_idx) in enumerate(folds):\n X_train = X[train_idx]\n Y_train = Y[train_idx]\n X_holdout = X[test_idx]\n Y_holdout = Y[test_idx]\n\n clf.fit(X_train, Y_train)\n Y_pred = clf.predict(X_holdout)[:]\n\n print (\" Model {}, fold {}. R^2 score: {:.4f}\"\\\n .format(i, j, r2_score(Y_holdout, Y_pred)))\n\n S_train[test_idx, i] = Y_pred\n S_test_i[:, j] = clf.predict(T)[:]\n\n # Update test data with average of predictions from the dummy\n S_test[:, i] = S_test_i.mean(axis = 1)\n\n # Print final CV score\n results = cross_val_score(self.stacker, S_train, Y, cv=5, scoring='r2')\n print(\"\\033[1;92mDONE! \\033[0;0m\\033[1;37mCV scores: {:.4f} (+/- {:.4f})\"\n .format(results.mean(), results.std() * 2))\n\n # After creating new features on the test data, fit the chosen stacker\n # on train data and finally predict on test data, then return\n self.stacker.fit(S_train, Y)\n final_prediction = self.stacker.predict(S_test)[:]\n\n return final_prediction\n\nstack = Ensemble(n_splits = 5, stacker = svr_mdl,\n base_models = (xgb_mdl, rf_mdl, xgb_mdl, svr_mdl, xgb_mdl))\n\nstack_pred = stack.fit_predict(X_train, Y_train, X_test)\n\n##### PLOTS #####\n# Plot outputs using scatter. Ticks are diabled and everything else is the clea-\n# nest that I could. Predicted prices vs Real Prices\ncustom_style = {'axes.labelcolor': 'white',\n 'xtick.color': 'white',\n 'ytick.color': 'white'}\ndata = pd.DataFrame(data = {'stack_pred': stack_pred, 'Y_test': Y_test})\nax = sns.lmplot(x='Y_test', y='stack_pred', data = data, truncate=True, size=5)\nax.set_axis_labels(\"Real prices\", \"Predicted prices\")\nplt.tick_params(axis='both', colors='gray')\nplt.title(\"Real vs Predicted prices on Boston Housing\", fontweight = 'bold')\nplt.tight_layout()\nplt.show()\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
class Image: def __init__(self, **kwargs): self.ClientID = kwargs['ClientID'] self.DealerID = kwargs['DealerID'] self.VIN = kwargs['VIN'] self.UrlVdp = None self.PhotoURL = kwargs['PhotoURL'] self.VdpActive = None def __repr__(self): return f"{self.DealerID} {self.VIN} {self.UrlVdp}" class VehiclePhoto: def __init__(self, **kwargs): self.ClientID = kwargs['ClientID'] self.DealerID = kwargs['DealerID'] self.Domain = kwargs['Domain'] self.VehiclePhotoID = kwargs['VehiclePhotoID'] self.VIN = kwargs['VIN'] self.UrlVdp = kwargs['UrlVdp'] self.UrlImage = kwargs['UrlImage'] def __repr__(self): return f"{self.VehiclePhotoID} {self.VIN} {self.UrlVdp}"
normal
{ "blob_id": "3dc4e10145ad42c0168fec3462da0f87c1e661a5", "index": 8701, "step-1": "<mask token>\n\n\nclass VehiclePhoto:\n <mask token>\n\n def __repr__(self):\n return f'{self.VehiclePhotoID} {self.VIN} {self.UrlVdp}'\n", "step-2": "class Image:\n <mask token>\n <mask token>\n\n\nclass VehiclePhoto:\n\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.Domain = kwargs['Domain']\n self.VehiclePhotoID = kwargs['VehiclePhotoID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = kwargs['UrlVdp']\n self.UrlImage = kwargs['UrlImage']\n\n def __repr__(self):\n return f'{self.VehiclePhotoID} {self.VIN} {self.UrlVdp}'\n", "step-3": "class Image:\n\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = None\n self.PhotoURL = kwargs['PhotoURL']\n self.VdpActive = None\n <mask token>\n\n\nclass VehiclePhoto:\n\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.Domain = kwargs['Domain']\n self.VehiclePhotoID = kwargs['VehiclePhotoID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = kwargs['UrlVdp']\n self.UrlImage = kwargs['UrlImage']\n\n def __repr__(self):\n return f'{self.VehiclePhotoID} {self.VIN} {self.UrlVdp}'\n", "step-4": "class Image:\n\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = None\n self.PhotoURL = kwargs['PhotoURL']\n self.VdpActive = None\n\n def __repr__(self):\n return f'{self.DealerID} {self.VIN} {self.UrlVdp}'\n\n\nclass VehiclePhoto:\n\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.Domain = kwargs['Domain']\n self.VehiclePhotoID = kwargs['VehiclePhotoID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = kwargs['UrlVdp']\n self.UrlImage = kwargs['UrlImage']\n\n def __repr__(self):\n return f'{self.VehiclePhotoID} {self.VIN} {self.UrlVdp}'\n", "step-5": "class Image:\n\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = None\n self.PhotoURL = kwargs['PhotoURL']\n self.VdpActive = None\n \n def __repr__(self):\n return f\"{self.DealerID} {self.VIN} {self.UrlVdp}\"\n\nclass VehiclePhoto:\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.Domain = kwargs['Domain']\n self.VehiclePhotoID = kwargs['VehiclePhotoID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = kwargs['UrlVdp']\n self.UrlImage = kwargs['UrlImage']\n \n def __repr__(self):\n return f\"{self.VehiclePhotoID} {self.VIN} {self.UrlVdp}\"", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> class Solution: <|reserved_special_token_0|> <|reserved_special_token_1|> class Solution: def jump(self, nums: List[int]) ->int: if len(nums) < 2: return 0 jump = 1 curr_max = max_reach = nums[0] for i in range(1, len(nums)): if max_reach >= len(nums) - 1: return jump curr_max = max(curr_max, i + nums[i]) if i == max_reach: max_reach = curr_max jump += 1 return jump <|reserved_special_token_1|> class Solution: def jump(self, nums: List[int]) -> int: if len(nums) < 2: return 0 jump = 1 curr_max = max_reach = nums[0] for i in range(1, len(nums)): if max_reach >= len(nums) - 1: return jump curr_max = max(curr_max, i + nums[i]) if i == max_reach: max_reach = curr_max jump += 1 return jump # TC: O(n) # n is the len(nums), as we only scan the list once # SC: O(1) # we only init 3 variables, thus space is constant
flexible
{ "blob_id": "7f2ffa653486d000c9eee0087fc1e6ca0c84003c", "index": 5671, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def jump(self, nums: List[int]) ->int:\n if len(nums) < 2:\n return 0\n jump = 1\n curr_max = max_reach = nums[0]\n for i in range(1, len(nums)):\n if max_reach >= len(nums) - 1:\n return jump\n curr_max = max(curr_max, i + nums[i])\n if i == max_reach:\n max_reach = curr_max\n jump += 1\n return jump\n", "step-4": "class Solution:\n def jump(self, nums: List[int]) -> int:\n \n if len(nums) < 2: return 0 \n \n jump = 1 \n curr_max = max_reach = nums[0] \n \n for i in range(1, len(nums)): \n if max_reach >= len(nums) - 1: \n return jump\n \n curr_max = max(curr_max, i + nums[i])\n \n if i == max_reach: \n max_reach = curr_max \n jump += 1 \n \n return jump\n \n # TC: O(n)\n # n is the len(nums), as we only scan the list once\n \n # SC: O(1)\n # we only init 3 variables, thus space is constant\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#downloads project detail reports from the web and places them in the correct project folder created by makeFolders.py import os, openpyxl, time, shutil from selenium import webdriver from selenium.webdriver.common.keys import Keys wb = openpyxl.load_workbook('ProjectSummary.xlsx') sheet = wb.active browser = webdriver.Firefox() browser.get('https://safetynet.predictivesolutions.com/CRMApp/default_login.jsp?loginZoneID=10459&originalHostName=jdc.predictivesolutions.com') userElem = browser.find_element_by_id('username') userElem.send_keys('temp') passElem = browser.find_element_by_id('password') passElem.send_keys('temp') passElem.submit() time.sleep(3) linkElem = browser.find_element_by_link_text('Reports') linkElem.click() time.sleep(2) linkElem = browser.find_element_by_link_text('Detail Report') linkElem.click() time.sleep(4) def pdfToFolder(projectName): os.chdir('/home/gmclaughlin/Downloads') if projectName.find("DEM") != -1: shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/Demo/%s/%s-Detail Report.pdf' % (projectName, projectName)) elif projectName.find("JDC") != -1: shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/JDC/%s/%s-Detail Report.pdf' % (projectName, projectName)) elif projectName.find("NEW") != -1: shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/NewRoads/%s/%s-Detail Report.pdf' % (projectName, projectName)) elif projectName.find("Site") != -1: shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/SiteCrew/%s/%s-Detail Report.pdf' % (projectName, projectName)) else: shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/Other/%s/%s-Detail Report.pdf' % (projectName, projectName)) finsihedFlag = False addValue = 0 counter = 0 for cellObj in sheet['A']: if cellObj.value != 'Project' and cellObj.value != 'JDC-Winchester HS Enabling (CONSIG': linkElem = browser.find_element_by_name('clear') #clear existing settings linkElem.click() time.sleep(4) linkElem = browser.find_element_by_name('showSafeAndUnsafeDetails') #select all reports linkElem.click() time.sleep(1) linkElem = browser.find_element_by_name('showImages') #show images in reports linkElem.click() time.sleep(1) linkElem = browser.find_element_by_name('datePickerRadio') linkElem.click() time.sleep(1) projectElem = browser.find_elements_by_xpath("//input[@type='text']") #find and use text fields print(cellObj.value) #projectElem = browser.find_element_by_xpath("//input[4]") #time.sleep(2) #projectElem[5+addValue].clear() projectElem[5+addValue].send_keys('01/01/2010') time.sleep(1) #projectElem[6+addValue].clear() projectElem[6+addValue].send_keys('08/15/2017') time.sleep(1) projectElem[8+addValue].clear() #this is the project name box projectElem[8+addValue].send_keys(cellObj.value) time.sleep(1) projectElem[8+addValue].send_keys(Keys.ENTER) time.sleep(3) linkElem = browser.find_element_by_xpath("//input[@type='submit']") #submit request for report linkElem.click() time.sleep(10) linkElem = browser.find_element_by_name('pdf') #download as PDF linkElem.click() time.sleep(70) addValue = 1 pdfToFolder(cellObj.value) counter = counter + 1
normal
{ "blob_id": "6e9fd8ee2a187888df07c9dd1c32fe59a111c869", "index": 8823, "step-1": "<mask token>\n\n\ndef pdfToFolder(projectName):\n os.chdir('/home/gmclaughlin/Downloads')\n if projectName.find('DEM') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Demo/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('JDC') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/JDC/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('NEW') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/NewRoads/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('Site') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/SiteCrew/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n else:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Other/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n\n\n<mask token>\n", "step-2": "<mask token>\nbrowser.get(\n 'https://safetynet.predictivesolutions.com/CRMApp/default_login.jsp?loginZoneID=10459&originalHostName=jdc.predictivesolutions.com'\n )\n<mask token>\nuserElem.send_keys('temp')\n<mask token>\npassElem.send_keys('temp')\npassElem.submit()\ntime.sleep(3)\n<mask token>\nlinkElem.click()\ntime.sleep(2)\n<mask token>\nlinkElem.click()\ntime.sleep(4)\n\n\ndef pdfToFolder(projectName):\n os.chdir('/home/gmclaughlin/Downloads')\n if projectName.find('DEM') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Demo/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('JDC') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/JDC/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('NEW') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/NewRoads/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('Site') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/SiteCrew/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n else:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Other/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n\n\n<mask token>\nfor cellObj in sheet['A']:\n if (cellObj.value != 'Project' and cellObj.value !=\n 'JDC-Winchester HS Enabling (CONSIG'):\n linkElem = browser.find_element_by_name('clear')\n linkElem.click()\n time.sleep(4)\n linkElem = browser.find_element_by_name('showSafeAndUnsafeDetails')\n linkElem.click()\n time.sleep(1)\n linkElem = browser.find_element_by_name('showImages')\n linkElem.click()\n time.sleep(1)\n linkElem = browser.find_element_by_name('datePickerRadio')\n linkElem.click()\n time.sleep(1)\n projectElem = browser.find_elements_by_xpath(\"//input[@type='text']\")\n print(cellObj.value)\n projectElem[5 + addValue].send_keys('01/01/2010')\n time.sleep(1)\n projectElem[6 + addValue].send_keys('08/15/2017')\n time.sleep(1)\n projectElem[8 + addValue].clear()\n projectElem[8 + addValue].send_keys(cellObj.value)\n time.sleep(1)\n projectElem[8 + addValue].send_keys(Keys.ENTER)\n time.sleep(3)\n linkElem = browser.find_element_by_xpath(\"//input[@type='submit']\")\n linkElem.click()\n time.sleep(10)\n linkElem = browser.find_element_by_name('pdf')\n linkElem.click()\n time.sleep(70)\n addValue = 1\n pdfToFolder(cellObj.value)\n counter = counter + 1\n", "step-3": "<mask token>\nwb = openpyxl.load_workbook('ProjectSummary.xlsx')\nsheet = wb.active\nbrowser = webdriver.Firefox()\nbrowser.get(\n 'https://safetynet.predictivesolutions.com/CRMApp/default_login.jsp?loginZoneID=10459&originalHostName=jdc.predictivesolutions.com'\n )\nuserElem = browser.find_element_by_id('username')\nuserElem.send_keys('temp')\npassElem = browser.find_element_by_id('password')\npassElem.send_keys('temp')\npassElem.submit()\ntime.sleep(3)\nlinkElem = browser.find_element_by_link_text('Reports')\nlinkElem.click()\ntime.sleep(2)\nlinkElem = browser.find_element_by_link_text('Detail Report')\nlinkElem.click()\ntime.sleep(4)\n\n\ndef pdfToFolder(projectName):\n os.chdir('/home/gmclaughlin/Downloads')\n if projectName.find('DEM') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Demo/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('JDC') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/JDC/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('NEW') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/NewRoads/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('Site') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/SiteCrew/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n else:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Other/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n\n\nfinsihedFlag = False\naddValue = 0\ncounter = 0\nfor cellObj in sheet['A']:\n if (cellObj.value != 'Project' and cellObj.value !=\n 'JDC-Winchester HS Enabling (CONSIG'):\n linkElem = browser.find_element_by_name('clear')\n linkElem.click()\n time.sleep(4)\n linkElem = browser.find_element_by_name('showSafeAndUnsafeDetails')\n linkElem.click()\n time.sleep(1)\n linkElem = browser.find_element_by_name('showImages')\n linkElem.click()\n time.sleep(1)\n linkElem = browser.find_element_by_name('datePickerRadio')\n linkElem.click()\n time.sleep(1)\n projectElem = browser.find_elements_by_xpath(\"//input[@type='text']\")\n print(cellObj.value)\n projectElem[5 + addValue].send_keys('01/01/2010')\n time.sleep(1)\n projectElem[6 + addValue].send_keys('08/15/2017')\n time.sleep(1)\n projectElem[8 + addValue].clear()\n projectElem[8 + addValue].send_keys(cellObj.value)\n time.sleep(1)\n projectElem[8 + addValue].send_keys(Keys.ENTER)\n time.sleep(3)\n linkElem = browser.find_element_by_xpath(\"//input[@type='submit']\")\n linkElem.click()\n time.sleep(10)\n linkElem = browser.find_element_by_name('pdf')\n linkElem.click()\n time.sleep(70)\n addValue = 1\n pdfToFolder(cellObj.value)\n counter = counter + 1\n", "step-4": "import os, openpyxl, time, shutil\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nwb = openpyxl.load_workbook('ProjectSummary.xlsx')\nsheet = wb.active\nbrowser = webdriver.Firefox()\nbrowser.get(\n 'https://safetynet.predictivesolutions.com/CRMApp/default_login.jsp?loginZoneID=10459&originalHostName=jdc.predictivesolutions.com'\n )\nuserElem = browser.find_element_by_id('username')\nuserElem.send_keys('temp')\npassElem = browser.find_element_by_id('password')\npassElem.send_keys('temp')\npassElem.submit()\ntime.sleep(3)\nlinkElem = browser.find_element_by_link_text('Reports')\nlinkElem.click()\ntime.sleep(2)\nlinkElem = browser.find_element_by_link_text('Detail Report')\nlinkElem.click()\ntime.sleep(4)\n\n\ndef pdfToFolder(projectName):\n os.chdir('/home/gmclaughlin/Downloads')\n if projectName.find('DEM') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Demo/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('JDC') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/JDC/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('NEW') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/NewRoads/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n elif projectName.find('Site') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/SiteCrew/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n else:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n '/home/gmclaughlin/Python/Safety Project/Other/%s/%s-Detail Report.pdf'\n % (projectName, projectName))\n\n\nfinsihedFlag = False\naddValue = 0\ncounter = 0\nfor cellObj in sheet['A']:\n if (cellObj.value != 'Project' and cellObj.value !=\n 'JDC-Winchester HS Enabling (CONSIG'):\n linkElem = browser.find_element_by_name('clear')\n linkElem.click()\n time.sleep(4)\n linkElem = browser.find_element_by_name('showSafeAndUnsafeDetails')\n linkElem.click()\n time.sleep(1)\n linkElem = browser.find_element_by_name('showImages')\n linkElem.click()\n time.sleep(1)\n linkElem = browser.find_element_by_name('datePickerRadio')\n linkElem.click()\n time.sleep(1)\n projectElem = browser.find_elements_by_xpath(\"//input[@type='text']\")\n print(cellObj.value)\n projectElem[5 + addValue].send_keys('01/01/2010')\n time.sleep(1)\n projectElem[6 + addValue].send_keys('08/15/2017')\n time.sleep(1)\n projectElem[8 + addValue].clear()\n projectElem[8 + addValue].send_keys(cellObj.value)\n time.sleep(1)\n projectElem[8 + addValue].send_keys(Keys.ENTER)\n time.sleep(3)\n linkElem = browser.find_element_by_xpath(\"//input[@type='submit']\")\n linkElem.click()\n time.sleep(10)\n linkElem = browser.find_element_by_name('pdf')\n linkElem.click()\n time.sleep(70)\n addValue = 1\n pdfToFolder(cellObj.value)\n counter = counter + 1\n", "step-5": "#downloads project detail reports from the web and places them in the correct project folder created by makeFolders.py\n\nimport os, openpyxl, time, shutil\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nwb = openpyxl.load_workbook('ProjectSummary.xlsx')\nsheet = wb.active\n\nbrowser = webdriver.Firefox()\nbrowser.get('https://safetynet.predictivesolutions.com/CRMApp/default_login.jsp?loginZoneID=10459&originalHostName=jdc.predictivesolutions.com')\n\nuserElem = browser.find_element_by_id('username')\nuserElem.send_keys('temp')\npassElem = browser.find_element_by_id('password')\npassElem.send_keys('temp')\npassElem.submit()\n\ntime.sleep(3)\nlinkElem = browser.find_element_by_link_text('Reports')\nlinkElem.click()\ntime.sleep(2)\nlinkElem = browser.find_element_by_link_text('Detail Report')\nlinkElem.click()\ntime.sleep(4)\n\ndef pdfToFolder(projectName):\n os.chdir('/home/gmclaughlin/Downloads')\n if projectName.find(\"DEM\") != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/Demo/%s/%s-Detail Report.pdf' % (projectName, projectName))\n\n elif projectName.find(\"JDC\") != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/JDC/%s/%s-Detail Report.pdf' % (projectName, projectName))\n\n elif projectName.find(\"NEW\") != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/NewRoads/%s/%s-Detail Report.pdf' % (projectName, projectName))\n\n elif projectName.find(\"Site\") != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/SiteCrew/%s/%s-Detail Report.pdf' % (projectName, projectName))\n\n else:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf','/home/gmclaughlin/Python/Safety Project/Other/%s/%s-Detail Report.pdf' % (projectName, projectName))\n\nfinsihedFlag = False\naddValue = 0\ncounter = 0\nfor cellObj in sheet['A']:\n if cellObj.value != 'Project' and cellObj.value != 'JDC-Winchester HS Enabling (CONSIG':\n\n linkElem = browser.find_element_by_name('clear') #clear existing settings\n linkElem.click()\n time.sleep(4)\n\n linkElem = browser.find_element_by_name('showSafeAndUnsafeDetails') #select all reports\n linkElem.click()\n time.sleep(1)\n\n linkElem = browser.find_element_by_name('showImages') #show images in reports\n linkElem.click()\n time.sleep(1)\n\n linkElem = browser.find_element_by_name('datePickerRadio')\n linkElem.click()\n time.sleep(1)\n\n projectElem = browser.find_elements_by_xpath(\"//input[@type='text']\") #find and use text fields\n print(cellObj.value)\n #projectElem = browser.find_element_by_xpath(\"//input[4]\")\n #time.sleep(2)\n #projectElem[5+addValue].clear()\n projectElem[5+addValue].send_keys('01/01/2010')\n time.sleep(1)\n #projectElem[6+addValue].clear()\n projectElem[6+addValue].send_keys('08/15/2017')\n time.sleep(1)\n projectElem[8+addValue].clear() #this is the project name box\n projectElem[8+addValue].send_keys(cellObj.value)\n time.sleep(1)\n projectElem[8+addValue].send_keys(Keys.ENTER)\n time.sleep(3)\n\n linkElem = browser.find_element_by_xpath(\"//input[@type='submit']\") #submit request for report\n linkElem.click()\n time.sleep(10)\n\n linkElem = browser.find_element_by_name('pdf') #download as PDF\n linkElem.click()\n time.sleep(70)\n addValue = 1\n\n pdfToFolder(cellObj.value)\n\n counter = counter + 1\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# 同一目录下的引用调用还是随意导入使用的 # 跨包使用就需要使用TwoUsage里面的两种方式。 import Importex Importex.atest()
normal
{ "blob_id": "1a66e7f59ada43deb8e28b9806dc4fb9be4ae247", "index": 5771, "step-1": "<mask token>\n", "step-2": "<mask token>\nImportex.atest()\n", "step-3": "import Importex\nImportex.atest()\n", "step-4": "# 同一目录下的引用调用还是随意导入使用的\n# 跨包使用就需要使用TwoUsage里面的两种方式。\n\nimport Importex\n\nImportex.atest()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class Test(TestItem): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def abortRun(self): self._runHistory.pop() <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @property def funcName(self): return self.item.__name__ <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @property def state(self): rec = self.runRecord if rec: return rec.state return NOT_RUN <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def addRunRecord(self, record): self._runHistory.append(record) if len(self._runHistory) > 5: self._runHistory[:] = self._runHistory[-5:] <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class NullTest(Test): amNull = True def __init__(self): context = Context.getContext(dirPath=os.getcwd()) super(NullTest, self).__init__(None, None, None, context) self.number = 0 self.startNewRun() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() @property def isBug(self): return False def __bool__(self): return False class Suite(TestItem): typeName = 'Suite' isSuite = True def __init__(self, *args, **kwargs): self.myDir = kwargs.pop('myDir') super(Suite, self).__init__(*args, **kwargs) self.exited = False self.number = 0 self.skipTests = False self.entered = False def reset(self): self.entered = False self.skipTests = False @intelliprop def children(self): """All the direct children of this item.""" tests = [t for t in self._collection if t.parent is self] suites = [t for t in self._collection.suites if t.parent is self] return suites + tests @intelliprop def tests(self): """All the direct test children of this item.""" return [t for t in self._collection if t.parent is self] @property def suite(self): return self.item @property def runAfter(self): """The _run_after for this source.""" return self.namespace.get('_run_after', []) @property def postCheck(self): return self.namespace.get('postCheck', lambda : None) @property def setUp(self): return self.namespace.get('setUp', lambda : None) @property def postSetUp(self): return self.namespace.get('postSetUp', lambda : None) @property def tearDown(self): return self.namespace.get('tearDown', lambda : None) @property def suiteSetUp(self): return self.namespace.get('suiteSetUp', lambda : None) @property def suiteTearDown(self): return self.namespace.get('suiteTearDown', lambda : None) def getResult(self, name=None): runCount = 0 childStates = {} result = Result(PASS, NONE) if not self.children: result.state = NOT_RUN return result for c in self.children: state = c.state runCount += state is not NOT_RUN childStates[state] = None if FAIL in childStates: result.state = CHILD_FAIL elif CHILD_FAIL in childStates: result.state = CHILD_FAIL elif BAD_SETUP in childStates: result.state = CHILD_FAIL elif PART_RUN in childStates: result.state = PART_RUN elif NOT_RUN in childStates: if runCount: result.state = PART_RUN else: result.state = NOT_RUN return result @property def result(self): return self.getResult() @property def state(self): result = self.getResult() return result.reportCode def hasTests(self): for t in self._collection: if t.parent is self: return True class ModuleSuite(Suite): pass class ClassSuite(Suite): @property def klass(self): return self.item.__class__.__name__ <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestItem: <|reserved_special_token_0|> def __init__(self, item, uid, parentUid, context, namespace=None): """Constructor: :Parameters: item The concrete test item. For a test function/method this is the function/method itself. For a `ClassSuite` this is the instance and for a `ModuleSuite` this is the the module instance. uid The unique ID for this item, which is a tuple of strings. parentUid The unique ID of the parent item or ``None``. Only the root `Suite` of a test tree has a parent of ``None``. namespace A dictionary that provides the containing namespace for the test item. """ self.item = item self.uid = uid self.context = context self.parentUid = parentUid self.namespace = self._getNamespace(namespace) self._collection = None self._running = False self._marks = {} self.extraInfo = {} <|reserved_special_token_0|> <|reserved_special_token_0|> def isMarked(self, mark): return mark in self._marks <|reserved_special_token_0|> <|reserved_special_token_0|> @intelliprop def state(self): """The current state of the test. """ result = self.getResult() return result.state def setState(self, state): if state is PASS: pass <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @property def path(self): p = self.namespace.get('__file__', None) if p is None: return self.parent.path if p.endswith('.pyc'): p = p[:-1] return p <|reserved_special_token_0|> <|reserved_special_token_0|> class Test(TestItem): typeName = 'Test' isSuite = False amNull = False def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) self._runHistory = [] self.stopAll = False if self.func: self.func.cs_test_info.test = weakref.proxy(self) def getHistory(self): return self._runHistory def dumpHist(self): return self._runHistory[-1].dump() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() def addStepRecord(self, name): runRecord = self._runHistory[-1] return runRecord.addStepRecord(name) @property def postCheck(self): return self.parent.postCheck @intelliprop def hasFailed(self): """Check if this test has properly failed. :Return: ``True`` if the test has failed to run for any reason. """ record = self.getRunRecord().getRecord('run') return record.state is FAIL @property def klass(self): return self.parent.klass @property def funcName(self): return self.item.__name__ @property def func(self): return self.item @property def info(self): return self.func.cs_test_info @property def isBroken(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) flag = self.info.reserved_cs_flags.get('broken', None) if flag is None: flag = self.info.cs_flags.get('broken', False) return flag @property def isTodo(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) return self.info.cs_flags.get('todo', False) @property def isBug(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) flag = self.info.reserved_cs_flags.get('bug', None) if flag is None: flag = self.info.cs_flags.get('bug', False) return flag @property def shouldFork(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) if self.info.reserved_cs_flags.get('fork', False): return True parent = self.parent try: return parent.suite.cs_attrs.fork_all except AttributeError: return False @property def testID(self): return self.info.cs_tags.get('testID', None) @property def title(self): return self.info.cs_flags.get('title', None) @property def isRunnable(self): if self.parent.exited: return False return True @property def state(self): rec = self.runRecord if rec: return rec.state return NOT_RUN @property def result(self): rec = self.runRecord if rec: return rec.result return NOT_RUN @property def hasRunProblem(self): rec = self.runRecord if rec: return rec.hasRunProblem return False @property def hasFailed(self): rec = self.runRecord if rec: return rec.hasFailed return False def addRunRecord(self, record): self._runHistory.append(record) if len(self._runHistory) > 5: self._runHistory[:] = self._runHistory[-5:] @property def runRecord(self): """The XXX TODO""" if self._runHistory: for rec in reversed(self._runHistory): if not rec.invalid: return rec @property def phaseRecord(self): """The XXX TODO""" if not self._runHistory: return None, None return self._runHistory[-1].phaseRecord def getStepRecord(self, phase): return self._runHistory[-1].getStepRecord(phase) def getTestProcedure(self): return self._collection.spec.getThing(self) class NullTest(Test): amNull = True def __init__(self): context = Context.getContext(dirPath=os.getcwd()) super(NullTest, self).__init__(None, None, None, context) self.number = 0 self.startNewRun() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() @property def isBug(self): return False def __bool__(self): return False class Suite(TestItem): typeName = 'Suite' isSuite = True def __init__(self, *args, **kwargs): self.myDir = kwargs.pop('myDir') super(Suite, self).__init__(*args, **kwargs) self.exited = False self.number = 0 self.skipTests = False self.entered = False def reset(self): self.entered = False self.skipTests = False @intelliprop def children(self): """All the direct children of this item.""" tests = [t for t in self._collection if t.parent is self] suites = [t for t in self._collection.suites if t.parent is self] return suites + tests @intelliprop def tests(self): """All the direct test children of this item.""" return [t for t in self._collection if t.parent is self] @property def suite(self): return self.item @property def runAfter(self): """The _run_after for this source.""" return self.namespace.get('_run_after', []) @property def postCheck(self): return self.namespace.get('postCheck', lambda : None) @property def setUp(self): return self.namespace.get('setUp', lambda : None) @property def postSetUp(self): return self.namespace.get('postSetUp', lambda : None) @property def tearDown(self): return self.namespace.get('tearDown', lambda : None) @property def suiteSetUp(self): return self.namespace.get('suiteSetUp', lambda : None) @property def suiteTearDown(self): return self.namespace.get('suiteTearDown', lambda : None) def getResult(self, name=None): runCount = 0 childStates = {} result = Result(PASS, NONE) if not self.children: result.state = NOT_RUN return result for c in self.children: state = c.state runCount += state is not NOT_RUN childStates[state] = None if FAIL in childStates: result.state = CHILD_FAIL elif CHILD_FAIL in childStates: result.state = CHILD_FAIL elif BAD_SETUP in childStates: result.state = CHILD_FAIL elif PART_RUN in childStates: result.state = PART_RUN elif NOT_RUN in childStates: if runCount: result.state = PART_RUN else: result.state = NOT_RUN return result @property def result(self): return self.getResult() @property def state(self): result = self.getResult() return result.reportCode def hasTests(self): for t in self._collection: if t.parent is self: return True class ModuleSuite(Suite): pass class ClassSuite(Suite): @property def klass(self): return self.item.__class__.__name__ <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestItem: <|reserved_special_token_0|> def __init__(self, item, uid, parentUid, context, namespace=None): """Constructor: :Parameters: item The concrete test item. For a test function/method this is the function/method itself. For a `ClassSuite` this is the instance and for a `ModuleSuite` this is the the module instance. uid The unique ID for this item, which is a tuple of strings. parentUid The unique ID of the parent item or ``None``. Only the root `Suite` of a test tree has a parent of ``None``. namespace A dictionary that provides the containing namespace for the test item. """ self.item = item self.uid = uid self.context = context self.parentUid = parentUid self.namespace = self._getNamespace(namespace) self._collection = None self._running = False self._marks = {} self.extraInfo = {} def setMark(self, mark): self._marks[mark] = None def clearMark(self, mark): if mark in self._marks: del self._marks[mark] def isMarked(self, mark): return mark in self._marks def setCollection(self, collection): self._collection = weakref.proxy(collection) <|reserved_special_token_0|> @intelliprop def state(self): """The current state of the test. """ result = self.getResult() return result.state def setState(self, state): if state is PASS: pass @intelliprop def level(self): """This item's level in the test tree. This is the number of ancestors this item has. If zero then this is the 'root' item. """ return len(self.ancestors) @intelliprop def parent(self): """The parent of this item, which may be ``None``. If this is ``None`` then this item is the root of a (possibly nested) suite of tests. """ return self._collection.parent(self) @intelliprop def ancestors(self): """A list of all ancestors for this item. Each entry is a UID. The first entry is the oldest ancesctor and the last entry is the immediate parent's UID. """ return self._collection.getAncestors(self) def hasFailingAncestor(self): """Check if any ancestor is considered to have failed. An ancestor suite has failed if, for example, its ``suiteSetup`` failed. :Return: ``True`` if any ancestors has failed. """ parent = self.parent if parent is None: return return return parent.hasFailed or parent.hasFailingAncestor() <|reserved_special_token_0|> @intelliprop def rawDoc(self): """The raw docstring, no cleaning up performed at all.""" return self.namespace['__doc__'] @intelliprop def docLines(self): """The docstring as lines. This is cleaned up to remove leading and trailing blank lines from the summary and details. :Return: A sequence of (non-nul terminated) lines for the docstring. The summary (if present) is separated from the details by a single empty line. """ summary, description = self._getDocParts() if description: return summary + [''] + description return summary @intelliprop def doc(self): """The docstring after being cleaned up. :Return: The cleaned up docstrinc as a multiline string. Leading and trailing blank lines are removed and the summary is separated from any details by a single blakn line. Common leading whitspace is also removed from each line. """ return '\n'.join(self.docLines) def _getDocParts(self): lines = self.rawDoc.splitlines() while lines and not lines[0].strip(): lines.pop(0) summary = [] while lines and lines[0].strip(): summary.append(lines.pop(0)) while lines and not lines[0].strip(): lines.pop(0) while lines and not lines[-1].strip(): lines.pop() summary = summary[:1] + dedentLines(summary[1:]) details = dedentLines(lines) return summary, details @property def summary(self): summary, description = self._getDocParts() return ' '.join(summary) @property def details(self): summary, description = self._getDocParts() return description @property def sourcesUnderTest(self): sources = [] for p in self.namespace.get('sources_under_test', []): if not os.path.isabs(p): p = os.path.abspath(os.path.join(self.dirname, p)) sources.append(p) p = self.parent if p is not None: sources.extend(p.sourcesUnderTest) return sources @property def klass(self): return None @property def path(self): p = self.namespace.get('__file__', None) if p is None: return self.parent.path if p.endswith('.pyc'): p = p[:-1] return p @property def dirname(self): f = self.path if f: return os.path.dirname(f) @property def isBug(self): return False class Test(TestItem): typeName = 'Test' isSuite = False amNull = False def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) self._runHistory = [] self.stopAll = False if self.func: self.func.cs_test_info.test = weakref.proxy(self) def getHistory(self): return self._runHistory def dumpHist(self): return self._runHistory[-1].dump() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() def addStepRecord(self, name): runRecord = self._runHistory[-1] return runRecord.addStepRecord(name) @property def postCheck(self): return self.parent.postCheck @intelliprop def hasFailed(self): """Check if this test has properly failed. :Return: ``True`` if the test has failed to run for any reason. """ record = self.getRunRecord().getRecord('run') return record.state is FAIL @property def klass(self): return self.parent.klass @property def funcName(self): return self.item.__name__ @property def func(self): return self.item @property def info(self): return self.func.cs_test_info @property def isBroken(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) flag = self.info.reserved_cs_flags.get('broken', None) if flag is None: flag = self.info.cs_flags.get('broken', False) return flag @property def isTodo(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) return self.info.cs_flags.get('todo', False) @property def isBug(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) flag = self.info.reserved_cs_flags.get('bug', None) if flag is None: flag = self.info.cs_flags.get('bug', False) return flag @property def shouldFork(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) if self.info.reserved_cs_flags.get('fork', False): return True parent = self.parent try: return parent.suite.cs_attrs.fork_all except AttributeError: return False @property def testID(self): return self.info.cs_tags.get('testID', None) @property def title(self): return self.info.cs_flags.get('title', None) @property def isRunnable(self): if self.parent.exited: return False return True @property def state(self): rec = self.runRecord if rec: return rec.state return NOT_RUN @property def result(self): rec = self.runRecord if rec: return rec.result return NOT_RUN @property def hasRunProblem(self): rec = self.runRecord if rec: return rec.hasRunProblem return False @property def hasFailed(self): rec = self.runRecord if rec: return rec.hasFailed return False def addRunRecord(self, record): self._runHistory.append(record) if len(self._runHistory) > 5: self._runHistory[:] = self._runHistory[-5:] @property def runRecord(self): """The XXX TODO""" if self._runHistory: for rec in reversed(self._runHistory): if not rec.invalid: return rec @property def phaseRecord(self): """The XXX TODO""" if not self._runHistory: return None, None return self._runHistory[-1].phaseRecord def getStepRecord(self, phase): return self._runHistory[-1].getStepRecord(phase) def getTestProcedure(self): return self._collection.spec.getThing(self) class NullTest(Test): amNull = True def __init__(self): context = Context.getContext(dirPath=os.getcwd()) super(NullTest, self).__init__(None, None, None, context) self.number = 0 self.startNewRun() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() @property def isBug(self): return False def __bool__(self): return False class Suite(TestItem): typeName = 'Suite' isSuite = True def __init__(self, *args, **kwargs): self.myDir = kwargs.pop('myDir') super(Suite, self).__init__(*args, **kwargs) self.exited = False self.number = 0 self.skipTests = False self.entered = False def reset(self): self.entered = False self.skipTests = False @intelliprop def children(self): """All the direct children of this item.""" tests = [t for t in self._collection if t.parent is self] suites = [t for t in self._collection.suites if t.parent is self] return suites + tests @intelliprop def tests(self): """All the direct test children of this item.""" return [t for t in self._collection if t.parent is self] @property def suite(self): return self.item @property def runAfter(self): """The _run_after for this source.""" return self.namespace.get('_run_after', []) @property def postCheck(self): return self.namespace.get('postCheck', lambda : None) @property def setUp(self): return self.namespace.get('setUp', lambda : None) @property def postSetUp(self): return self.namespace.get('postSetUp', lambda : None) @property def tearDown(self): return self.namespace.get('tearDown', lambda : None) @property def suiteSetUp(self): return self.namespace.get('suiteSetUp', lambda : None) @property def suiteTearDown(self): return self.namespace.get('suiteTearDown', lambda : None) def getResult(self, name=None): runCount = 0 childStates = {} result = Result(PASS, NONE) if not self.children: result.state = NOT_RUN return result for c in self.children: state = c.state runCount += state is not NOT_RUN childStates[state] = None if FAIL in childStates: result.state = CHILD_FAIL elif CHILD_FAIL in childStates: result.state = CHILD_FAIL elif BAD_SETUP in childStates: result.state = CHILD_FAIL elif PART_RUN in childStates: result.state = PART_RUN elif NOT_RUN in childStates: if runCount: result.state = PART_RUN else: result.state = NOT_RUN return result @property def result(self): return self.getResult() @property def state(self): result = self.getResult() return result.reportCode def hasTests(self): for t in self._collection: if t.parent is self: return True class ModuleSuite(Suite): pass class ClassSuite(Suite): @property def klass(self): return self.item.__class__.__name__ <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class StepRecord: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @property def state(self): return self.result <|reserved_special_token_0|> <|reserved_special_token_0|> class StepRecordList: def __init__(self): self.entries = [] class RunRecord: """A set of records containing all information about a single test's run. This stores multiple `StepRecord` instances. The records are stored in a dictionary keyed by the following names: setUp, tearDown, prevTearDown, rn Each maps to a single `StepRecord`. suiteSetUp, suiteTearDown, prevSuiteTearDown Each mapping to a list of `StepRecord` instances, in execution order. """ _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split() _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split() _recordNames = _simpleNames + _listNames _runTime = None def __init__(self): self.runTime = RunRecord._runTime self.invalid = False self._records = {} self.extraInfo = {} def __setstate__(self, state): self.invalid = False self.__dict__.update(state) @classmethod def startNewRun(cls): cls._runTime = time.time() @classmethod def finishRun(cls): cls._runTime = None def addStepRecord(self, name): """Add a new phase record to this run record. Adds a new `StepRecord` for a test phase, which must be one of those defined for a `RunRecord`. :Parameters: name The name for the record. It must be the name of a defined test phase. :Return: The newly added `StepRecord` instance. This will always be a newly created instance. """ assert name in RunRecord._recordNames record = StepRecord() if name in RunRecord._simpleNames: assert name not in self._records self._records[name] = record else: if name not in self._records: self._records[name] = StepRecordList() self._records[name].entries.append(record) return record def getResult(self, name): pass @property def result(self): try: rec = self._records['setUp'] except KeyError: pass else: if rec.state is not PASS: result = Result(BAD_SETUP, BAD_SETUP) return result try: rec = self._records['run'] except KeyError: pass else: result = Result(rec.state, rec.reason) return result for rec in self._records.get('suiteSetUp', []): if rec.state is not PASS: return Result(NOT_RUN, BAD_SUITE_SETUP) try: rec = self._records['setUp'] except KeyError: pass else: if rec.state is not PASS: return Result(NOT_RUN, BAD_SETUP) return Result(NOT_RUN, NONE) @property def state(self): try: rec = self._records['setUp'] except KeyError: pass else: if rec.state is NOT_RUN: return NOT_RUN if rec.state not in (PASS, BUG, BUG_PASS): return BAD_SETUP try: rec = self._records['run'] return rec.state except KeyError: pass return NOT_RUN @property def isRunnable(self): for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'): try: if self._records[name].state not in (PASS, SKIPPED, NOT_RUN): return True except KeyError: pass return False @property def hasRunProblem(self): for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp', 'run', 'postCheck'): try: record = self._records[name] except KeyError: continue if name in ('tearDown', 'setUp', 'run', 'postCheck'): if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True else: for rec in record.entries: if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True return False @property def hasFailed(self): for name in ('suiteSetUp', 'setUp', 'run'): try: record = self._records[name] except KeyError: continue if name in ('setUp', 'run'): if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True else: for rec in record.entries: if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True return False @property def phaseRecord(self): """Get the most recent phaseRecord. This is used to get the most pertinent record for this test; i.e. the one that provides the most useful result for the test. TODO: This is not yet well defined. """ for name in ('tearDown', 'run', 'setUp'): try: return name, self._records[name] except KeyError: pass seq = self._records.get('suiteSetUp', None) if seq is None: return None, None for ent in seq.entries: if ent.hasFailed: return 'suiteSetUp', ent return 'suiteSetUp', seq.entries[0] def getStepRecord(self, phase): """Get the record details for a test run phase.""" ent = self._records.get(phase, None) if hasattr(ent, 'append'): seq = ent for ent in seq: if ent.hasFailed: return ent return seq.entries[0] if hasattr(ent, 'entries'): seq = ent.entries for ent in seq: if ent.hasFailed: return ent if seq: return seq[0] return return ent class TestItem: """Base class for `Test` and `Suite` classes. """ def __init__(self, item, uid, parentUid, context, namespace=None): """Constructor: :Parameters: item The concrete test item. For a test function/method this is the function/method itself. For a `ClassSuite` this is the instance and for a `ModuleSuite` this is the the module instance. uid The unique ID for this item, which is a tuple of strings. parentUid The unique ID of the parent item or ``None``. Only the root `Suite` of a test tree has a parent of ``None``. namespace A dictionary that provides the containing namespace for the test item. """ self.item = item self.uid = uid self.context = context self.parentUid = parentUid self.namespace = self._getNamespace(namespace) self._collection = None self._running = False self._marks = {} self.extraInfo = {} def setMark(self, mark): self._marks[mark] = None def clearMark(self, mark): if mark in self._marks: del self._marks[mark] def isMarked(self, mark): return mark in self._marks def setCollection(self, collection): self._collection = weakref.proxy(collection) def setPhase(self, phase): self._phase = phase @intelliprop def state(self): """The current state of the test. """ result = self.getResult() return result.state def setState(self, state): if state is PASS: pass @intelliprop def level(self): """This item's level in the test tree. This is the number of ancestors this item has. If zero then this is the 'root' item. """ return len(self.ancestors) @intelliprop def parent(self): """The parent of this item, which may be ``None``. If this is ``None`` then this item is the root of a (possibly nested) suite of tests. """ return self._collection.parent(self) @intelliprop def ancestors(self): """A list of all ancestors for this item. Each entry is a UID. The first entry is the oldest ancesctor and the last entry is the immediate parent's UID. """ return self._collection.getAncestors(self) def hasFailingAncestor(self): """Check if any ancestor is considered to have failed. An ancestor suite has failed if, for example, its ``suiteSetup`` failed. :Return: ``True`` if any ancestors has failed. """ parent = self.parent if parent is None: return return return parent.hasFailed or parent.hasFailingAncestor() def _getNamespace(self, namespace=None): return namespace or dict([(n, getattr(self.item, n)) for n in dir( self.item)]) @intelliprop def rawDoc(self): """The raw docstring, no cleaning up performed at all.""" return self.namespace['__doc__'] @intelliprop def docLines(self): """The docstring as lines. This is cleaned up to remove leading and trailing blank lines from the summary and details. :Return: A sequence of (non-nul terminated) lines for the docstring. The summary (if present) is separated from the details by a single empty line. """ summary, description = self._getDocParts() if description: return summary + [''] + description return summary @intelliprop def doc(self): """The docstring after being cleaned up. :Return: The cleaned up docstrinc as a multiline string. Leading and trailing blank lines are removed and the summary is separated from any details by a single blakn line. Common leading whitspace is also removed from each line. """ return '\n'.join(self.docLines) def _getDocParts(self): lines = self.rawDoc.splitlines() while lines and not lines[0].strip(): lines.pop(0) summary = [] while lines and lines[0].strip(): summary.append(lines.pop(0)) while lines and not lines[0].strip(): lines.pop(0) while lines and not lines[-1].strip(): lines.pop() summary = summary[:1] + dedentLines(summary[1:]) details = dedentLines(lines) return summary, details @property def summary(self): summary, description = self._getDocParts() return ' '.join(summary) @property def details(self): summary, description = self._getDocParts() return description @property def sourcesUnderTest(self): sources = [] for p in self.namespace.get('sources_under_test', []): if not os.path.isabs(p): p = os.path.abspath(os.path.join(self.dirname, p)) sources.append(p) p = self.parent if p is not None: sources.extend(p.sourcesUnderTest) return sources @property def klass(self): return None @property def path(self): p = self.namespace.get('__file__', None) if p is None: return self.parent.path if p.endswith('.pyc'): p = p[:-1] return p @property def dirname(self): f = self.path if f: return os.path.dirname(f) @property def isBug(self): return False class Test(TestItem): typeName = 'Test' isSuite = False amNull = False def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) self._runHistory = [] self.stopAll = False if self.func: self.func.cs_test_info.test = weakref.proxy(self) def getHistory(self): return self._runHistory def dumpHist(self): return self._runHistory[-1].dump() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() def addStepRecord(self, name): runRecord = self._runHistory[-1] return runRecord.addStepRecord(name) @property def postCheck(self): return self.parent.postCheck @intelliprop def hasFailed(self): """Check if this test has properly failed. :Return: ``True`` if the test has failed to run for any reason. """ record = self.getRunRecord().getRecord('run') return record.state is FAIL @property def klass(self): return self.parent.klass @property def funcName(self): return self.item.__name__ @property def func(self): return self.item @property def info(self): return self.func.cs_test_info @property def isBroken(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) flag = self.info.reserved_cs_flags.get('broken', None) if flag is None: flag = self.info.cs_flags.get('broken', False) return flag @property def isTodo(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) return self.info.cs_flags.get('todo', False) @property def isBug(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) flag = self.info.reserved_cs_flags.get('bug', None) if flag is None: flag = self.info.cs_flags.get('bug', False) return flag @property def shouldFork(self): if not hasattr(self, 'info'): raise PropertyError('%r has no attribute %r' % (self.__class__. __name__, 'info')) if self.info.reserved_cs_flags.get('fork', False): return True parent = self.parent try: return parent.suite.cs_attrs.fork_all except AttributeError: return False @property def testID(self): return self.info.cs_tags.get('testID', None) @property def title(self): return self.info.cs_flags.get('title', None) @property def isRunnable(self): if self.parent.exited: return False return True @property def state(self): rec = self.runRecord if rec: return rec.state return NOT_RUN @property def result(self): rec = self.runRecord if rec: return rec.result return NOT_RUN @property def hasRunProblem(self): rec = self.runRecord if rec: return rec.hasRunProblem return False @property def hasFailed(self): rec = self.runRecord if rec: return rec.hasFailed return False def addRunRecord(self, record): self._runHistory.append(record) if len(self._runHistory) > 5: self._runHistory[:] = self._runHistory[-5:] @property def runRecord(self): """The XXX TODO""" if self._runHistory: for rec in reversed(self._runHistory): if not rec.invalid: return rec @property def phaseRecord(self): """The XXX TODO""" if not self._runHistory: return None, None return self._runHistory[-1].phaseRecord def getStepRecord(self, phase): return self._runHistory[-1].getStepRecord(phase) def getTestProcedure(self): return self._collection.spec.getThing(self) class NullTest(Test): amNull = True def __init__(self): context = Context.getContext(dirPath=os.getcwd()) super(NullTest, self).__init__(None, None, None, context) self.number = 0 self.startNewRun() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() @property def isBug(self): return False def __bool__(self): return False class Suite(TestItem): typeName = 'Suite' isSuite = True def __init__(self, *args, **kwargs): self.myDir = kwargs.pop('myDir') super(Suite, self).__init__(*args, **kwargs) self.exited = False self.number = 0 self.skipTests = False self.entered = False def reset(self): self.entered = False self.skipTests = False @intelliprop def children(self): """All the direct children of this item.""" tests = [t for t in self._collection if t.parent is self] suites = [t for t in self._collection.suites if t.parent is self] return suites + tests @intelliprop def tests(self): """All the direct test children of this item.""" return [t for t in self._collection if t.parent is self] @property def suite(self): return self.item @property def runAfter(self): """The _run_after for this source.""" return self.namespace.get('_run_after', []) @property def postCheck(self): return self.namespace.get('postCheck', lambda : None) @property def setUp(self): return self.namespace.get('setUp', lambda : None) @property def postSetUp(self): return self.namespace.get('postSetUp', lambda : None) @property def tearDown(self): return self.namespace.get('tearDown', lambda : None) @property def suiteSetUp(self): return self.namespace.get('suiteSetUp', lambda : None) @property def suiteTearDown(self): return self.namespace.get('suiteTearDown', lambda : None) def getResult(self, name=None): runCount = 0 childStates = {} result = Result(PASS, NONE) if not self.children: result.state = NOT_RUN return result for c in self.children: state = c.state runCount += state is not NOT_RUN childStates[state] = None if FAIL in childStates: result.state = CHILD_FAIL elif CHILD_FAIL in childStates: result.state = CHILD_FAIL elif BAD_SETUP in childStates: result.state = CHILD_FAIL elif PART_RUN in childStates: result.state = PART_RUN elif NOT_RUN in childStates: if runCount: result.state = PART_RUN else: result.state = NOT_RUN return result @property def result(self): return self.getResult() @property def state(self): result = self.getResult() return result.reportCode def hasTests(self): for t in self._collection: if t.parent is self: return True class ModuleSuite(Suite): pass class ClassSuite(Suite): @property def klass(self): return self.item.__class__.__name__ <|reserved_special_token_0|> <|reserved_special_token_1|> """Those things that are core to tests. This module provides the most fundamental test entities, which include such things as: - Tests - Suites - Test states """ from __future__ import print_function __docformat__ = "restructuredtext" import os import textwrap import time import weakref import inspect from cleversheep3.Prog.Aspects import intelliprop from cleversheep3.Prog.Enum import Enum from cleversheep3.Test.Tester import Context from cleversheep3.Test.Tester import Coordinator from cleversheep3.Test.Tester import options State = Enum("State") # Static test states. NOT_RUN = State("NOT_RUN") PASS = State("PASS") FAIL = State("FAIL") SKIPPED = State("SKIPPED") BROKEN = State("BROKEN") DISABLED = State("DISABLED") BUG = State("BUG") BUG_PASS = State("BUG_PASS") TODO = State("TODO") # Dynamic test states. SET_UP = State("SET_UP") TEAR_DOWN = State("TEAR_DOWN") RUNNING = State("RUNNING") FINISHED = State("FINISHED") # TODO: To remove! # Suite specific states. CHILD_FAIL = State("CHILD_FAIL") PART_RUN = State("PART_RUN") # Reason codes. Note that this list is those codes that are only used as # reasons, some states are also used as reason code. NONE = State("NONE") ERROR = State("ERROR") BAD_SETUP = State("BAD_SETUP") BAD_SUITE_SETUP = State("BAD_SUITE_SETUP") EXIT_SUITE = State("EXIT_SUITE") EXIT_ALL = State("EXIT_ALL") USER_STOPPED = State("USER_STOPPED") def dedentLines(lines): return textwrap.dedent("\n".join(lines)).splitlines() class TestInfo: """Information about a test function. This class supports the ``@test(...)`` decorator that is used by cleversheep3 to mark test functions. All such marked functions are given an attribute called ``cs_test_info``, which is in an instance of this class. This is most commonly used in test filter functions, as registered by `addTestFilter`. When tests are marked using the ``@test`` decorator they can be given one or more tags and/or flags. Currently this is little more than a struct, except that it provides a `__getattr__` that returns ``None`` by default. """ def __init__(self, *args, **kwargs): """Constructor: :Parameters: args Non-keyword arguments are interpreted by the test framework. Each argument is a string. The supported forms are: plat:<platformType> The test will only be executed if ``<platformType>`` matches `Sys.Platform.platformType`. For example: ``"plat:windows"``. kwargs Any keyword arguments are simply stored as attributes. So, if you decorate a ``test_x`` with ``test(xyz=123)`` then ``test_x.cs_test_info.xyz`` will be ``123``. """ self.reserved_cs_flags = {} self.cs_flags = {} self.cs_tags = {} for arg in args: if ":" in arg: name, value = arg.split(":", 1) self.cs_flags[name] = value else: self.cs_flags[arg] = True for name in kwargs: if name.startswith("cs_"): self.reserved_cs_flags[name[3:]] = kwargs[name] else: self.cs_tags[name] = kwargs[name] self.reserved_cs_flags['defined_in_base'] = None def __getattr__(self, name): """Attribute access: Provides read access to test method tags. For example, if you mark a test:<py>: @test(abc="Hello") Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will be ``"Hello"``. If the test does not have ``abc`` set then the result is ``None``. """ if name in self.__dict__: return self.__dict__.get(name) return self.cs_tags.get(name, None) class Result: """Full result details for a test.""" def __init__(self, state, reason): self.state, self.reason = state, reason @property def reportCode(self): if self.reason is NONE: return self.state return self.reason class StepRecord: """A single record used to store informmation about the success or otherwise of a test phase. A test phase is one of: - A suite set-up/tear-down. - A test set-up/tear-down. - The execution of the test-method itself. :Ivariables: result TODO reason TODO """ def __init__(self, result=NOT_RUN, reason=NONE, details=None): self.result, self.reason = result, reason self.exc = None self.reported = False def setResult(self, state, reason=NONE, details=None): self._state, self._reason = state, reason self._details = details # TODO: Just transitional. @property def state(self): return self.result @property def hasFailed(self): return self.result in (FAIL, BAD_SETUP) def __str__(self): return "StepRecord: %s/%s" % (self.state, self.reason) class StepRecordList: def __init__(self): self.entries = [] class RunRecord: """A set of records containing all information about a single test's run. This stores multiple `StepRecord` instances. The records are stored in a dictionary keyed by the following names: setUp, tearDown, prevTearDown, rn Each maps to a single `StepRecord`. suiteSetUp, suiteTearDown, prevSuiteTearDown Each mapping to a list of `StepRecord` instances, in execution order. """ _simpleNames = """setUp tearDown prevTearDown run postCheck""".split() _listNames = """suiteSetUp suiteTearDown prevSuiteTearDown""".split() _recordNames = _simpleNames + _listNames _runTime = None def __init__(self): #assert RunRecord._runTime is not None self.runTime = RunRecord._runTime self.invalid = False self._records = {} self.extraInfo = {} def __setstate__(self, state): self.invalid = False self.__dict__.update(state) @classmethod def startNewRun(cls): cls._runTime = time.time() @classmethod def finishRun(cls): cls._runTime = None def addStepRecord(self, name): """Add a new phase record to this run record. Adds a new `StepRecord` for a test phase, which must be one of those defined for a `RunRecord`. :Parameters: name The name for the record. It must be the name of a defined test phase. :Return: The newly added `StepRecord` instance. This will always be a newly created instance. """ assert name in RunRecord._recordNames record = StepRecord() if name in RunRecord._simpleNames: assert name not in self._records self._records[name] = record else: if name not in self._records: self._records[name] = StepRecordList() self._records[name].entries.append(record) return record def getResult(self, name): pass @property def result(self): # Is set-up failed then we report that as bad setup. try: rec = self._records["setUp"] except KeyError: pass else: if rec.state is not PASS: result = Result(BAD_SETUP, BAD_SETUP) return result # See if the test was actually executed. try: rec = self._records["run"] except KeyError: pass else: result = Result(rec.state, rec.reason) return result # Test was not run, so we need to find out why. A suite set-up # failure means we consider the test not-run. for rec in self._records.get("suiteSetUp", []): if rec.state is not PASS: return Result(NOT_RUN, BAD_SUITE_SETUP) try: rec = self._records["setUp"] except KeyError: pass else: if rec.state is not PASS: return Result(NOT_RUN, BAD_SETUP) return Result(NOT_RUN, NONE) @property def state(self): # If set-up failed then we report that as bad setup. try: rec = self._records["setUp"] except KeyError: pass else: if rec.state is NOT_RUN: return NOT_RUN if rec.state not in (PASS, BUG, BUG_PASS): return BAD_SETUP # If the test has a 'run' entry then that defines the state. try: rec = self._records["run"] #if rec.state is NOT_RUN: # return RUNNING return rec.state except KeyError: pass # Otherwise the state is not-run. return NOT_RUN @property def isRunnable(self): for name in ("suiteTearDown", "tearDown", "suiteSetUp", "setUp"): try: if self._records[name].state not in (PASS, SKIPPED, NOT_RUN): return True except KeyError: pass return False @property def hasRunProblem(self): for name in ("tearDown", "suiteTearDown", "suiteSetUp", "setUp", "run", "postCheck"): try: record = self._records[name] except KeyError: continue if name in ("tearDown", "setUp", "run", "postCheck"): if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True else: for rec in record.entries: if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True return False @property def hasFailed(self): for name in ("suiteSetUp", "setUp", "run"): try: record = self._records[name] except KeyError: continue if name in ("setUp", "run"): if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True else: for rec in record.entries: if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True return False @property def phaseRecord(self): """Get the most recent phaseRecord. This is used to get the most pertinent record for this test; i.e. the one that provides the most useful result for the test. TODO: This is not yet well defined. """ for name in ("tearDown", "run", "setUp"): try: return name, self._records[name] except KeyError: pass #return None, None seq = self._records.get("suiteSetUp", None) if seq is None: return None, None for ent in seq.entries: if ent.hasFailed: return "suiteSetUp", ent return "suiteSetUp", seq.entries[0] def getStepRecord(self, phase): """Get the record details for a test run phase.""" ent = self._records.get(phase, None) if hasattr(ent, "append"): # Yurk! seq = ent for ent in seq: if ent.hasFailed: return ent return seq.entries[0] if hasattr(ent, "entries"): # Double yurk! seq = ent.entries for ent in seq: if ent.hasFailed: return ent if seq: return seq[0] return return ent class TestItem: """Base class for `Test` and `Suite` classes. """ def __init__(self, item, uid, parentUid, context, namespace=None): """Constructor: :Parameters: item The concrete test item. For a test function/method this is the function/method itself. For a `ClassSuite` this is the instance and for a `ModuleSuite` this is the the module instance. uid The unique ID for this item, which is a tuple of strings. parentUid The unique ID of the parent item or ``None``. Only the root `Suite` of a test tree has a parent of ``None``. namespace A dictionary that provides the containing namespace for the test item. """ self.item = item self.uid = uid self.context = context self.parentUid = parentUid self.namespace = self._getNamespace(namespace) self._collection = None self._running = False self._marks = {} self.extraInfo = {} def setMark(self, mark): self._marks[mark] = None def clearMark(self, mark): if mark in self._marks: del self._marks[mark] def isMarked(self, mark): return mark in self._marks def setCollection(self, collection): self._collection = weakref.proxy(collection) # TODO: To remove. def setPhase(self, phase): self._phase = phase @intelliprop def state(self): """The current state of the test. """ result = self.getResult() return result.state def setState(self, state): if state is PASS: pass @intelliprop def level(self): """This item's level in the test tree. This is the number of ancestors this item has. If zero then this is the 'root' item. """ return len(self.ancestors) @intelliprop def parent(self): """The parent of this item, which may be ``None``. If this is ``None`` then this item is the root of a (possibly nested) suite of tests. """ return self._collection.parent(self) @intelliprop def ancestors(self): """A list of all ancestors for this item. Each entry is a UID. The first entry is the oldest ancesctor and the last entry is the immediate parent's UID. """ return self._collection.getAncestors(self) def hasFailingAncestor(self): """Check if any ancestor is considered to have failed. An ancestor suite has failed if, for example, its ``suiteSetup`` failed. :Return: ``True`` if any ancestors has failed. """ parent = self.parent if parent is None: return # TODO: Temporarily disabled. return return parent.hasFailed or parent.hasFailingAncestor() def _getNamespace(self, namespace=None): return namespace or dict([(n, getattr(self.item, n)) for n in dir(self.item)]) @intelliprop def rawDoc(self): """The raw docstring, no cleaning up performed at all.""" return self.namespace["__doc__"] @intelliprop def docLines(self): """The docstring as lines. This is cleaned up to remove leading and trailing blank lines from the summary and details. :Return: A sequence of (non-nul terminated) lines for the docstring. The summary (if present) is separated from the details by a single empty line. """ summary, description = self._getDocParts() if description: return summary + [""] + description return summary @intelliprop def doc(self): """The docstring after being cleaned up. :Return: The cleaned up docstrinc as a multiline string. Leading and trailing blank lines are removed and the summary is separated from any details by a single blakn line. Common leading whitspace is also removed from each line. """ return "\n".join(self.docLines) def _getDocParts(self): # Lose leading blank lines. lines = self.rawDoc.splitlines() while lines and not lines[0].strip(): lines.pop(0) # All lines up to next blank line are the summary. summary = [] while lines and lines[0].strip(): summary.append(lines.pop(0)) # Strip leading and trailing blank lines from the remaining details. while lines and not lines[0].strip(): lines.pop(0) while lines and not lines[-1].strip(): lines.pop() # Dedent the summary and details before returning them. summary = summary[:1] + dedentLines(summary[1:]) details = dedentLines(lines) return summary, details @property def summary(self): summary, description = self._getDocParts() return " ".join(summary) @property def details(self): summary, description = self._getDocParts() return description @property def sourcesUnderTest(self): sources = [] for p in self.namespace.get("sources_under_test", []): if not os.path.isabs(p): p = os.path.abspath(os.path.join(self.dirname, p)) sources.append(p) p = self.parent if p is not None: sources.extend(p.sourcesUnderTest) return sources @property def klass(self): return None @property def path(self): p = self.namespace.get("__file__", None) if p is None: return self.parent.path if p.endswith(".pyc"): p = p[:-1] return p @property def dirname(self): f = self.path if f: return os.path.dirname(f) @property def isBug(self): return False class Test(TestItem): typeName = "Test" isSuite = False amNull = False def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) self._runHistory = [] self.stopAll = False if self.func: self.func.cs_test_info.test = weakref.proxy(self) def getHistory(self): return self._runHistory def dumpHist(self): return self._runHistory[-1].dump() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() def addStepRecord(self, name): runRecord = self._runHistory[-1] return runRecord.addStepRecord(name) @property def postCheck(self): return self.parent.postCheck @intelliprop def hasFailed(self): """Check if this test has properly failed. :Return: ``True`` if the test has failed to run for any reason. """ record = self.getRunRecord().getRecord("run") return record.state is FAIL @property def klass(self): return self.parent.klass @property def funcName(self): return self.item.__name__ @property def func(self): return self.item @property def info(self): return self.func.cs_test_info @property def isBroken(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) flag = self.info.reserved_cs_flags.get("broken", None) if flag is None: flag = self.info.cs_flags.get("broken", False) # deprecated return flag @property def isTodo(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) return self.info.cs_flags.get("todo", False) @property def isBug(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) flag = self.info.reserved_cs_flags.get("bug", None) if flag is None: flag = self.info.cs_flags.get("bug", False) # deprecated return flag @property def shouldFork(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) if self.info.reserved_cs_flags.get("fork", False): return True parent = self.parent try: return parent.suite.cs_attrs.fork_all except AttributeError: return False @property def testID(self): return self.info.cs_tags.get("testID", None) @property def title(self): return self.info.cs_flags.get("title", None) @property def isRunnable(self): #if self.isBroken and not options.no_disabled: # return False if self.parent.exited: return False return True @property def state(self): rec = self.runRecord if rec: return rec.state return NOT_RUN @property def result(self): rec = self.runRecord if rec: return rec.result return NOT_RUN @property def hasRunProblem(self): rec = self.runRecord if rec: return rec.hasRunProblem return False @property def hasFailed(self): rec = self.runRecord if rec: return rec.hasFailed return False def addRunRecord(self, record): self._runHistory.append(record) if len(self._runHistory) > 5: self._runHistory[:] = self._runHistory[-5:] @property def runRecord(self): """The XXX TODO""" if self._runHistory: for rec in reversed(self._runHistory): if not rec.invalid: return rec # TODO: Should now be StepRecord. @property def phaseRecord(self): """The XXX TODO""" if not self._runHistory: return None, None return self._runHistory[-1].phaseRecord def getStepRecord(self, phase): return self._runHistory[-1].getStepRecord(phase) def getTestProcedure(self): return self._collection.spec.getThing(self) class NullTest(Test): amNull = True def __init__(self): context = Context.getContext(dirPath=os.getcwd()) super(NullTest, self).__init__(None, None, None, context) self.number = 0 self.startNewRun() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() @property def isBug(self): return False def __bool__(self): return False class Suite(TestItem): typeName = "Suite" isSuite = True def __init__(self, *args, **kwargs): self.myDir = kwargs.pop("myDir") super(Suite, self).__init__(*args, **kwargs) self.exited = False self.number = 0 self.skipTests = False self.entered = False def reset(self): self.entered = False self.skipTests = False @intelliprop def children(self): """All the direct children of this item.""" tests = [t for t in self._collection if t.parent is self] suites = [t for t in self._collection.suites if t.parent is self] return suites + tests @intelliprop def tests(self): """All the direct test children of this item.""" return [t for t in self._collection if t.parent is self] @property def suite(self): return self.item @property def runAfter(self): """The _run_after for this source.""" return self.namespace.get("_run_after", []) @property def postCheck(self): return self.namespace.get("postCheck", lambda: None) @property def setUp(self): return self.namespace.get("setUp", lambda: None) @property def postSetUp(self): return self.namespace.get("postSetUp", lambda: None) @property def tearDown(self): return self.namespace.get("tearDown", lambda: None) @property def suiteSetUp(self): return self.namespace.get("suiteSetUp", lambda: None) @property def suiteTearDown(self): return self.namespace.get("suiteTearDown", lambda: None) def getResult(self, name=None): runCount = 0 childStates = {} result = Result(PASS, NONE) if not self.children: result.state = NOT_RUN return result for c in self.children: state = c.state runCount += state is not NOT_RUN childStates[state] = None if FAIL in childStates: result.state = CHILD_FAIL elif CHILD_FAIL in childStates: result.state = CHILD_FAIL elif BAD_SETUP in childStates: result.state = CHILD_FAIL elif PART_RUN in childStates: result.state = PART_RUN elif NOT_RUN in childStates: if runCount: result.state = PART_RUN else: result.state = NOT_RUN return result @property def result(self): return self.getResult() @property def state(self): result = self.getResult() return result.reportCode def hasTests(self): # Deprecated. Only used for old reporter support. for t in self._collection: if t.parent is self: return True class ModuleSuite(Suite): pass class ClassSuite(Suite): @property def klass(self): return self.item.__class__.__name__ def enter_pdb(): """Enter the python debugger.""" import sys, pdb sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__ pdb.set_trace()
flexible
{ "blob_id": "cac9d84f20a79b115c84ff4fe8cf4640182a42d7", "index": 754, "step-1": "<mask token>\n\n\nclass Test(TestItem):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def abortRun(self):\n self._runHistory.pop()\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def funcName(self):\n return self.item.__name__\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <mask token>\n <mask token>\n <mask token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestItem:\n <mask token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n <mask token>\n <mask token>\n\n def isMarked(self, mark):\n return mark in self._marks\n <mask token>\n <mask token>\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <mask token>\n <mask token>\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TestItem:\n <mask token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <mask token>\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n <mask token>\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass StepRecord:\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def state(self):\n return self.result\n <mask token>\n <mask token>\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n", "step-5": "\"\"\"Those things that are core to tests.\n\nThis module provides the most fundamental test entities, which include such\nthings as:\n\n- Tests\n- Suites\n- Test states\n\n\"\"\"\nfrom __future__ import print_function\n__docformat__ = \"restructuredtext\"\n\nimport os\nimport textwrap\nimport time\nimport weakref\nimport inspect\n\nfrom cleversheep3.Prog.Aspects import intelliprop\nfrom cleversheep3.Prog.Enum import Enum\n\nfrom cleversheep3.Test.Tester import Context\nfrom cleversheep3.Test.Tester import Coordinator\nfrom cleversheep3.Test.Tester import options\n\nState = Enum(\"State\")\n\n# Static test states.\nNOT_RUN = State(\"NOT_RUN\")\nPASS = State(\"PASS\")\nFAIL = State(\"FAIL\")\nSKIPPED = State(\"SKIPPED\")\nBROKEN = State(\"BROKEN\")\nDISABLED = State(\"DISABLED\")\nBUG = State(\"BUG\")\nBUG_PASS = State(\"BUG_PASS\")\nTODO = State(\"TODO\")\n\n# Dynamic test states.\nSET_UP = State(\"SET_UP\")\nTEAR_DOWN = State(\"TEAR_DOWN\")\nRUNNING = State(\"RUNNING\")\nFINISHED = State(\"FINISHED\") # TODO: To remove!\n\n# Suite specific states.\nCHILD_FAIL = State(\"CHILD_FAIL\")\nPART_RUN = State(\"PART_RUN\")\n\n# Reason codes. Note that this list is those codes that are only used as\n# reasons, some states are also used as reason code.\nNONE = State(\"NONE\")\nERROR = State(\"ERROR\")\nBAD_SETUP = State(\"BAD_SETUP\")\nBAD_SUITE_SETUP = State(\"BAD_SUITE_SETUP\")\nEXIT_SUITE = State(\"EXIT_SUITE\")\nEXIT_ALL = State(\"EXIT_ALL\")\nUSER_STOPPED = State(\"USER_STOPPED\")\n\ndef dedentLines(lines):\n return textwrap.dedent(\"\\n\".join(lines)).splitlines()\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if \":\" in arg:\n name, value = arg.split(\":\", 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n\n for name in kwargs:\n if name.startswith(\"cs_\"):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n # TODO: Just transitional.\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return \"StepRecord: %s/%s\" % (self.state, self.reason)\n\n\nclass StepRecordList:\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = \"\"\"setUp tearDown prevTearDown run postCheck\"\"\".split()\n _listNames = \"\"\"suiteSetUp suiteTearDown prevSuiteTearDown\"\"\".split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n #assert RunRecord._runTime is not None\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n # Is set-up failed then we report that as bad setup.\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n\n # See if the test was actually executed.\n try:\n rec = self._records[\"run\"]\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n\n # Test was not run, so we need to find out why. A suite set-up\n # failure means we consider the test not-run.\n for rec in self._records.get(\"suiteSetUp\", []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n # If set-up failed then we report that as bad setup.\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n\n # If the test has a 'run' entry then that defines the state.\n try:\n rec = self._records[\"run\"]\n #if rec.state is NOT_RUN:\n # return RUNNING\n return rec.state\n except KeyError:\n pass\n\n # Otherwise the state is not-run.\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in (\"suiteTearDown\", \"tearDown\", \"suiteSetUp\", \"setUp\"):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n\n return False\n\n @property\n def hasRunProblem(self):\n for name in (\"tearDown\", \"suiteTearDown\", \"suiteSetUp\", \"setUp\",\n \"run\", \"postCheck\"):\n try:\n record = self._records[name]\n except KeyError:\n continue\n\n if name in (\"tearDown\", \"setUp\", \"run\", \"postCheck\"):\n if record.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n\n return False\n\n @property\n def hasFailed(self):\n for name in (\"suiteSetUp\", \"setUp\", \"run\"):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in (\"setUp\", \"run\"):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in (\"tearDown\", \"run\", \"setUp\"):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n #return None, None\n seq = self._records.get(\"suiteSetUp\", None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return \"suiteSetUp\", ent\n return \"suiteSetUp\", seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, \"append\"): # Yurk!\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, \"entries\"): # Double yurk!\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n # TODO: To remove.\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n # TODO: Temporarily disabled.\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n))\n for n in dir(self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace[\"__doc__\"]\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [\"\"] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return \"\\n\".join(self.docLines)\n\n def _getDocParts(self):\n # Lose leading blank lines.\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n\n # All lines up to next blank line are the summary.\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n\n # Strip leading and trailing blank lines from the remaining details.\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n\n # Dedent the summary and details before returning them.\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return \" \".join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get(\"sources_under_test\", []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get(\"__file__\", None)\n if p is None:\n return self.parent.path\n if p.endswith(\".pyc\"):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = \"Test\"\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord(\"run\")\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n flag = self.info.reserved_cs_flags.get(\"broken\", None)\n if flag is None:\n flag = self.info.cs_flags.get(\"broken\", False) # deprecated\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n return self.info.cs_flags.get(\"todo\", False)\n\n @property\n def isBug(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n flag = self.info.reserved_cs_flags.get(\"bug\", None)\n if flag is None:\n flag = self.info.cs_flags.get(\"bug\", False) # deprecated\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n if self.info.reserved_cs_flags.get(\"fork\", False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get(\"testID\", None)\n\n @property\n def title(self):\n return self.info.cs_flags.get(\"title\", None)\n\n @property\n def isRunnable(self):\n #if self.isBroken and not options.no_disabled:\n # return False\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n # TODO: Should now be StepRecord.\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = \"Suite\"\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop(\"myDir\")\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get(\"_run_after\", [])\n\n @property\n def postCheck(self):\n return self.namespace.get(\"postCheck\", lambda: None)\n\n @property\n def setUp(self):\n return self.namespace.get(\"setUp\", lambda: None)\n\n @property\n def postSetUp(self):\n return self.namespace.get(\"postSetUp\", lambda: None)\n\n @property\n def tearDown(self):\n return self.namespace.get(\"tearDown\", lambda: None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get(\"suiteSetUp\", lambda: None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get(\"suiteTearDown\", lambda: None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n # Deprecated. Only used for old reporter support.\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\ndef enter_pdb():\n \"\"\"Enter the python debugger.\"\"\"\n import sys, pdb\n sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__\n pdb.set_trace()\n", "step-ids": [ 33, 64, 81, 104, 122 ] }
[ 33, 64, 81, 104, 122 ]
<|reserved_special_token_0|> class UDPProtocol: <|reserved_special_token_0|> def connection_made(self, transport): self.transport = transport <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def stop(self): self.transport.close() <|reserved_special_token_1|> <|reserved_special_token_0|> class UDPProtocol: def __init__(self, consumer): self.consumer = consumer self.transport = None def connection_made(self, transport): self.transport = transport def connection_lost(self, exc): pass <|reserved_special_token_0|> <|reserved_special_token_0|> def stop(self): self.transport.close() <|reserved_special_token_1|> <|reserved_special_token_0|> if CONFIRMATION: CONFIRMATION = CONFIRMATION.encode() class UDPProtocol: def __init__(self, consumer): self.consumer = consumer self.transport = None def connection_made(self, transport): self.transport = transport def connection_lost(self, exc): pass def datagram_received(self, packet, address): self.consumer.consume_packet(packet) if CONFIRMATION: self.transport.sendto(CONFIRMATION, address) def start(self): loop = self.consumer.loop coroutine = loop.create_datagram_endpoint(lambda : self, LISTEN_ADDRESS, reuse_port=True) loop.run_until_complete(coroutine) def stop(self): self.transport.close() <|reserved_special_token_1|> <|reserved_special_token_0|> LISTEN_IP = getenv('LISTEN_IP', '0.0.0.0') LISTEN_PORT = int(getenv('LISTEN_PORT', 51273)) LISTEN_ADDRESS = LISTEN_IP, LISTEN_PORT CONFIRMATION = getenv('CONFIRMATION') if CONFIRMATION: CONFIRMATION = CONFIRMATION.encode() class UDPProtocol: def __init__(self, consumer): self.consumer = consumer self.transport = None def connection_made(self, transport): self.transport = transport def connection_lost(self, exc): pass def datagram_received(self, packet, address): self.consumer.consume_packet(packet) if CONFIRMATION: self.transport.sendto(CONFIRMATION, address) def start(self): loop = self.consumer.loop coroutine = loop.create_datagram_endpoint(lambda : self, LISTEN_ADDRESS, reuse_port=True) loop.run_until_complete(coroutine) def stop(self): self.transport.close() <|reserved_special_token_1|> from os import getenv LISTEN_IP = getenv('LISTEN_IP', '0.0.0.0') LISTEN_PORT = int(getenv('LISTEN_PORT', 51273)) LISTEN_ADDRESS = LISTEN_IP, LISTEN_PORT CONFIRMATION = getenv('CONFIRMATION') if CONFIRMATION: CONFIRMATION = CONFIRMATION.encode() class UDPProtocol: def __init__(self, consumer): self.consumer = consumer self.transport = None def connection_made(self, transport): self.transport = transport def connection_lost(self, exc): pass def datagram_received(self, packet, address): # WARNING: some kind of filtering should be there for the real app self.consumer.consume_packet(packet) if CONFIRMATION: self.transport.sendto(CONFIRMATION, address) def start(self): loop = self.consumer.loop coroutine = loop.create_datagram_endpoint(lambda: self, LISTEN_ADDRESS, reuse_port=True) loop.run_until_complete(coroutine) def stop(self): self.transport.close()
flexible
{ "blob_id": "cca543f461724c3aac8fef23ef648883962bd706", "index": 4607, "step-1": "<mask token>\n\n\nclass UDPProtocol:\n <mask token>\n\n def connection_made(self, transport):\n self.transport = transport\n <mask token>\n <mask token>\n <mask token>\n\n def stop(self):\n self.transport.close()\n", "step-2": "<mask token>\n\n\nclass UDPProtocol:\n\n def __init__(self, consumer):\n self.consumer = consumer\n self.transport = None\n\n def connection_made(self, transport):\n self.transport = transport\n\n def connection_lost(self, exc):\n pass\n <mask token>\n <mask token>\n\n def stop(self):\n self.transport.close()\n", "step-3": "<mask token>\nif CONFIRMATION:\n CONFIRMATION = CONFIRMATION.encode()\n\n\nclass UDPProtocol:\n\n def __init__(self, consumer):\n self.consumer = consumer\n self.transport = None\n\n def connection_made(self, transport):\n self.transport = transport\n\n def connection_lost(self, exc):\n pass\n\n def datagram_received(self, packet, address):\n self.consumer.consume_packet(packet)\n if CONFIRMATION:\n self.transport.sendto(CONFIRMATION, address)\n\n def start(self):\n loop = self.consumer.loop\n coroutine = loop.create_datagram_endpoint(lambda : self,\n LISTEN_ADDRESS, reuse_port=True)\n loop.run_until_complete(coroutine)\n\n def stop(self):\n self.transport.close()\n", "step-4": "<mask token>\nLISTEN_IP = getenv('LISTEN_IP', '0.0.0.0')\nLISTEN_PORT = int(getenv('LISTEN_PORT', 51273))\nLISTEN_ADDRESS = LISTEN_IP, LISTEN_PORT\nCONFIRMATION = getenv('CONFIRMATION')\nif CONFIRMATION:\n CONFIRMATION = CONFIRMATION.encode()\n\n\nclass UDPProtocol:\n\n def __init__(self, consumer):\n self.consumer = consumer\n self.transport = None\n\n def connection_made(self, transport):\n self.transport = transport\n\n def connection_lost(self, exc):\n pass\n\n def datagram_received(self, packet, address):\n self.consumer.consume_packet(packet)\n if CONFIRMATION:\n self.transport.sendto(CONFIRMATION, address)\n\n def start(self):\n loop = self.consumer.loop\n coroutine = loop.create_datagram_endpoint(lambda : self,\n LISTEN_ADDRESS, reuse_port=True)\n loop.run_until_complete(coroutine)\n\n def stop(self):\n self.transport.close()\n", "step-5": "from os import getenv\n\n\nLISTEN_IP = getenv('LISTEN_IP', '0.0.0.0')\nLISTEN_PORT = int(getenv('LISTEN_PORT', 51273))\nLISTEN_ADDRESS = LISTEN_IP, LISTEN_PORT\n\nCONFIRMATION = getenv('CONFIRMATION')\nif CONFIRMATION:\n CONFIRMATION = CONFIRMATION.encode()\n\n\nclass UDPProtocol:\n\n def __init__(self, consumer):\n self.consumer = consumer\n self.transport = None\n\n def connection_made(self, transport):\n self.transport = transport\n\n def connection_lost(self, exc):\n pass\n\n def datagram_received(self, packet, address):\n # WARNING: some kind of filtering should be there for the real app\n self.consumer.consume_packet(packet)\n\n if CONFIRMATION:\n self.transport.sendto(CONFIRMATION, address)\n\n def start(self):\n loop = self.consumer.loop\n coroutine = loop.create_datagram_endpoint(lambda: self, LISTEN_ADDRESS,\n reuse_port=True)\n loop.run_until_complete(coroutine)\n\n def stop(self):\n self.transport.close()\n", "step-ids": [ 3, 5, 8, 9, 11 ] }
[ 3, 5, 8, 9, 11 ]